Ir para conteúdo
  • Cadastre-se

  • Este tópico foi criado há 1708 dias atrás.
  • Talvez seja melhor você criar um NOVO TÓPICO do que postar uma resposta aqui.

Recommended Posts

  • Membro Pro Verificado
Postado (editado)

Caros amigos,

Estou com o seguinte problema quando ocorre instabilidade no servidor de Autorização de NFC-e na Sefaz/MG. Faço a segue rotina a abaixo:

1º Tento enviar NFC-e, exemplo, Número: 20 e ocorre da Sefaz/MG não retorna a autorização;

2º Gero uma nova NFC-e com Número: 21 no modo Contingência/Offline;

3º Após período configurado o sistema tentar enviar as NFC-e em Offline;

4º Já as NFC-e que ficaram pendentes por falta de retorno da Sefaz/MG, eu tento recuperar a NFC-e, caso a mesma não conste na Base da Sefaz/MG eu Inutilizo. Agora se a NFC-e existe na Sefaz/MG faço o Cancelamento por Substituição;

O erro ocorre no momento do Cancelamento por Substituição, assim que cancelo retorna o erro: "DigestValue do documento CHAVE DE ACESSO não confere". Sei que foi cancelada porque pego a chave de acesso e vejo o cancelamento no SPED/MG.

Estava tudo funcionando corretamente, o erro começou após o dia 01/10/2021, abaixo segue o código que estou usando para Cancelamento Por Substituição;

procedure TFrmPDV.CancelamentoSubstituicao;
  var Chave, idLote, CNPJ, Protocolo, Justificativa: string;
