Exemplo n.º 1
0
        public bool IsNotaFiscalValida(NotaFiscal notaFiscal, string cscId, string csc)
        {
            string qrCode = "";

            string refUri           = "#NFe" + notaFiscal.Identificacao.Chave;
            string digVal           = "";
            string nFeNamespaceName = "http://www.portalfiscal.inf.br/nfe";

            X509Certificate2 certificado;

            var certificadoEntity = new CertificadoRepository(new NFeContext()).GetCertificado();

            if (!string.IsNullOrWhiteSpace(certificadoEntity.Caminho))
            {
                certificado = CertificateManager.GetCertificateByPath(certificadoEntity.Caminho,
                                                                      RijndaelManagedEncryption.DecryptRijndael(certificadoEntity.Senha));
            }
            else
            {
                certificado = CertificateManager.GetCertificateBySerialNumber(certificadoEntity.NumeroSerial, false);
            }

            var     xml  = Regex.Replace(XmlUtil.GerarXmlLoteNFe(notaFiscal, nFeNamespaceName), "<motDesICMS>1</motDesICMS>", string.Empty);;
            XmlNode node = AssinaturaDigital.AssinarLoteComUmaNota(xml, refUri, certificado, ref digVal);

            TNFe   nfe        = null;
            string newNodeXml = string.Empty;

            try
            {
                var codigoUF = (CodigoUfIbge)Enum.Parse(typeof(CodigoUfIbge), notaFiscal.Emitente.Endereco.UF);

                if (notaFiscal.Identificacao.Modelo == Modelo.Modelo65)
                {
                    qrCode = QrCodeUtil.GerarQrCodeNFe(notaFiscal.Identificacao.Chave, notaFiscal.Destinatario, digVal, notaFiscal.Identificacao.Ambiente,
                                                       notaFiscal.Identificacao.DataHoraEmissao, notaFiscal.TotalNFe.IcmsTotal.ValorTotalNFe.ToString("F", CultureInfo.InvariantCulture),
                                                       notaFiscal.TotalNFe.IcmsTotal.ValorTotalIcms.ToString("F", CultureInfo.InvariantCulture), cscId, csc, notaFiscal.Identificacao.TipoEmissao);

                    newNodeXml = node.InnerXml.Replace("<qrCode />", "<qrCode>" + qrCode + "</qrCode>");
                }
                else
                {
                    newNodeXml = node.InnerXml;
                }

                var document = new XmlDocument();
                document.LoadXml(newNodeXml);
                node = document.DocumentElement;

                TEnviNFe lote = (TEnviNFe)XmlUtil.Deserialize <TEnviNFe>(node.OuterXml);
                nfe = lote.NFe[0];

                ValidadorXml.ValidarXml(node.OuterXml, "enviNFe_v4.00.xsd");

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Exemplo n.º 2
0
        /** <exception cref="Exception"/>
         * <summary>Responsável pelo envio da Nota Fiscal para a SEFAZ.</summary>
         */
        internal async Task <int> EnviarNotaFiscalAsync(NotaFiscal notaFiscal, string cscId, string csc)
        {
            string           qrCode               = "";
            TNFe             nfe                  = null;
            string           newNodeXml           = string.Empty;
            int              idNotaCopiaSeguranca = 0;
            NotaFiscalEntity notaFiscalEntity     = null;

            string refUri           = "#NFe" + notaFiscal.Identificacao.Chave;
            string digVal           = "";
            string nFeNamespaceName = "http://www.portalfiscal.inf.br/nfe";

            X509Certificate2 certificado;

            var certificadoEntity = new CertificadoRepository(new NFeContext()).GetCertificado();

            certificado = EscolherCertificado(certificadoEntity);

            var     xml  = Regex.Replace(XmlUtil.GerarXmlLoteNFe(notaFiscal, nFeNamespaceName), "<motDesICMS>1</motDesICMS>", string.Empty);
            XmlNode node = AssinaturaDigital.AssinarLoteComUmaNota(xml, refUri, certificado, ref digVal);

            try
            {
                var codigoUF = (CodigoUfIbge)Enum.Parse(typeof(CodigoUfIbge), notaFiscal.Emitente.Endereco.UF);

                if (notaFiscal.Identificacao.Modelo == Modelo.Modelo65)
                {
                    //NFC-e tem QrCode obrigatório
                    qrCode = QrCodeUtil.GerarQrCodeNFe(notaFiscal.Identificacao.Chave, notaFiscal.Destinatario, digVal, notaFiscal.Identificacao.Ambiente,
                                                       notaFiscal.Identificacao.DataHoraEmissao, notaFiscal.TotalNFe.IcmsTotal.ValorTotalNFe.ToString("F", CultureInfo.InvariantCulture),
                                                       notaFiscal.TotalNFe.IcmsTotal.ValorTotalIcms.ToString("F", CultureInfo.InvariantCulture), cscId, csc, notaFiscal.Identificacao.TipoEmissao);

                    newNodeXml = node.InnerXml.Replace("<qrCode />", "<qrCode>" + qrCode + "</qrCode>");
                }
                else
                {
                    newNodeXml = node.InnerXml;
                }

                var document = new XmlDocument();
                document.LoadXml(newNodeXml);
                node = document.DocumentElement;

                TEnviNFe lote = (TEnviNFe)XmlUtil.Deserialize <TEnviNFe>(node.OuterXml);
                nfe = lote.NFe[0];

                var servico = ServiceFactory.GetService(notaFiscal.Identificacao.Modelo, notaFiscal.Identificacao.Ambiente, Factory.Servico.AUTORIZACAO, codigoUF, certificado);
                var client  = (NFeAutorizacao4.NFeAutorizacao4SoapClient)servico.SoapClient;

                //salvar nota PreEnvio aqui
                notaFiscal.Identificacao.Status = NFe.Repository.Status.PENDENTE;

                var notaFiscalService = new NotaFiscalService();

                idNotaCopiaSeguranca = await notaFiscalService.SalvarNotaFiscalPendenteAsync(notaFiscal, XmlUtil.GerarNfeProcXml(nfe, qrCode), notaFiscal.Identificacao.Ambiente);

                XmlNode     result  = client.nfeAutorizacaoLote(node);
                TRetEnviNFe retorno = (TRetEnviNFe)XmlUtil.Deserialize <TRetEnviNFe>(result.OuterXml);
                XmlSchemas.NfeAutorizacao.Retorno.TProtNFe protocolo = (XmlSchemas.NfeAutorizacao.Retorno.TProtNFe)retorno.Item; //existem dois valores possíveis de retorno (esse aqui só vale para lote com 1 nota)

                if (protocolo.infProt.cStat.Equals("100"))
                {
                    notaFiscalEntity = await notaFiscalService.GetNotaFiscalByIdAsync(idNotaCopiaSeguranca, false);

                    notaFiscalEntity.Status          = (int)Status.ENVIADA;
                    notaFiscalEntity.DataAutorizacao = DateTime.ParseExact(protocolo.infProt.dhRecbto, "yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture);

                    notaFiscalEntity.Protocolo = protocolo.infProt.nProt;
                    string xmlNFeProc = XmlUtil.GerarNfeProcXml(nfe, qrCode, protocolo);

                    await notaFiscalService.SalvarAsync(notaFiscalEntity, xmlNFeProc);
                }
                else
                {
                    if (protocolo.infProt.xMotivo.Contains("Duplicidade"))
                    {
                        notaFiscalEntity = await CorrigirNotaDuplicada(notaFiscal, qrCode, nFeNamespaceName, certificado, nfe, idNotaCopiaSeguranca, notaFiscalEntity);
                    }
                    else
                    {
                        //Nota continua com status pendente nesse caso
                        XmlUtil.SalvarXmlNFeComErro(notaFiscal, node);
                        string mensagem = string.Concat("O xml informado é inválido de acordo com o validar da SEFAZ. Nota Fiscal não enviada!", "\n", protocolo.infProt.xMotivo);
                        throw new ArgumentException(mensagem);
                    }
                }

                notaFiscal.QrCodeUrl            = qrCode;
                notaFiscal.Identificacao.Status = Status.ENVIADA;
                notaFiscal.DhAutorizacao        = notaFiscalEntity.DataAutorizacao.ToString("dd/MM/yyyy HH:mm:ss");
                notaFiscal.DataHoraAutorização  = notaFiscalEntity.DataAutorizacao;
                notaFiscal.ProtocoloAutorizacao = notaFiscalEntity.Protocolo;
                return(idNotaCopiaSeguranca);
            }
            catch (Exception e)
            {
                var codigoUF = notaFiscal.Identificacao.UF;
                var ambiente = notaFiscal.Identificacao.Ambiente;

                if (e.InnerException is WebException)
                {
                    throw new Exception("Serviço indisponível ou sem conexão com a internet.", e.InnerException);
                }

                try
                {
                    notaFiscalEntity = await VerificarSeNotaFoiEnviada(notaFiscal, cscId, csc, qrCode, nfe, idNotaCopiaSeguranca, notaFiscalEntity, nFeNamespaceName, certificado);
                }
                catch (Exception retornoConsultaException)
                {
                    EscreverLogErro(e);
                    EscreverLogErro(retornoConsultaException);
                    XmlUtil.SalvarXmlNFeComErro(notaFiscal, node);
                    throw retornoConsultaException;
                }

                notaFiscal.QrCodeUrl            = qrCode;
                notaFiscal.Identificacao.Status = Status.ENVIADA;
                notaFiscal.DhAutorizacao        = notaFiscalEntity.DataAutorizacao.ToString("dd/MM/yyyy HH:mm:ss");
                notaFiscal.DataHoraAutorização  = notaFiscalEntity.DataAutorizacao;
                notaFiscal.ProtocoloAutorizacao = notaFiscalEntity.Protocolo;
                return(idNotaCopiaSeguranca);
            }
        }
        private MensagemRetornoTransmissaoNotasContingencia TransmitirLoteNotasFiscaisContingencia(List <string> nfeList, Modelo modelo)
        {
            var lote = new TEnviNFe();

            lote.idLote  = "999999";              //qual a regra pra gerar o id?
            lote.indSinc = TEnviNFeIndSinc.Item0; //apenas uma nota no lote
            lote.versao  = "4.00";
            lote.NFe     = new TNFe[1];
            lote.NFe[0]  = new TNFe(); //Gera tag <NFe /> vazia para usar no replace

            string parametroXML = XmlUtil.Serialize(lote, "http://www.portalfiscal.inf.br/nfe");

            parametroXML = parametroXML.Replace("<NFe />", XmlUtil.GerarXmlListaNFe(nfeList)).Replace("<motDesICMS>1</motDesICMS>", string.Empty);

            var document = new XmlDocument();

            document.LoadXml(parametroXML);
            var node = document.DocumentElement;

            var config = ConfiguracaoService.GetConfiguracao();

            Ambiente         ambiente = config.IsProducao ? Ambiente.Producao : Ambiente.Homologacao;
            var              codigoUF = (CodigoUfIbge)Enum.Parse(typeof(CodigoUfIbge), EmissorService.GetEmissor().Endereco.UF);
            X509Certificate2 certificado;

            var certificadoEntity = new CertificadoRepository(new NFeContext()).GetCertificado();

            if (!string.IsNullOrWhiteSpace(certificadoEntity.Caminho))
            {
                certificado = CertificateManager.GetCertificateByPath(certificadoEntity.Caminho,
                                                                      RijndaelManagedEncryption.DecryptRijndael(certificadoEntity.Senha));
            }
            else
            {
                certificado = CertificateManager.GetCertificateBySerialNumber(certificadoEntity.NumeroSerial, false);
            }

            try
            {
                var servico = ServiceFactory.GetService(modelo, ambiente, Factory.Servico.AUTORIZACAO, codigoUF, certificado);
                var client  = (NFeAutorizacao4.NFeAutorizacao4SoapClient)servico.SoapClient;

                XmlNode     result  = client.nfeAutorizacaoLote(node);
                TRetEnviNFe retorno = (TRetEnviNFe)XmlUtil.Deserialize <TRetEnviNFe>(result.OuterXml);

                return(new MensagemRetornoTransmissaoNotasContingencia()
                {
                    RetEnviNFeInfRec = (TRetEnviNFeInfRec)retorno.Item,
                    TipoMensagem = TipoMensagem.Sucesso
                });
            }
            catch (Exception)
            {
                if (!_isFirstTimeResending)
                {
                    _isFirstTimeResending = true;
                    return(TransmitirLoteNotasFiscaisContingencia(nfeList, modelo));
                }
                else
                {
                    _isFirstTimeResending = false;

                    return(new MensagemRetornoTransmissaoNotasContingencia()
                    {
                        TipoMensagem = TipoMensagem.ServicoIndisponivel
                    });
                }
            }
        }
        internal async Task <int> EnviarNotaContingencia(NotaFiscal notaFiscal, string cscId, string csc)
        {
            TNFe   nfe              = null;
            string qrCode           = string.Empty;
            string newNodeXml       = string.Empty;
            string nFeNamespaceName = "http://www.portalfiscal.inf.br/nfe";
            string digVal           = string.Empty;

            int idNotaCopiaSeguranca = 0;

            var config = ConfiguracaoService.GetConfiguracao();

            notaFiscal.Identificacao.DataHoraEntradaContigencia = config.DataHoraEntradaContingencia;
            notaFiscal.Identificacao.JustificativaContigencia   = config.JustificativaContingencia;
            notaFiscal.Identificacao.TipoEmissao = notaFiscal.Identificacao.Modelo == Modelo.Modelo65 ? TipoEmissao.ContigenciaNfce : TipoEmissao.FsDa;
            notaFiscal.CalcularChave();

            X509Certificate2 certificado;

            var certificadoEntity = new CertificadoRepository(new NFeContext()).GetCertificado();

            if (!string.IsNullOrWhiteSpace(certificadoEntity.Caminho))
            {
                certificado = CertificateManager.GetCertificateByPath(certificadoEntity.Caminho,
                                                                      RijndaelManagedEncryption.DecryptRijndael(certificadoEntity.Senha));
            }
            else
            {
                certificado = CertificateManager.GetCertificateBySerialNumber(certificadoEntity.NumeroSerial, false);
            }

            if (notaFiscal.Identificacao.Ambiente == Domain.Services.Identificacao.Ambiente.Homologacao)
            {
                notaFiscal.Produtos[0].Descricao = "NOTA FISCAL EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL";
            }

            var refUri = "#NFe" + notaFiscal.Identificacao.Chave;

            var     xml  = Regex.Replace(XmlUtil.GerarXmlLoteNFe(notaFiscal, nFeNamespaceName), "<motDesICMS>1</motDesICMS>", string.Empty);
            XmlNode node = AssinaturaDigital.AssinarLoteComUmaNota(xml, refUri, certificado, ref digVal);

            var codigoUF = (CodigoUfIbge)Enum.Parse(typeof(CodigoUfIbge), notaFiscal.Emitente.Endereco.UF);

            if (notaFiscal.Identificacao.Modelo == Modelo.Modelo65)
            {
                qrCode = QrCodeUtil.GerarQrCodeNFe(notaFiscal.Identificacao.Chave, notaFiscal.Destinatario, digVal, notaFiscal.Identificacao.Ambiente,
                                                   notaFiscal.Identificacao.DataHoraEmissao, notaFiscal.TotalNFe.IcmsTotal.ValorTotalNFe.ToString("F", CultureInfo.InvariantCulture),
                                                   notaFiscal.TotalNFe.IcmsTotal.ValorTotalIcms.ToString("F", CultureInfo.InvariantCulture), cscId, csc, notaFiscal.Identificacao.TipoEmissao);

                newNodeXml = node.InnerXml.Replace("<qrCode />", "<qrCode>" + qrCode + "</qrCode>");
            }
            else
            {
                newNodeXml = node.InnerXml.Replace("<infNFeSupl><qrCode /></infNFeSupl>", "");
            }

            var document = new XmlDocument();

            document.LoadXml(newNodeXml);
            node = document.DocumentElement;

            TEnviNFe lote = (TEnviNFe)XmlUtil.Deserialize <TEnviNFe>(node.OuterXml);

            nfe = lote.NFe[0];

            //salvar nota PreEnvio aqui
            notaFiscal.Identificacao.Status = NFe.Repository.Status.CONTINGENCIA;

            var notaFiscalService = new NotaFiscalService();

            idNotaCopiaSeguranca = await notaFiscalService.SalvarNotaFiscalPendenteAsync(notaFiscal, XmlUtil.GerarNfeProcXml(nfe, qrCode), notaFiscal.Identificacao.Ambiente);

            var notaFiscalEntity = await notaFiscalService.GetNotaFiscalByIdAsync(idNotaCopiaSeguranca, false);

            notaFiscalEntity.Status = (int)Status.CONTINGENCIA;
            string nfeProcXml = XmlUtil.GerarNfeProcXml(nfe, qrCode);

            await notaFiscalService.SalvarAsync(notaFiscalEntity, nfeProcXml);

            notaFiscal.QrCodeUrl = qrCode;
            return(idNotaCopiaSeguranca);
        }
        private async Task <List <string> > TransmitirConsultarLoteContingenciaAsync(ConfiguracaoEntity config, List <string> notasNFCe, Modelo modelo)
        {
            var retornoTransmissao = TransmitirLoteNotasFiscaisContingencia(notasNFCe, modelo);

            if (retornoTransmissao.TipoMensagem == TipoMensagem.ErroValidacao)
            {
                return(new List <string>()
                {
                    retornoTransmissao.Mensagem
                });
            }
            else if (retornoTransmissao.TipoMensagem == TipoMensagem.ServicoIndisponivel)
            {
                return(new List <string>()
                {
                    mensagemErro
                });
            }

            int           tempoEspera = Int32.Parse(retornoTransmissao.RetEnviNFeInfRec.tMed) * 1000;
            List <string> erros       = new List <string>();

            Thread.Sleep(tempoEspera);
            var resultadoConsulta = ConsultarReciboLoteContingencia(retornoTransmissao.RetEnviNFeInfRec.nRec, modelo);

            if (resultadoConsulta == null)
            {
                return(new List <string>()
                {
                    mensagemErro
                });
            }

            foreach (var resultado in resultadoConsulta)
            {
                var ambiente = config.IsProducao ? Ambiente.Producao : Ambiente.Homologacao;
                var nota     = new NotaFiscalService().GetNotaFiscalByChave(resultado.Chave);

                if (resultado.CodigoStatus == "100")
                {
                    nota.DataAutorizacao = DateTime.ParseExact(resultado.DataAutorizacao, "yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture);
                    nota.Protocolo       = resultado.Protocolo;
                    nota.Status          = (int)NFe.Repository.Status.ENVIADA;

                    string xml = await nota.LoadXmlAsync();

                    xml = xml.Replace("<protNFe />", resultado.Xml);

                    var notaFiscalService = new NotaFiscalService();

                    await notaFiscalService.SalvarAsync(nota, xml);
                }
                else
                {
                    if (resultado.Motivo.Contains("Duplicidade"))
                    {
                        X509Certificate2 certificado;
                        var certificadoEntity = new CertificadoRepository(new NFeContext()).GetCertificado();
                        var emitente          = EmissorService.GetEmissor();

                        if (!string.IsNullOrWhiteSpace(certificadoEntity.Caminho))
                        {
                            certificado = CertificateManager.GetCertificateByPath(certificadoEntity.Caminho,
                                                                                  RijndaelManagedEncryption.DecryptRijndael(certificadoEntity.Senha));
                        }
                        else
                        {
                            certificado = CertificateManager.GetCertificateBySerialNumber(certificadoEntity.NumeroSerial, false);
                        }

                        var retornoConsulta = NFeConsulta.ConsultarNotaFiscal
                                              (
                            nota.Chave,
                            emitente.Endereco.CodigoUF,
                            certificado,
                            config.IsProducao ? Ambiente.Producao : Ambiente.Homologacao,
                            nota.Modelo.Equals("65") ? Modelo.Modelo65 : Modelo.Modelo55
                                              );

                        if (retornoConsulta.IsEnviada)
                        {
                            var protSerialized = XmlUtil.Serialize(retornoConsulta.Protocolo, string.Empty)
                                                 .Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", string.Empty)
                                                 .Replace("TProtNFe", "protNFe");

                            protSerialized = Regex.Replace(protSerialized, "<infProt (.*?)>", "<infProt>");

                            nota.DataAutorizacao = retornoConsulta.DhAutorizacao;
                            nota.Protocolo       = retornoConsulta.Protocolo.infProt.nProt;
                            nota.Status          = (int)NFe.Repository.Status.ENVIADA;

                            string xml = await nota.LoadXmlAsync();

                            xml = xml.Replace("<protNFe />", protSerialized);

                            var notaFiscalService = new NotaFiscalService();

                            await notaFiscalService.SalvarAsync(nota, xml);
                        }
                        else
                        {
                            erros.Add(string.Format("Modelo: {0} Nota: {1} Série: {2} \nMotivo: {3}", nota.Modelo, nota.Numero, nota.Serie, resultado.Motivo)); //O que fazer com essas mensagens de erro?
                        }
                    }
                    else
                    {
                        erros.Add(string.Format("Modelo: {0} Nota: {1} Série: {2} \nMotivo: {3}", nota.Modelo, nota.Numero, nota.Serie, resultado.Motivo)); //O que fazer com essas mensagens de erro?
                    }
                }
            }

            return(erros);
        }