/// <summary> /// Lista de NF-e para envio /// </summary> /// <returns></returns> public TNFe[] tnfeLista() { TNFe[] nfe = new TNFe[1]; nfe[1] = tnfe(); return(nfe); }
public static string GeraQrCode(this TNFe nfe, string cscId, string cscToken, string digest = null) { var builder = new StringBuilder(); builder.Append(ListaUrl.BuscaUrls(nfe.infNFe.ide.cUF, nfe.infNFe.ide.tpAmb).UrlNfceQrCode); var dataHex = ToHex(nfe.infNFe.ide.dhEmi ?? nfe.infNFe.ide.dhCont); if (digest == null) { digest = ToHex(nfe.Signature.SignedInfo.Reference.DigestValue); } var parametros = string.Format("chNFe={0}&nVersao={1}&tpAmb={2}&cDest={3}&dhEmi={4}&vNF={5}&vICMS={6}&digVal={7}", nfe.infNFe.Id.Substring(3), nfe.infNFe.versao, (int)nfe.infNFe.ide.tpAmb, (nfe.infNFe.dest != null && nfe.infNFe.dest.Item.HasValue()) ? nfe.infNFe.dest.Item : String.Empty, dataHex, nfe.infNFe.total.ICMSTot.vNF, nfe.infNFe.total.ICMSTot.vICMS, digest); builder.Append(parametros); builder.AppendFormat("&cIdToken={0}", cscId); using (var sha = SHA1.Create()) { parametros += "&CSC=" + cscToken; builder.Append("&cHashQRCode=" + ToHex(sha.ComputeHash(Encoding.UTF8.GetBytes(parametros)))); } return(builder.ToString()); }
private NotaFiscalEntity VerificarSeNotaFoiEnviada(NotaFiscal notaFiscal, string qrCode, TNFe nfe, int idNotaCopiaSeguranca, NotaFiscalEntity notaFiscalEntity, string nFeNamespaceName, X509Certificate2 certificado) { var retornoConsulta = _nfeConsulta.ConsultarNotaFiscal(notaFiscal.Identificacao.Chave, notaFiscal.Emitente.Endereco.CodigoUF, certificado, notaFiscal.Identificacao.Ambiente, notaFiscal.Identificacao.Modelo); if (!retornoConsulta.IsEnviada) { return(notaFiscalEntity); } var protSerialized = XmlUtil.Serialize(retornoConsulta.Protocolo, nFeNamespaceName); var protDeserialized = (TProtNFe)XmlUtil.Deserialize <TProtNFe>(protSerialized); notaFiscalEntity = _notaFiscalRepository.GetNotaFiscalById(idNotaCopiaSeguranca, false); notaFiscalEntity.Status = (int)Status.ENVIADA; notaFiscalEntity.DataAutorizacao = retornoConsulta.DhAutorizacao; notaFiscalEntity.Protocolo = retornoConsulta.Protocolo.infProt.nProt; var xmlNfeProc = XmlUtil.GerarNfeProcXml(nfe, qrCode, protDeserialized); _notaFiscalRepository.Salvar(notaFiscalEntity, xmlNfeProc); return(notaFiscalEntity); }
private long ObterInserirEmpresaFrete(TNFe nfe) { if (nfe.infNFe.transp != null && nfe.infNFe.transp.transporta != null && !string.IsNullOrEmpty(nfe.infNFe.transp.transporta.Item)) { Pessoa empresaFrete = GerenciadorPessoa.GetInstance().ObterPorCpfCnpj(nfe.infNFe.transp.transporta.Item).ElementAtOrDefault(0); if (empresaFrete == null) { empresaFrete = GerenciadorPessoa.GetInstance().ObterPorNome(nfe.infNFe.transp.transporta.xNome).ElementAtOrDefault(0); } if (empresaFrete == null) { empresaFrete = new Pessoa(); empresaFrete.CpfCnpj = nfe.infNFe.transp.transporta.Item; empresaFrete.Nome = nfe.infNFe.transp.transporta.xNome.ToUpper(); empresaFrete.NomeFantasia = nfe.infNFe.transp.transporta.xNome.ToUpper(); empresaFrete.Ie = nfe.infNFe.transp.transporta.IE; empresaFrete.Endereco = nfe.infNFe.transp.transporta.xEnder.ToUpper(); empresaFrete.Uf = nfe.infNFe.transp.transporta.UF.ToString().ToUpper(); empresaFrete.Cidade = nfe.infNFe.transp.transporta.xMun.ToUpper(); empresaFrete.CodMunicipioIBGE = GerenciadorMunicipio.GetInstance().ObterPorCidadeEstado(empresaFrete.Cidade, empresaFrete.Uf).Codigo; empresaFrete.Tipo = empresaFrete.CpfCnpj.Length == 11 ? Pessoa.PESSOA_FISICA : Pessoa.PESSOA_JURIDICA; return(GerenciadorPessoa.GetInstance().Inserir(empresaFrete)); } else { return(empresaFrete.CodPessoa); } } else { return(1); } }
/// <summary> /// tag enviNFe /// </summary> /// <returns></returns> public TNFe tnfe() { TNFe nfe = new TNFe(); nfe.infNFe = tNFeInfNFe(); // nfe.Signature return(nfe); }
private int SalvarNotaFiscalPréEnvio(NotaFiscal notaFiscal, string qrCode, TNFe nfe) { int idNotaCopiaSeguranca; notaFiscal.Identificacao.Status = Status.PENDENTE; idNotaCopiaSeguranca = _notaFiscalRepository.SalvarNotaFiscalPendente(notaFiscal, XmlUtil.GerarNfeProcXml(nfe, qrCode), notaFiscal.Identificacao.Ambiente); return(idNotaCopiaSeguranca); }
public static TNFe GeraAssinatura(this TNFe nfe, X509Certificate2 certificate) { if (string.IsNullOrEmpty(nfe.infNFe.Id)) { nfe.CalculaChave(); } var nfeXml = new XmlDocument(); nfeXml.LoadXml(nfe.Serialize().LimpaNamespaces()); nfe.Signature = AssinadorXml.GeraAssinatura(nfeXml, "infNFe", certificate); return(nfe); }
public TNFe AssinarNFE(TNFe nota, string pUri) { var arquivoNaoAssinado = new XmlDocument(); arquivoNaoAssinado.LoadXml(Funcoes.RemoveNameSpaceFromXml(nota.Serialize())); var auxDocXML = CertificadoDigital.Assinar(arquivoNaoAssinado, pUri, Certificado); auxDocXML.Save(nota.NomeArquivo); var retorno = TNFe.LoadFromFile(nota.NomeArquivo); retorno.NomeArquivo = nota.NomeArquivo; retorno.ArquivoXML = auxDocXML; return(retorno); }
public static string CalculaChave(this TNFe nfe) { var random = new Random(); var dtEmissao = Convert.ToDateTime(nfe.infNFe.ide.dhEmi); var codUF = ((int)nfe.infNFe.ide.cUF).ToString(CultureInfo.InvariantCulture); var dEmi = dtEmissao.ToString("yyMM"); var cnpj = nfe.infNFe.emit.Item; var mod = ((int)nfe.infNFe.ide.mod).ToString(CultureInfo.InvariantCulture); var serie = string.Format("{0:000}", Convert.ToInt32(nfe.infNFe.ide.serie)); var numNf = string.Format("{0:000000000}", Convert.ToInt32(nfe.infNFe.ide.nNF)); var codigo = nfe.infNFe.ide.cNF ?? string.Format("{0:00000000}", random.Next(10000000, 99999999)); var tpEmissao = ((int)nfe.infNFe.ide.tpEmis).ToString(CultureInfo.InvariantCulture); var chaveNF = codUF + dEmi + cnpj + mod + serie + numNf + tpEmissao + codigo; var dv = Digit.Modulo11(chaveNF); nfe.infNFe.Id = "NFe" + chaveNF + dv; nfe.infNFe.ide.cDV = dv.ToString(CultureInfo.InvariantCulture); nfe.infNFe.ide.cNF = codigo; return(chaveNF + dv); }
public void Pdf(Stream stream, TNFe nfe, TProtNFe protocolo, string cscId, string cscToken, bool mostrarDetalhes = false) { var document = new Document(); var style = document.Styles["Normal"].Font.Name = "Helvetica"; if (nfe.infNFe.ide.tpEmis == TipoEmissaoNFe.ContingenciaOffline) { MontaPagina(document, nfe, protocolo, cscId, cscToken, mostrarDetalhes, " - Via do Consumidor"); MontaPagina(document, nfe, protocolo, cscId, cscToken, mostrarDetalhes, " - Via do Estabelecimento"); } else { MontaPagina(document, nfe, protocolo, cscId, cscToken, mostrarDetalhes); } var pdfRenderer = new PdfDocumentRenderer(false, PdfFontEmbedding.Always); pdfRenderer.Document = document; pdfRenderer.RenderDocument(); pdfRenderer.PdfDocument.Save(stream); }
public void ToJSON(Issuer issuer, Recipient recipient, List <Product> products) { var NFe = new TNFe() { }; }
private void MontaPagina(Document document, TNFe nfe, TProtNFe protocolo, string cscId, string cscToken, bool mostrarDetalhesVenda, string via = "") { var page = document.AddSection(); // 2.3.1 Divisão I - Informações do Cabeçalho var table = page.AddTable(); table.Rows.LeftIndent = 0; // Before you can add a row, you must define the columns var column = table.AddColumn("4cm"); column.Format.Alignment = ParagraphAlignment.Center; column = table.AddColumn("6cm"); //column.Format.Alignment = ParagraphAlignment.Left; column = table.AddColumn("6cm"); //column.Format.Alignment = ParagraphAlignment.Left; // Logo NFC-e (opcional) // Logo do Contribuinte (opcional) var row = table.AddRow(); row.Cells[0].MergeDown = 2; var file = @"..\..\..\NFCerta.NFe\Resources\logo.jpg"; var image = row.Cells[0].AddImage(file); image.Height = "1.3cm"; // Razão social do Emitente row.Cells[1].AddParagraph(nfe.infNFe.emit.xNome); // Inscrição Municipal do Emitente (se houver) if (nfe.infNFe.emit.IM.HasValue()) { row.Cells[2].AddParagraph("Inscrição Municipal - " + nfe.infNFe.emit.IM); } row = table.AddRow(); // CNPJ do Emitente row.Cells[1].AddParagraph("CNPJ - " + nfe.infNFe.emit.Item); // Inscrição Estadual do Emitente row.Cells[2].AddParagraph("Inscrição Estadual - " + nfe.infNFe.emit.IE); row = table.AddRow(); // Endereço Completo do Emitente // Endereço Completo (Logradouro, n, bairro, municipio, sigla, uf) row.Cells[1].AddParagraph(nfe.infNFe.emit.enderEmit.xLgr + ", " + nfe.infNFe.emit.enderEmit.nro + ", " + nfe.infNFe.emit.enderEmit.xBairro + ", " + nfe.infNFe.emit.enderEmit.xMun + ", " + nfe.infNFe.emit.enderEmit.UF.ToString()); row.Cells[1].MergeRight = 1; table.SetEdge(0, 0, table.Columns.Count, table.Rows.Count, Edge.Box, BorderStyle.Single, 0.5); // 2.3.2 Divisão II – Informações Fixas do DANFE NFC-e table = page.AddTable(); table.Rows.LeftIndent = 0; column = table.AddColumn("16cm"); column.Format.Alignment = ParagraphAlignment.Center; row = table.AddRow(); row.Cells[0].AddParagraph("DANFE NFC-e - Documento Auxiliar de Nota Fiscal de Consumidor Eletrônica"); row = table.AddRow(); row.Cells[0].AddParagraph("Não permite aproveitamento de crédito de ICMS"); table.SetEdge(0, 0, table.Columns.Count, table.Rows.Count, Edge.Box, BorderStyle.Single, 0.5); // 2.3.3 Divisão III – Informações de Detalhe da Venda if (mostrarDetalhesVenda || nfe.infNFe.ide.tpEmis == TipoEmissaoNFe.ContingenciaOffline) { table = page.AddTable(); table.Rows.LeftIndent = 0; table.AddColumn("2cm"); table.AddColumn("3cm"); table.AddColumn("3cm"); table.AddColumn("2cm"); table.AddColumn("3cm"); table.AddColumn("3cm"); row = table.AddRow(); row.HeadingFormat = true; row.Cells[0].AddParagraph("Código"); row.Cells[1].AddParagraph("Descrição"); row.Cells[2].AddParagraph("Qtde"); row.Cells[3].AddParagraph("Un"); row.Cells[4].AddParagraph("Valor unit."); row.Cells[5].AddParagraph("Valor total"); foreach (var det in nfe.infNFe.det) { row = table.AddRow(); row.Cells[0].AddParagraph(det.prod.cProd); row.Cells[1].AddParagraph(det.prod.xProd); row.Cells[2].AddParagraph(det.prod.qCom); row.Cells[3].AddParagraph(det.prod.uCom); row.Cells[4].AddParagraph(det.prod.vUnCom); row.Cells[5].AddParagraph(det.prod.vProd); } table.SetEdge(0, 0, table.Columns.Count, table.Rows.Count, Edge.Box, BorderStyle.Single, 0.5); } // 2.3.4 Divisão IV – Informações de Total do DANFE NFC-e table = page.AddTable(); table.Rows.LeftIndent = 0; table.AddColumn("8cm"); column = table.AddColumn("8cm"); column.Format.Alignment = ParagraphAlignment.Right; // QTD. TOTAL DE ITENS = somatório da quantidade de itens; var qtdTotal = nfe.infNFe.det.Sum(det => float.Parse(det.prod.qCom)); row = table.AddRow(); row.Cells[0].AddParagraph("QTD. TOTAL DE ITENS"); row.Cells[1].AddParagraph(qtdTotal.ToString("0.####")); // ACRESCIMO row = table.AddRow(); row.Cells[0].AddParagraph("ACRESCIMO"); row.Cells[1].AddParagraph(nfe.infNFe.total.ICMSTot.vOutro); // VALOR TOTAL = somatório dos valores totais dos itens somados os acréscimos e subtraído dos descontos row = table.AddRow(); row.Cells[0].AddParagraph("VALOR TOTAL R$"); row.Cells[1].AddParagraph(nfe.infNFe.total.ICMSTot.vNF); row = table.AddRow(); row.Cells[0].AddParagraph("FORMA DE PAGAMENTO"); // VALOR PAGO = valor pago efetivamente na forma de pagamento identificada imediatamente acima row.Cells[1].AddParagraph("Valor Pago"); // FORMA PAGAMENTO = forma na qual o pagamento da NFC-e foi efetuado (podem ocorrer mais de uma forma de pagamento, devendo neste caso ser indicado o montante parcial do pagamento para a respectiva forma. Exemplo: em dinheiro, em cheque, etc nfe.infNFe.pag.ForEach(pag => { row = table.AddRow(); row.Cells[0].AddParagraph(pag.tPag.ToString()); row.Cells[1].AddParagraph(pag.vPag); }); table.SetEdge(0, 0, table.Columns.Count, table.Rows.Count, Edge.Box, BorderStyle.Single, 0.5); // 2.3.5 Divisão V – Informações dos Tributos no DANFE NFC-e table = page.AddTable(); table.Rows.LeftIndent = 0; table.AddColumn("8cm"); column = table.AddColumn("8cm"); column.Format.Alignment = ParagraphAlignment.Right; row = table.AddRow(); row.Cells[0].AddParagraph("Informação dos TributosTotais Incedentais (Lei Federal 12.741/2012)"); // Soma de todos os tributos incidentes na operação/prestação, contemplando toda a cadeia de fornecimento row.Cells[1].AddParagraph(nfe.infNFe.total.ICMSTot.vTotTrib ?? "0.00"); table.SetEdge(0, 0, table.Columns.Count, table.Rows.Count, Edge.Box, BorderStyle.Single, 0.5); // 2.3.6 Divisão Va – Mensagem de Interesse do Contribuinte table = page.AddTable(); table.Rows.LeftIndent = 0; column = table.AddColumn("16cm"); column.Format.Alignment = ParagraphAlignment.Center; row = table.AddRow(); row.Cells[0].AddParagraph(nfe.infNFe.infAdic.infCpl); table.SetEdge(0, 0, table.Columns.Count, table.Rows.Count, Edge.Box, BorderStyle.Single, 0.5); // 2.3.7 Divisão VI – Mensagem Fiscal e Informações da Consulta via Chave de Acesso table = page.AddTable(); table.Rows.LeftIndent = 0; column = table.AddColumn("16cm"); column.Format.Alignment = ParagraphAlignment.Center; // Área de Mensagem Fiscal. Quando for o caso deve ser incluídas as seguintes mensagens: “EMITIDA EM CONTINGÊNCIA”, “EMITIDA EM AMBIENTE DE HOMOLOGAÇÃO – SEM VALOR FISCAL”) if (nfe.infNFe.ide.tpEmis == TipoEmissaoNFe.ContingenciaOffline) { row = table.AddRow(); row.Cells[0].AddParagraph("EMITIDA EM CONTINGÊNCIA"); } if (nfe.infNFe.ide.tpAmb == AmbienteSefaz.Homologacao) { row = table.AddRow(); row.Cells[0].AddParagraph("EMITIDA EM AMBIENTE DE HOMOLOGAÇÃO – SEM VALOR FISCAL"); } // Número da NFC-e // Série da NFC-e // Data e Hora de Emissão da NFC-e (observação: a data de emissão apesar de constar no arquivo XML da NFC- NFC-e sempre convertida para o horário local) var dataEmissaoLocal = nfe.infNFe.ide.dhEmi.FromSefazTime().InZone(nfe.infNFe.emit.enderEmit.UF).ToString("dd/MM/yyyy HH:mm:ss"); row = table.AddRow(); var text = "Número {0} Série {1} Emissão {2}".F(nfe.infNFe.ide.nNF, nfe.infNFe.ide.serie, dataEmissaoLocal); row.Cells[0].AddParagraph(text + via); row = table.AddRow(); // O texto “Consulte pela Chave de Acesso em” seguido do endereço eletrônico para consulta pública da NFC-e no Portal da Secretaria da Fazenda do Estado do contribuinte row.Cells[0].AddParagraph("Consulte pela Chave de Acesso em " + ListaUrl.BuscaUrls(nfe.infNFe.ide.cUF, nfe.infNFe.ide.tpAmb).UrlNfceConsultaChaveAcesso); row = table.AddRow(); // O texto “CHAVE DE ACESSO”, em caixa alta row.Cells[0].AddParagraph("CHAVE DE ACESSO"); row = table.AddRow(); // A chave de acesso impressa em 11 blocos de quatro dígitos, com um espaço entre cada bloco row.Cells[0].AddParagraph(protocolo.infProt.chNFe.SplitChunks(4).JoinString(" ")); table.SetEdge(0, 0, table.Columns.Count, table.Rows.Count, Edge.Box, BorderStyle.Single, 0.5); // 2.3.8 Divisão VII – Informações sobre o Consumidor table = page.AddTable(); table.Rows.LeftIndent = 0; column = table.AddColumn("16cm"); column.Format.Alignment = ParagraphAlignment.Center; row = table.AddRow(); row.Cells[0].AddParagraph("CONSUMIDOR"); if (nfe.infNFe.dest != null) { var doc = ""; if (nfe.infNFe.dest.TipoDocumento == TipoDocumento.CNPJ) { doc = "CNPJ: "; } if (nfe.infNFe.dest.TipoDocumento == TipoDocumento.CNPJ) { doc = "CPF: "; } if (nfe.infNFe.dest.TipoDocumento == TipoDocumento.CNPJ) { doc = "Id. Estrangeiro: "; } doc += nfe.infNFe.dest.Item; // Nome opcional row = table.AddRow(); row.Cells[0].AddParagraph(doc + " " + nfe.infNFe.dest.xNome); row = table.AddRow(); // Endereco opcional row.Cells[0].AddParagraph(nfe.infNFe.emit.enderEmit.xLgr + ", " + nfe.infNFe.emit.enderEmit.nro + ", " + nfe.infNFe.emit.enderEmit.xBairro + ", " + nfe.infNFe.emit.enderEmit.xMun); } else { // Na hipótese do não preenchimento das informações de identificação do consumidor na NFCe, deverá ser impressa na área reservada apenas a mensagem “CONSUMIDOR NÃO IDENTIFICADO”. row = table.AddRow(); row.Cells[0].AddParagraph("CONSUMIDOR NÃO IDENTIFICADO"); } table.SetEdge(0, 0, table.Columns.Count, table.Rows.Count, Edge.Box, BorderStyle.Single, 0.5); // 2.3.9 Divisão VIII – Informações da Consulta via QR Code table = page.AddTable(); table.Rows.LeftIndent = 0; column = table.AddColumn("16cm"); column.Format.Alignment = ParagraphAlignment.Center; row = table.AddRow(); // O texto “Consulta via leitor de QR Code” row.Cells[0].AddParagraph("Consulta via leitor de QR Code"); table.SetEdge(0, 0, table.Columns.Count, table.Rows.Count, Edge.Box, BorderStyle.Single, 0.5); // A imagem do QR Code em tamanho mínimo 25 mm x 25 mm var url = nfe.GeraQrCode(cscId, cscToken); // "http://www4.fazenda.rj.gov.br/consultaNFCe/QRCode?chNFe=99999999999999999999999999999999999999999999&nVersao=&tpAmp=2&cDest=&dhEmi=323031342D31322D32365430313A31383A33342D30323A3030&vNF=8904.50&vICMS=0.00&digVal=370032007100510061002B0062003000740061006F0051004F003900660041004A007700660064006C005800750071005100760038003D00&cIdToken=cscId&cHashQRCode=1975033D50D8B701C99A2E201E8ED85A75B0D4F4" var qrGenerator = new QRCodeGenerator(); var bitmap = qrGenerator.CreateQrCode(url, QRCodeGenerator.ECCLevel.L).GetGraphic(1); var qrFile = new DisposableFile(); Disposables.Add(qrFile); bitmap.Save(qrFile.Path); table = page.AddTable(); table.Rows.LeftIndent = 0; column = table.AddColumn("65mm"); column = table.AddColumn("30mm"); column = table.AddColumn("65mm"); row = table.AddRow(); image = row.Cells[1].AddImage(qrFile.Path); image.Height = "30mm"; table.SetEdge(0, 0, table.Columns.Count, table.Rows.Count, Edge.Box, BorderStyle.Single, 0.5); // No caso de emissão em contingência a informação sobre o protocolo de autorização será suprimida if (nfe.infNFe.ide.tpEmis != TipoEmissaoNFe.ContingenciaOffline) { table = page.AddTable(); table.Rows.LeftIndent = 0; column = table.AddColumn("16cm"); column.Format.Alignment = ParagraphAlignment.Center; row = table.AddRow(); // O texto “Protocolo de autorização:” com o número do protocolo de autorização obtido para NFC-e e a data e hora da autorização. row.Cells[0].AddParagraph("Protocolo de Autorização: " + protocolo.infProt.nProt + " " + protocolo.infProt.dhRecbto.FromSefazTime().ToString("dd/MM/yyyy HH:mm:ss")); table.SetEdge(0, 0, table.Columns.Count, table.Rows.Count, Edge.Box, BorderStyle.Single, 0.5); } }
public int EnviarNotaFiscal(NotaFiscal notaFiscal, string cscId, string csc) { if (notaFiscal.Identificacao.Ambiente == Ambiente.Homologacao) { notaFiscal.Produtos[0].Descricao = "NOTA FISCAL EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL"; } X509Certificate2 certificado; var certificadoEntity = _certificadoRepository.GetCertificado(); if (!string.IsNullOrWhiteSpace(certificadoEntity.Caminho)) { certificado = _certificateManager.GetCertificateByPath(certificadoEntity.Caminho, RijndaelManagedEncryption.DecryptRijndael(certificadoEntity.Senha)); } else { certificado = _certificateManager.GetCertificateBySerialNumber(certificadoEntity.NumeroSerial, false); } if (!IsNotaFiscalValida(notaFiscal, cscId, csc, certificado)) { throw new ArgumentException("Nota fiscal inválida."); } try { var qrCode = ""; TNFe nfe = null; var newNodeXml = string.Empty; var idNotaCopiaSeguranca = 0; NotaFiscalEntity notaFiscalEntity = null; var refUri = "#NFe" + notaFiscal.Identificacao.Chave; var digVal = ""; var nFeNamespaceName = "http://www.portalfiscal.inf.br/nfe"; 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); newNodeXml = PreencherQrCode(notaFiscal, cscId, csc, ref qrCode, digVal, node); var document = new XmlDocument(); document.LoadXml(newNodeXml); node = document.DocumentElement; var lote = (TEnviNFe)XmlUtil.Deserialize <TEnviNFe>(node.OuterXml); nfe = lote.NFe[0]; var configuração = _configuracaoRepository.GetConfiguracao(); if (configuração.IsContingencia) { return(_emiteNotaFiscalContingenciaService.EmitirNotaContingencia(notaFiscal, cscId, csc)); } NFeAutorizacao4Soap client = CriarClientWS(notaFiscal, certificado, codigoUf); idNotaCopiaSeguranca = SalvarNotaFiscalPréEnvio(notaFiscal, qrCode, nfe); TProtNFe protocolo = RetornarProtocoloParaLoteSomenteComUmaNotaFiscal(node, client); if (protocolo.infProt.cStat.Equals("100")) { notaFiscalEntity = _notaFiscalRepository.GetNotaFiscalById(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; var xmlNFeProc = XmlUtil.GerarNfeProcXml(nfe, qrCode, protocolo); _notaFiscalRepository.Salvar(notaFiscalEntity, xmlNFeProc); } else { if (protocolo.infProt.xMotivo.Contains("Duplicidade")) { notaFiscalEntity = CorrigirNotaDuplicada(notaFiscal, qrCode, nFeNamespaceName, certificado, nfe, idNotaCopiaSeguranca); } else { //Nota continua com status pendente nesse caso XmlUtil.SalvarXmlNFeComErro(notaFiscal, node); var 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); } } AtribuirValoresApósEnvioComSucesso(notaFiscal, qrCode, notaFiscalEntity); return(idNotaCopiaSeguranca); } catch (Exception e) { log.Error(e); if (e is WebException || e.InnerException is WebException) { throw new Exception("Serviço indisponível ou sem conexão com a internet.", e.InnerException); } try { notaFiscalEntity = VerificarSeNotaFoiEnviada(notaFiscal, qrCode, nfe, idNotaCopiaSeguranca, notaFiscalEntity, nFeNamespaceName, certificado); } catch (Exception retornoConsultaException) { log.Error(retornoConsultaException); XmlUtil.SalvarXmlNFeComErro(notaFiscal, node); throw; } AtribuirValoresApósEnvioComSucesso(notaFiscal, qrCode, notaFiscalEntity); return(idNotaCopiaSeguranca); } } catch (Exception e) { log.Error(e); //Necessário para não tentar enviar a mesma nota como contingência. _configuracaoService.SalvarPróximoNúmeroSérie(notaFiscal.Identificacao.Modelo, notaFiscal.Identificacao.Ambiente); if (notaFiscal.Identificacao.Modelo == Modelo.Modelo55) { throw; } var message = e.InnerException != null ? e.InnerException.Message : e.Message; NotaEmitidaEmContingenciaEvent(message, notaFiscal.Identificacao.DataHoraEmissao); return(_emiteNotaFiscalContingenciaService.EmitirNotaContingencia(notaFiscal, cscId, csc)); } finally { _configuracaoService.SalvarPróximoNúmeroSérie(notaFiscal.Identificacao.Modelo, notaFiscal.Identificacao.Ambiente); } }
/// <summary> /// Gera os dados básicos da NF. Cabeçalho: Identificacao da NFe, informacoes da NFe, dados do emitente, destinatario /// </summary> /// <param name="movimento"></param> /// <returns></returns> private TNFe GerarTNFeBasico(Movimento movimento) { try { var localManager = new LocalidadeDaoManager(); var emitente = movimento.EmpresaFilial; var municEmitente = localManager.GetMunicipioByNome(emitente.Cidade); var ufEmitente = localManager.GetUfByCodigo(emitente.Uf); var destinatario = movimento.CliFor; var municDestinatario = localManager.GetMunicipioByNome(destinatario.Cidade); var ufDestinatario = localManager.GetUfByCodigo(destinatario.Uf); //informacoes basicas da nota fiscal var tnfe = new TNFe() { infNFe = new TNFeInfNFe() { Id = "NFe" + movimento.ChaveAcessoNf, versao = "4.00", ide = new TNFeInfNFeIde() { cUF = ufEmitente.CodigoIBGE, //uf do emitente (cod ibge) cNF = "99999", natOp = movimento.TipoMovimento.DescricaoTipoMovimento, mod = movimento.ModeloDocumentoFiscal.CodigoModelo, serie = movimento.Serie, nNF = ParseUtil.ToInt(movimento.NumeroMovimento).ToString(), dhEmi = movimento.DataEmissao.ToString(), dhSaiEnt = movimento.DataEntrada.ToString(), tpNF = ParseUtil.ToInt(movimento.DirecaoMovimento).ToString(), //entrada ou saida idDest = TNFeInfNFeIdeIdDest.Interna, cMunFG = municEmitente.CodigoIbge, //codigo uf do ibge. tratar tpImp = TNFeInfNFeIdeTpImp.DanfeRetrato, tpEmis = TNFeInfNFeIdeTpEmis.Normal, cDV = "9", //digito verificador. tratar tpAmb = TAmb.Homologacao, finNFe = TFinNFe.NFeNormal, indFinal = TNFeInfNFeIdeIndFinal.Nao, indPres = TNFeInfNFeIdeIndPres.NaoPresencial, procEmi = TProcEmi.Contribuinte, verProc = "1" }, emit = new TNFeInfNFeEmit() { xNome = emitente.RazaoSocial, xFant = emitente.NomeFantasia, IE = emitente.InscricaoEstadual, IM = emitente.InscricaoMunicipal, CRT = TNFeInfNFeEmitCRT.SimplesNacional, TipoDocumentoEmitente = TipoDocumentoEmitente.CNPJ, TipoDocEmitente = emitente.Cnpj.FixString(), enderEmit = new TEnderEmi() { CEP = emitente.Cep.FixString(), cMun = municEmitente.CodigoIbge, xMun = municEmitente.NomeMunicipio, xPais = emitente.Pais, fone = emitente.Telefone.FixString(), nro = emitente.NumeroEndereco, xCpl = emitente.Complemento, UF = emitente.Uf, xBairro = emitente.Bairro, xLgr = emitente.NomeEndereco } }, dest = new TNFeInfNFeDest() { TipoDocumentoDestinatario = TipoDocumentoDestinatario.CNPJ, TipoDocumento = destinatario.CpfCnpj.FixString(), email = destinatario.Email, IE = destinatario.InscricaoEstadual, IM = destinatario.InscricaoMunicipal, indIEDest = TNFeInfNFeDestIndIEDest.NaoContribuinte, xNome = destinatario.RazaoSocial, enderDest = new TEndereco() { CEP = destinatario.Cep.FixString(), cMun = municDestinatario.CodigoIbge, xMun = municDestinatario.NomeMunicipio, cPais = destinatario.Pais, xPais = destinatario.Pais, fone = destinatario.Telefone.FixString(), nro = destinatario.NumeroEndereco, UF = destinatario.Uf, xBairro = destinatario.Bairro, xCpl = destinatario.Complemento, xLgr = destinatario.NomeEndereco } } } }; GerarTNFeDetalhes(movimento, tnfe); tnfe.infNFe.total = GerarTotalNFe(movimento); tnfe.infNFe.transp = GerarDadosTransporte(movimento); tnfe.infNFe.infAdic = GerarDadosAdicionais(movimento); return(tnfe); } catch (Exception) { throw; } }
/// <summary> /// Gerar os detalhes da NFe - Itens, impostos /// </summary> /// <param name="movimento"></param> /// <param name="tnfe"></param> /// <returns></returns> private TNFeInfNFeDet GerarTNFeDetalhes(Movimento movimento, TNFe tnfe) { try { // Gets a NumberFormatInfo associated with the en-US culture. NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat; nfi.NumberDecimalSeparator = "."; //gera detalhes de item e imposto var i = 1; //indice //inicializando o array, maximo 990 itens por NFe tnfe.infNFe.det = new TNFeInfNFeDet[990]; var det = new TNFeInfNFeDet(); foreach (var prod in movimento.ItensMovimento) { //numero do item det.nItem = i.ToString(); //gerar detalhe dos produtos det.prod = new TNFeInfNFeDetProd() { cProd = prod.Produto.CodigoBarras, xProd = prod.Produto.DescricaoProduto, cEAN = "", CFOP = prod.Cfop.CodigoCfop, CEST = "", cEANTrib = "", indTot = TNFeInfNFeDetProdIndTot.ValorProdutoCompoeTotalNF, NCM = prod.Produto.CodigoNCM, qCom = prod.Quantidade.ToString(nfi), qTrib = prod.Quantidade.ToString(nfi), uCom = prod.Produto.UnidadeMedida.NomeUnidadeMedida, uTrib = prod.Produto.UnidadeMedida.NomeUnidadeMedida, vDesc = "0.00", vFrete = "0.00", vOutro = "0.00", vSeg = "0.00", vUnCom = prod.ValorUnitario.ToString(nfi), vUnTrib = prod.ValorUnitario.ToString(nfi), vProd = prod.TotalItem.ToString(nfi) }; var impostosItem = new TNFeInfNFeDetImposto(); det.imposto = impostosItem; det.imposto.Items = new object[prod.ImpostosItemMovimento.Count]; //gerar impostos foreach (var imp in prod.ImpostosItemMovimento) { if (imp.TipoImposto.CodigoImposto == "PIS") { det.imposto.PIS = gerarImpostoPIS(imp); } else if (imp.TipoImposto.CodigoImposto == "COFINS") { det.imposto.COFINS = gerarImpostoCOFINS(imp); } else if (imp.TipoImposto.CodigoImposto == "ICMS") { det.imposto.Items[i] = gerarImpostoICMS(imp); } } //adicionando o item no array de detalhes da NF tnfe.infNFe.det[i] = det; i++; } return(det); } catch (Exception) { throw; } }
private RetornoNotaFiscal PreencheMensagemRetornoContingencia(string urlQrCode, TNFe nfe) { RetornoNotaFiscal mensagem = new RetornoNotaFiscal() { UrlQrCode = urlQrCode, Xml = XmlUtil.GerarNfeProcXml(nfe, urlQrCode) }; return(mensagem); }
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); }
/// <summary> /// TNfeProc class constructor /// </summary> public TNfeProc() { this.protNFeField = new TProtNFe(); this.nFeField = new TNFe(); }
private long ObterInserirFornecedor(TNFe nfe) { if (nfe.infNFe.emit != null) { Pessoa fornecedor = GerenciadorPessoa.GetInstance().ObterPorCpfCnpj(nfe.infNFe.emit.Item).ElementAtOrDefault(0); if (fornecedor == null) { fornecedor = GerenciadorPessoa.GetInstance().ObterPorNome(nfe.infNFe.emit.xNome).ElementAtOrDefault(0); } if (fornecedor == null) { fornecedor = new Pessoa(); fornecedor.CpfCnpj = nfe.infNFe.emit.Item; fornecedor.Nome = nfe.infNFe.emit.xNome.Length > 50 ? nfe.infNFe.emit.xNome.ToUpper().Substring(0, 50) : nfe.infNFe.emit.xNome.ToUpper(); if (nfe.infNFe.emit.xFant != null) { fornecedor.NomeFantasia = nfe.infNFe.emit.xFant.Length > 50 ? nfe.infNFe.emit.xFant.ToUpper().Substring(0, 50) : nfe.infNFe.emit.xFant.ToUpper(); } else { fornecedor.NomeFantasia = fornecedor.Nome; } fornecedor.Ie = nfe.infNFe.emit.IE; fornecedor.Endereco = nfe.infNFe.emit.enderEmit.xLgr.ToUpper(); fornecedor.Cep = nfe.infNFe.emit.enderEmit.CEP; fornecedor.Cidade = nfe.infNFe.emit.enderEmit.xMun.ToUpper(); fornecedor.CodMunicipioIBGE = Convert.ToInt32(nfe.infNFe.emit.enderEmit.cMun); fornecedor.Complemento = (nfe.infNFe.emit.enderEmit.xCpl != null) ? nfe.infNFe.emit.enderEmit.xCpl.ToUpper() : ""; if (string.IsNullOrEmpty(nfe.infNFe.emit.enderEmit.fone)) { fornecedor.Fone1 = ""; } else { fornecedor.Fone1 = nfe.infNFe.emit.enderEmit.fone.Length <= 12 ? nfe.infNFe.emit.enderEmit.fone : nfe.infNFe.emit.enderEmit.fone.Substring(0, 12); } fornecedor.Bairro = nfe.infNFe.emit.enderEmit.xBairro.ToUpper(); fornecedor.Ie = nfe.infNFe.emit.IE; if (nfe.infNFe.emit.IEST != null) { fornecedor.IeSubstituto = nfe.infNFe.emit.IEST; } fornecedor.Numero = nfe.infNFe.emit.enderEmit.nro.Length > 10 ? nfe.infNFe.emit.enderEmit.nro.Substring(0, 10):nfe.infNFe.emit.enderEmit.nro; fornecedor.Uf = nfe.infNFe.emit.enderEmit.UF.ToString(); fornecedor.Tipo = fornecedor.CpfCnpj.Length == 11 ? Pessoa.PESSOA_FISICA : Pessoa.PESSOA_JURIDICA; return(GerenciadorPessoa.GetInstance().Inserir(fornecedor)); } else { fornecedor.CpfCnpj = nfe.infNFe.emit.Item; fornecedor.Nome = nfe.infNFe.emit.xNome.Length > 50 ? nfe.infNFe.emit.xNome.ToUpper().Substring(0, 50) : nfe.infNFe.emit.xNome.ToUpper(); fornecedor.Ie = nfe.infNFe.emit.IE; fornecedor.Endereco = nfe.infNFe.emit.enderEmit.xLgr.ToUpper(); fornecedor.Cep = nfe.infNFe.emit.enderEmit.CEP; fornecedor.Cidade = nfe.infNFe.emit.enderEmit.xMun.ToUpper(); fornecedor.CodMunicipioIBGE = Convert.ToInt32(nfe.infNFe.emit.enderEmit.cMun); fornecedor.Complemento = (nfe.infNFe.emit.enderEmit.xCpl != null) ? nfe.infNFe.emit.enderEmit.xCpl.ToUpper() : ""; if (string.IsNullOrEmpty(nfe.infNFe.emit.enderEmit.fone)) { fornecedor.Fone1 = ""; } else { fornecedor.Fone1 = nfe.infNFe.emit.enderEmit.fone.Length <= 12 ? nfe.infNFe.emit.enderEmit.fone : nfe.infNFe.emit.enderEmit.fone.Substring(0, 12); } fornecedor.Bairro = nfe.infNFe.emit.enderEmit.xBairro.ToUpper(); fornecedor.Ie = nfe.infNFe.emit.IE; fornecedor.IeSubstituto = nfe.infNFe.emit.IEST; fornecedor.Numero = nfe.infNFe.emit.enderEmit.nro.Length > 10 ? nfe.infNFe.emit.enderEmit.nro.Substring(0, 10) : nfe.infNFe.emit.enderEmit.nro; fornecedor.Uf = nfe.infNFe.emit.enderEmit.UF.ToString(); fornecedor.Tipo = fornecedor.CpfCnpj.Length == 11 ? Pessoa.PESSOA_FISICA : Pessoa.PESSOA_JURIDICA; GerenciadorPessoa.GetInstance().Atualizar(fornecedor); return(fornecedor.CodPessoa); } } else { return(1); // quando por algum motivo não conseguir recuperar o fornecedor } }