begin
  if (Trim(qryNFCeGravadasCHAVE_SUBSTITUTA.Value) <> '') and (qryNFCeGravadasSITUACAO.Value = 'G') then
  begin
    if Length(qryNFCeGravadasCHAVE_SUBSTITUTA.Value) <> 44 then
    begin
      memoLog.Lines.Add(' Erro: Chave de Acesso Substituta invalida! Chave deve Conter 44 números.');
      memoLog.Lines.Add('-----------------------------------------------------------------');
      exit;
    end;
  end;

  // Recuperar o Protocolo
  if (qryNFCeGravadasPROTOCOLO.IsNull) or (Trim(qryNFCeGravadasPROTOCOLO.Value) = '') then
  begin
    if ACBrNFe.WebServices.Consulta.cStat = 100 then
    begin
      qryNFCeGravadas.Edit;
      qryNFCeGravadasCHAVE.Value := copy(ACBrNFe.NotasFiscais.Items[0].NFe.infNFe.id, 4, 100);
      qryNFCeGravadasPROTOCOLO.Value := ACBrNFe.NotasFiscais.Items[0].NFe.procNFe.nProt;
      qryNFCeGravadasXML.Value := ACBrNFe.NotasFiscais.Items[0].XMLAssinado;
      qryNFCeGravadasFLAG.Value := 'N';
      qryNFCeGravadasABERTO.Value := 'N';
      qryNFCeGravadas.Post;
      Dados.Conexao.Commit;
      ACBrNFe.NotasFiscais.Items[0].GravarXML();
    end
    else
    begin
      memoLog.Lines.Add('Status: ' + #13 + IntToStr(ACBrNFe.WebServices.Consulta.cStat) +
       '-' + ACBrNFe.WebServices.Consulta.XMotivo);
      memoLog.Lines.Add('-----------------------------------------------------------------');
      exit;
    end;
  end;

  if (qryNFCeGravadasPROTOCOLO.IsNull) or (Trim(qryNFCeGravadasPROTOCOLO.Value) = '') then
  begin
    memoLog.Lines.Add(' Erro: Não é possível efetuar o Cancelamento da NFC-e! Não Existe Protocolo de Autorização.');
    memoLog.Lines.Add('-----------------------------------------------------------------');
    exit;
  end;

  // Valida se Chave Substituta Foi Transmitida
  Dados.qryConsulta.SQL.Clear;
  Dados.qryConsulta.SQL.Text := 'SELECT NUMERO FROM NFCE_MASTER WHERE SITUACAO=''T'' AND CHAVE=:chave';
  Dados.qryConsulta.Params[0].Value := qryNFCeGravadasCHAVE_SUBSTITUTA.AsString;
  Dados.qryConsulta.Open;

  if Dados.qryConsulta.IsEmpty then
    exit;

  ACBrNFe.Configuracoes.Arquivos.PathEvento := dados.qryConfigPATHCAN.Value;

  try
    Chave := Trim(OnlyNumber(qryNFCeGravadasCHAVE.Value));
    idLote := '1';
    CNPJ := copy(Chave, 7, 14);
    Protocolo := qryNFCeGravadasPROTOCOLO.Value;
    Justificativa := 'Cancelamento Por Substituição Devido a Falta de Retorno no Envio da NFC-e.' +
      ' Assim Foi emitida a NFC-e Nº: '+ IntToStr(qryNFCeGravadasNUMERO.AsInteger + 1) +
      'Série: ' + qryNFCeGravadasSERIE.AsString + ' como Substituta.';

    ACBrNFe.EventoNFe.Evento.Clear;
    with ACBrNFe.EventoNFe.Evento.Add do
    begin
      infEvento.chNFe := Chave;
      infEvento.CNPJ := CNPJ;
      infEvento.dhEvento := now;
      infEvento.tpEvento := teCancSubst;
      infEvento.detEvento.cOrgaoAutor := Dados.qryEmpresaID_UF.Value;
      infEvento.detEvento.tpAutor := taEmpresaEmitente;
      infEvento.detEvento.verAplic := '1';
      infEvento.detEvento.chNFeRef := qryNFCeGravadasCHAVE_SUBSTITUTA.Value;
      infEvento.detEvento.xJust := Justificativa;
      infEvento.detEvento.nProt := Protocolo;
    end;

    ACBrNFe.EnviarEvento(StrToInt(idLote));

    if ACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.cStat = 135 then
    begin
      ACBrNFe.NotasFiscais.Clear;
      ACBrNFe.WebServices.Consulta.NFeChave := qryNFCeGravadasCHAVE.Value;
      ACBrNFe.WebServices.Consulta.Executar;

      if ACBrNFe.WebServices.Consulta.cStat = 101 then
      begin
        qryNFCeGravadas.Edit;
        qryNFCeGravadasSITUACAO.Value := 'C';
        qryNFCeGravadasCANCEL_SUBSTITUICAO.Value := 'C';
        qryNFCeGravadasMOTIVOCANCELAMENTO.Value := Justificativa;
        qryNFCeGravadasFK_VENDA.Clear;
        qryNFCeGravadasFLAG.Value := 'N';
        qryNFCeGravadasABERTO.Value := 'N';
        qryNFCeGravadas.Post;
        Dados.Conexao.Commit;
        ACBrNFe.NotasFiscais.GravarXML();

        memoLog.Lines.Add(' Retorno: 101 - Cancelamento por Substituição');
        memoLog.Lines.Add(' Status: Cancelada');
        memoLog.Lines.Add('-----------------------------------------------------------------');
      end;
    end

    else if ACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.cStat = 910 then
    begin
      memoLog.Lines.Add(' Rejeição 910: Chave de Acesso NF-e Substituta inválida.');
      memoLog.Lines.Add('-----------------------------------------------------------------');
      exit;
    end

    else if ACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.cStat = 911 then
    begin
      memoLog.Lines.Add(' Rejeição 911: Chave de Acesso NF-e Substituta incorreta.');
      memoLog.Lines.Add('-----------------------------------------------------------------');
      exit;
    end

    else if ACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.cStat = 912 then
    begin
      memoLog.Lines.Add(' Rejeição 912: NF-e Substituta inexistente');
      memoLog.Lines.Add('-----------------------------------------------------------------');
      exit;
    end

    else if ACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.cStat = 913 then
    begin
      memoLog.Lines.Add(' Rejeição 913: NF-e Substituta Denegada ou Cancelada.');
      memoLog.Lines.Add('-----------------------------------------------------------------');
      exit;
    end

    else if ACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.cStat = 914 then
    begin
      memoLog.Lines.Add(' Rejeição 914: Data de emissão da NF-e Substituta maior que 2 horas da data de emissão da NFe a ser cancelada.');
      memoLog.Lines.Add('-----------------------------------------------------------------');
      exit;
    end

    else if ACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.cStat = 915 then
    begin
      memoLog.Lines.Add(' Rejeição 915: Valor total da NF-e Substituta difere do valor da NF-e a ser cancelada.');
      memoLog.Lines.Add('-----------------------------------------------------------------');
      exit;
    end

    else if ACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.cStat = 916 then
    begin
      memoLog.Lines.Add(' Rejeição 916: Valor total do ICMS da NF-e Substituta difere do valor da NF-e a ser cancelada.');
      memoLog.Lines.Add('-----------------------------------------------------------------');
      exit;
    end

    else if ACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.cStat = 917 then
    begin
      memoLog.Lines.Add(' Rejeição 917: Identificação do destinatário da NF-e Substituta difere da identificação do destinatário da NF-e a ser cancelada.');
      memoLog.Lines.Add('-----------------------------------------------------------------');
      exit;
    end

    else if ACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.cStat = 918 then
    begin
      memoLog.Lines.Add(' Rejeição 918: Quantidade de itens da NF-e Substituta difere da quantidade de itens da NF-e a ser cancelada.');
      memoLog.Lines.Add('-----------------------------------------------------------------');
      exit;
    end

    else if ACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.cStat = 919 then
    begin
      memoLog.Lines.Add(' Rejeição 919: Item da NF-e Substituta difere do mesmo item da NF-e a ser cancelada.');
      memoLog.Lines.Add('-----------------------------------------------------------------');
      exit;
    end

    else if ACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.cStat = 920 then
    begin
      memoLog.Lines.Add(' Rejeição 920 - Tipo de Emissão inválido no cancelamento por substituição.');
      memoLog.Lines.Add('-----------------------------------------------------------------');
      exit;
    end

    else
    begin
      memoLog.Lines.Add(' Status: ' + IntToStr(ACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.cStat) +
       '-' + ACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.xMotivo);
      memoLog.Lines.Add('-----------------------------------------------------------------');
      exit;
    end;

  except on E: Exception do
    begin
      memoLog.Lines.Add('-----------------------------------------------------------------');
      memoLog.Lines.Add(' ERROR: ' + E.Message);
      memoLog.Lines.Add('-----------------------------------------------------------------');
      exit;
    end;
  end;

