quinta-feira, 29 de novembro de 2012

Nota Técnica 2011 Cancelamento da NF da Nota Fiscal Eletrônica Manual de Integração 2011/006 NF-e como Evento Versão 1.00a Março 2012 - Contribuinte


Para ajudar quem está se preparando para  a nota de cancelamento como evendo
Gerando o arquivo em C#



///

        /// gera o arquivo xml para envio no evento
        ///
        /// diretorio a ser salvo o arquivo
        /// codigo da empresa
        /// tipo ambiente nfe
        /// numero da nota
        /// serie nfe
        /// vesão nfe
        /// justificativa digitada
        /// tipo do evento exemplo Carta de Correcao ou Cancelamento
        /// prefixo inicial do nome do arquivo exemplo CCE (Carta de Correcao) ou CNFE (cancelamento)
        private void GeraArquivoXmlEvento(string DiretorioEnviar, int idEmpresa
                    , int tpAmb, string NumNota, string Serie, string VersaoNF
                    , string Justificativa, string Evento, string prefixoInicialArquivo)
        {
            UTF8Encoding _utf8 = new UTF8Encoding();
            DataTable _infoNfe = new DataTable(); //informações da nfe
            int _seqEvento = 0;
            string _cnpjEmi = string.Empty, _caminhoxml = string.Empty, _tipoEvento = string.Empty;
            try
            {
                //retorna a nota fiscal
                _infoNfe =retorna um datatable contendo a nota fiscal;
                //formata cnpj
                _cnpjEmi = pega o cnpj do emitente da nota.ToString().Replace(".", "").Replace("-", "").Replace("/", "");
                //prepara caminho
                _caminhoxml = DiretorioEnviar + @"\" + prefixoInicialArquivo + _infoNfe.Rows[0]["chNFe"].ToString() + ".xml";
                //busca o tipo do evento
                _tipoEvento = TipoEvento(Evento);
                if (File.Exists(_caminhoxml))
                {
                    File.Delete(_caminhoxml);
                }

                int _i = RetornaSeqEvento(_infoNfe.Rows[0]["chNFe"].ToString(),Evento);
                _seqEvento = _i > 0 ? _i : 1;

                XmlTextWriter _xml = new XmlTextWriter(_caminhoxml, _utf8);

                _xml.WriteStartDocument();

                _xml.WriteStartElement("envEvento");
                if (tpAmb == 1)
                {
                    _xml.WriteStartAttribute("xmlns");
                    _xml.WriteString("http://www.portalfiscal.inf.br/nfe");
                    _xml.WriteEndAttribute();
                    _xml.WriteStartAttribute("versao");
                    _xml.WriteString("1.00");
                    _xml.WriteEndAttribute();
                }
                _xml.WriteStartElement("idLote");//num lote
                _xml.WriteString(_infoNfe.Rows[0]["idlote"].ToString());// numero lote
                _xml.WriteEndElement();

                _xml.WriteStartElement("evento");
                _xml.WriteStartAttribute("xmlns");
                _xml.WriteString("http://www.portalfiscal.inf.br/nfe");
                _xml.WriteEndAttribute();
                _xml.WriteStartAttribute("versao");
                _xml.WriteString("1.00");
                _xml.WriteEndAttribute();
                _xml.WriteStartElement("infEvento");
                _xml.WriteStartAttribute("Id");
                _xml.WriteString("ID" + _tipoEvento + _infoNfe.Rows[0]["chNFe"].ToString() + _seqEvento.ToString("00"));//
                _xml.WriteEndAttribute();
                #region itensInternos

                _xml.WriteStartElement("cOrgao");//num uf ibge
                _xml.WriteString(_infoNfe.Rows[0]["cUF"].ToString());// numero da UF ibge
                _xml.WriteEndElement();

                _xml.WriteStartElement("tpAmb");//num uf ibge
                _xml.WriteString(tpAmb.ToString());// numero da UF ibge
                _xml.WriteEndElement();

                _xml.WriteStartElement("CNPJ");//cnpj emitente
                _xml.WriteString(_cnpjEmi);//
                _xml.WriteEndElement();

                _xml.WriteStartElement("chNFe");//Chave da Nfe 44 posiçoes (nfe antes) NFexxx...
                _xml.WriteString(_infoNfe.Rows[0]["chNFe"].ToString());//
                _xml.WriteEndElement();

                _xml.WriteStartElement("dhEvento");//Serie NFe
                _xml.WriteString(string.Format("{0:yyyy-MM-ddTHH:mm:sszzz}", DateTime.Now));//
                _xml.WriteEndElement();

                _xml.WriteStartElement("tpEvento");//
                _xml.WriteString(_tipoEvento);//
                _xml.WriteEndElement();

                _xml.WriteStartElement("nSeqEvento");//
                _xml.WriteString(_seqEvento.ToString());//
                _xml.WriteEndElement();

                _xml.WriteStartElement("verEvento");//
                _xml.WriteString("1.00");// fixo por hora
                _xml.WriteEndElement();

                _xml.WriteStartElement("detEvento");//abre tag da descrição do envento
                _xml.WriteStartAttribute("versao");//versão
                _xml.WriteString("1.00");// fixo por hora
                _xml.WriteEndAttribute();

                _xml.WriteStartElement("descEvento");//descrição do tipo do envento
                _xml.WriteString(Evento);//
                _xml.WriteEndElement();
//define a mesnagem e campos conforme evento
                switch (Evento)
                {
                    case "Carta de Correcao":
                        /// a sequencia de um mesmo eventdo de cce não pode ser maior que 20 correções
                        if (_seqEvento < 20)
                        {
                            _xml.WriteStartElement("xCorrecao");//Justividativa escrita da cce
                            _xml.WriteString(_comp.RemoveSpecialCharactersXml(Justificativa, true));//
                            _xml.WriteEndElement();

                            _xml.WriteStartElement("xCondUso");//Justividativa escrita da cce
                            _xml.WriteString("A Carta de Correcao e disciplinada pelo paragrafo 1o-A do art. 7o do Convenio S/N," +
                                             " de 15 de dezembro de 1970 e pode ser utilizada para regularizacao de erro ocorrido " +
                                             "na emissao de documento fiscal, desde que o erro nao esteja relacionado com: I - as " +
                                             "variaveis que determinam o valor do imposto tais como: base de calculo, aliquota, " +
                                             "diferenca de preco, quantidade, valor da operacao ou da prestacao; II - a correcao de " +
                                             "dados cadastrais que implique mudanca do remetente ou do destinatario; III - a data de emissao ou de saida.");//
                            _xml.WriteEndElement();
                        }
                        else
                        {
                            throw new Exception("Sequência de correções ultrapassou o limite de 20 para esta nota");
                        }

                        break;
                    case "Cancelamento":
                        _xml.WriteStartElement("nProt");//Numero do protocolo quando aceita a nfe no sefaz
                        _xml.WriteString(_infoNfe.Rows[0]["nProt"].ToString());//
                        _xml.WriteEndElement();

                        _xml.WriteStartElement("xJust");//Justividativa escrita do cancelmaento
                        _xml.WriteString(Justificativa);//
                        _xml.WriteEndElement();
                        break;
                }

                #endregion
                _xml.WriteEndElement();//detEvento
                _xml.WriteEndElement();//infEvento
                _xml.WriteEndElement();//Evento
                _xml.WriteEndElement();//envEvento

                _xml.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                _infoNfe.Dispose();
            }
        }

Comentem se usarem...e melhorem também...
att
Fernando