end;

 

Desde já agradeço pela atenção e ajuda de todos.

Att, Arthur

Editado por TiicTechnology Sac
  • Moderadores
Postado
12 minutos atrás, TiicTechnology Sac disse:

1º Tento enviar NFC-e, exemplo, Número: 20 e ocorre da Sefaz/MG não retorna a autorização;

Está gravando o XML dessa nota, pra depois tentar consultar e cancelar/inutilizar?

O erro de digest value ocorre na consulta, quando a chave é a mesma mas o conteúdo do XML está diferente do que foi enviado pra SEFAZ.

Equipe ACBr BigWings
Ajude o Projeto ACBr crescer - Assine o SAC

Projeto ACBr

 

 

  • Membro Pro Verificado
Postado
3 minutos atrás, BigWings disse:

Está gravando o XML dessa nota, pra depois tentar consultar e cancelar/inutilizar?

O erro de digest value ocorre na consulta, quando a chave é a mesma mas o conteúdo do XML está diferente do que foi enviado pra SEFAZ.

Primeiramente muito obrigado pela ajuda, BigWings!

Está gravando o XML dessa nota, pra depois tentar consultar e cancelar/inutilizar?

Sim! Eu salvo o XML original que não obtive resposta da Sefaz/MG. Ai depois um "robô" tenta recuperar e cancelar por substituição essa NFC-e.

ACBrNFe.Configuracoes.Arquivos.PathEvento := dados.qryConfigPATHCAN.Value;

  try
    Chave := Trim(OnlyNumber(qryNFCeGravadasCHAVE.Value));
    idLote := '1';
    CNPJ := copy(Chave, 7, 14);
    Protocolo := qryNFCeGravadasPROTOCOLO.Value;
    Justificativa := 'Cancelamento Por Substituição Devido a Falta de Retorno no Envio da NFC-e.' +
      ' Assim Foi emitida a NFC-e Nº: '+ IntToStr(qryNFCeGravadasNUMERO.AsInteger + 1) +
      'Série: ' + qryNFCeGravadasSERIE.AsString + ' como Substituta.';

    ACBrNFe.EventoNFe.Evento.Clear;
    with ACBrNFe.EventoNFe.Evento.Add do
    begin
      infEvento.chNFe := Chave;
      infEvento.CNPJ := CNPJ;
      infEvento.dhEvento := now;
      infEvento.tpEvento := teCancSubst;
      infEvento.detEvento.cOrgaoAutor := Dados.qryEmpresaID_UF.Value;
      infEvento.detEvento.tpAutor := taEmpresaEmitente;
      infEvento.detEvento.verAplic := '1';
      infEvento.detEvento.chNFeRef := qryNFCeGravadasCHAVE_SUBSTITUTA.Value;
      infEvento.detEvento.xJust := Justificativa;
      infEvento.detEvento.nProt := Protocolo;
    end;

    ACBrNFe.EnviarEvento(StrToInt(idLote));

    if ACBrNFe.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento.cStat = 135 then
    begin
      ACBrNFe.NotasFiscais.Clear;
      ACBrNFe.WebServices.Consulta.NFeChave := qryNFCeGravadasCHAVE.Value;
      ACBrNFe.WebServices.Consulta.Executar;

      if ACBrNFe.WebServices.Consulta.cStat = 101 then
      begin
        qryNFCeGravadas.Edit;
        qryNFCeGravadasSITUACAO.Value := 'C';
        qryNFCeGravadasCANCEL_SUBSTITUICAO.Value := 'C';
        qryNFCeGravadasMOTIVOCANCELAMENTO.Value := Justificativa;
        qryNFCeGravadasFK_VENDA.Clear;
        qryNFCeGravadasFLAG.Value := 'N';
        qryNFCeGravadasABERTO.Value := 'N';
        qryNFCeGravadas.Post;
        Dados.Conexao.Commit;
        ACBrNFe.NotasFiscais.GravarXML();

        memoLog.Lines.Add(' Retorno: 101 - Cancelamento por Substituição');
        memoLog.Lines.Add(' Status: Cancelada');
        memoLog.Lines.Add('-----------------------------------------------------------------');
      end;
    end

Continua...

O interessante é que antes o cancelamento por substituição estava funcionando normalmente. Outro detalhe, o XML salvo no banco é o mesmo que tentei enviar sem alteração.

  • Membro Pro Verificado
Postado (editado)

Bom dia, acho que encontrei a solução, fiz o seguinte:

1º Quando tento enviar para a Sefaz/MG e ocorre o erro eu agora salvo o XML Assinado no Banco. Antes estava salvando XML sem assinatura e apenas assinava na hora da consulta;

2º Na hora da Consulta uso o método (ACBrNFe.NotasFiscais.LoadFromString(qryNFCeGravadasXMLASSINADO.Value) com o XML Assinado, garantindo a igualdade dos XML entre Sefaz e meu Sistema;

Estou realizando os teste e em homologação tá tudo certo!

Obrigado.

Editado por TiicTechnology Sac
  • Curtir 2
  • Este tópico foi criado há 1708 dias atrás.
  • Talvez seja melhor você criar um NOVO TÓPICO do que postar uma resposta aqui.
Visitante
Este tópico está agora fechado para novas respostas
×
×
  • Criar Novo...

Informação Importante

Colocamos cookies em seu dispositivo para ajudar a tornar este site melhor. Você pode ajustar suas configurações de cookies, caso contrário, assumiremos que você está bem para continuar.

The popup will be closed in 10 segundos...
The popup will be closed in 10 segundos...