Ir para conteúdo
  • Cadastre-se

dev botao

DistribuicaoDfe.txt Decifrado para baixar xml da Sefaz


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

Recommended Posts

Depois de uma semana pesquisando na net, perguntando pra um e pra outro, consegui baixar as notas da sefaz.

Estar qui caso algum colega precise.

Este primeiro processo é para mostrar as notas que estão na sefaz

procedure TTesteWeb.consultarnotasClick(Sender: TObject);
var
CNPJ, Impresso, sChave, sEmissao, sCNPJ, sNome, sNumero, sSerie,
sIEst, sNSU, sTipoNFe: String;
Valor: Double;
i, j,iEvento, k: integer;
sStat,utNSU,ANSU:string;
sMotivo:string;
sUltimoNSU:string;
sTemMais:string;
caminho:string;
UF, icount, codStatus: Integer;
xml:string;
begin
// ======== Dados do Emitente =============================================

//pego o codigo da Filial que estar fazendo
// a pesquisa no meu cadastro de empresas
Empresa.Close;
Empresa.SQL.Clear;
Empresa.SQL.Add('Select * From filial');
Empresa.SQL.Add('Where CodFil = :xCodigo');
Empresa.Params[0].AsString:='1';
Empresa.Active:=True;
Empresa.Open;

MemoStatus.Lines.Add('------------------------------------------------------');
MemoStatus.Lines.Add(' => Consultando NFe Destinadas');
MemoStatus.Lines.Add('------------------------------------------------------');

Memo1.Text := '';
k := 0;
repeat
inc(k);
CNPJ := '';
ACBrNFe1.DistribuicaoDFePorUltNSU(EMPRESAUF.AsInteger,CNPJ,edtUltNSU.Text );

sStat := IntToStr(ACBrNFe1.WebServices.DistribuicaoDFe.retDistDFeInt.cStat);
sMotivo := ACBrNFe1.WebServices.DistribuicaoDFe.retDistDFeInt.xMotivo;

if ACBrNFe1.WebServices.DistribuicaoDFe.retDistDFeInt.cStat = 137
then sTemMais := 'N'
else sTemMais := 'S';

sUltimoNSU := ACBrNFe1.WebServices.DistribuicaoDFe.retDistDFeInt.ultNSU;

// GravaUltimaConsulta;

if ACBrNFe1.WebServices.DistribuicaoDFe.retDistDFeInt.cStat = 138
then begin
MemoStatus.Lines.Add(' Documento Localizado para o Destinatário');
MemoStatus.Lines.Add(' Utilizar o número que esta no campo: Último NSU');
MemoStatus.Lines.Add(' Para uma nova pesquisa.');
MemoStatus.Lines.Add(' ');

j := ACBrNFe1.WebServices.DistribuicaoDFe.retDistDFeInt.docZip.Count - 1;
lstChave1.Clear;
chkListaNotas.Clear;

for i := 0 to j do
begin
sSerie := '';
sNumero := '';
sCNPJ := '';
sNome := '';
sIEst := '';
sNSU := '';
sEmissao := '';
sTipoNFe := '';
Valor := 0.0;
Impresso := ' ';

if ACBrNFe1.WebServices.DistribuicaoDFe.retDistDFeInt.docZip.Items.resNFe.chNFe <> ''
then begin
// Conjunto de informações resumo da NF-e localizadas.
// Este conjunto de informação será gerado quando a NF-e for autorizada ou denegada.

sChave := ACBrNFe1.WebServices.DistribuicaoDFe.retDistDFeInt.docZip.Items.resNFe.chNFe;

sSerie := Copy(sChave, 23, 3);
sNumero := Copy(sChave, 26, 9);
sCNPJ := '';
sNome := ACBrNFe1.WebServices.DistribuicaoDFe.retDistDFeInt.docZip.Items.resNFe.xNome;
sIEst := ACBrNFe1.WebServices.DistribuicaoDFe.retDistDFeInt.docZip.Items.resNFe.IE;
case ACBrNFe1.WebServices.DistribuicaoDFe.retDistDFeInt.docZip.Items.resNFe.tpNF of
tnEntrada: sTipoNFe := 'E';
tnSaida: sTipoNFe := 'S';
end;
sNSU := ACBrNFe1.WebServices.DistribuicaoDFe.retDistDFeInt.docZip.Items.NSU;
sEmissao := DateToStr(ACBrNFe1.WebServices.DistribuicaoDFe.retDistDFeInt.docZip.Items.resNFe.dhEmi);
Valor := ACBrNFe1.WebServices.DistribuicaoDFe.retDistDFeInt.docZip.Items.resNFe.vNF;

case ACBrNFe1.WebServices.DistribuicaoDFe.retDistDFeInt.docZip.Items.resNFe.cSitNFe of
snAutorizado: Impresso := 'A';
snDenegado: Impresso := 'D';
// snCancelada: Impresso := 'C';
end;
end;

// Registra no Banco de Dados as Notas Retornadas pela Consulta
Manifestacao.Close;
Manifestacao.SQL.Clear;
Manifestacao.SQL.Add('Select * From manifestacao');
Manifestacao.SQL.Add('Where Empresa = :xEmpresa');
Manifestacao.SQL.Add('and Chave = :xChave');
Manifestacao.Params[0].AsString:='1';
Manifestacao.Params[1].AsString:=sChave;
Manifestacao.Active:=True;
Manifestacao.Open;

if not ((ManifestacaoEmpresa.AsString = '1') and
(ManifestacaoChave.AsString = sChave))

then begin
IncAltDel.SQL.Clear;
IncAltDel.SQL.Add('Insert into manifestacao');
IncAltDel.SQL.Add('(Empresa, Chave, CNPJ, Nome, IE, Emissao, Tipo, Valor,');
IncAltDel.SQL.Add('Situacao, Confirmacao, NSU, DataEvento, Protocolo)');
IncAltDel.SQL.Add('Values (:xEmpresa, :xChave, :xCNPJ, :xNome, :xIE, :xEmissao, :xTipo,');
IncAltDel.SQL.Add(':xValor, :xSituacao, :xConfirmacao, :xNSU, :xDataEve, :xProtocolo)');
IncAltDel.Params[0].AsString:='1';
IncAltDel.Params[1].AsString:=sChave;
IncAltDel.Params[2].AsString:='';
IncAltDel.Params[3].AsString:=sNome;
IncAltDel.Params[4].AsString:=sIEst;
IncAltDel.Params[5].AsDateTime:=StrToDate(sEmissao);
IncAltDel.Params[6].AsString:=sTipoNFe;
IncAltDel.Params[7].AsFloat:=Valor;
IncAltDel.Params[8].AsString:=Impresso;
IncAltDel.Params[9].AsInteger:=-1;
IncAltDel.Params[10].AsString:=sNSU;
IncAltDel.Params[11].AsDateTime:=0;
IncAltDel.Params[12].AsString:='';
IncAltDel.ExecSQL;
end;

//Atualizo o sql que mostra as notas no dbgrid
MANIFESTACAO.Close;
MANIFESTACAO.SQL.Clear;
MANIFESTACAO.SQL.Add('select * from manifestacao');
MANIFESTACAO.open;

end; // Fim do For
end
else begin
// Nenhum Documento Localizado para o Destinatário
if ACBrNFe1.WebServices.DistribuicaoDFe.retDistDFeInt.cStat = 137
then begin
MemoStatus.Lines.Add(' Nenhum Documento Localizado para o Destinatário');
MemoStatus.Lines.Add(' Utilizar o número que esta no campo: Último NSU');
MemoStatus.Lines.Add(' Para uma nova pesquisa ('+edtUltNSU.Text+').');
MemoStatus.Lines.Add(' ');
end
else begin
MemoStatus.Lines.Add(' Falha ao realizar a consulta.');
MemoStatus.Lines.Add(' ' + sStat + ' - ' + sMotivo);
MemoStatus.Lines.Add(' ');
end;
end;

until (k = StrToIntDef(edtConsultas.Text, 1)) or (sTemMais = 'S');

ACBrNFe1.Configuracoes.Arquivos.Salvar := True;

if sTemMais = 'S'
then Memo1.Text := IntToStr(k) + ' Consultas Realizadas e tem mais Documentos.'
else Memo1.Text := IntToStr(k) + ' Consultas Realizadas e não tem mais Documentos.';

end;

=========================================
Este segundo processo é para fazer a confirmação
de uma nota pela chave, vc pode fazer a
confirmação de todas as notas que
baixou no primeiro processo e depois
efetuar o download.

procedure TTesteWeb.EnviarManifesClick(Sender: TObject);
var
Chave, idLote, CNPJ: string;
lMsg: string;
begin

// manidestação de uma nota especifica pela chave

Chave:='';
if not(InputQuery('WebServices Eventos: Manif. Destinatario - Conf. Operacao', 'Chave da NF-e', Chave)) then
exit;
Chave := Trim(OnlyNumber(Chave));

idLote := '1';
if not(InputQuery('WebServices Eventos: Manif. Destinatario - Conf. Operacao', 'Identificador de controle do Lote de envio do Evento', idLote)) then
exit;

CNPJ := '';
if not(InputQuery('WebServices Eventos: Manif. Destinatario - Conf. Operacao', 'CNPJ ou o CPF do autor do Evento', CNPJ)) then
exit;

ACBrNFe1.EventoNFe.Evento.Clear;
with ACBrNFe1.EventoNFe.Evento.Add do
begin
InfEvento.cOrgao := 91;
infEvento.chNFe := Chave;
infEvento.CNPJ := CNPJ;
infEvento.dhEvento := now;
infEvento.tpEvento := teManifDestConfirmacao;
end;
ACBrNFe1.EnviarEvento(StrToInt(IDLote));

with AcbrNFe1.WebServices.EnvEvento.EventoRetorno.retEvento.Items[0].RetInfEvento do
begin
lMsg:=
'Id: '+Id+#13+
'tpAmb: '+TpAmbToStr(tpAmb)+#13+
'verAplic: '+verAplic+#13+
'cOrgao: '+IntToStr(cOrgao)+#13+
'cStat: '+IntToStr(cStat)+#13+
'xMotivo: '+xMotivo+#13+
'chNFe: '+chNFe+#13+
'tpEvento: '+TpEventoToStr(tpEvento)+#13+
'xEvento: '+xEvento+#13+
'nSeqEvento: '+IntToStr(nSeqEvento)+#13+
'CNPJDest: '+CNPJDest+#13+
'emailDest: '+emailDest+#13+
'dhRegEvento: '+DateTimeToStr(dhRegEvento)+#13+
'nProt: '+nProt;
end;
ShowMessage(lMsg);

MemoResp.Lines.Text := ACBrNFe1.WebServices.EnvEvento.RetWS;
memoRespWS.Lines.Text := ACBrNFe1.WebServices.EnvEvento.RetornoWS;
LoadXML(ACBrNFe1.WebServices.EnvEvento.RetornoWS, WBResposta);
end;

=======================================
verifique agora se estas configurações estão certas no seu componente ACBRNFe:
propriedades\configurações\arquivos\PathDownload = aqui a pasta onde vc quer salvar os xml.
propriedades\configurações\arquivos\PathEvento = Salvar os eventos.
propriedades\configurações\arquivos\salvar = true

Ainda em configurações de arquivos tem as opções separar por cnpj, ele cria uma pasta para cada cnpj que vc baixar

e execute o primeiro processo novamente, ele vai fazer uma nova busca e baixar os que vc confimou

teste ai e me diga o resultado

Comigo funcionou certinho.

  • Curtir 3
  • Obrigado 1
Link para o comentário
Compartilhar em outros sites

  • Administradores

Bom dia.

Obrigada por compartilhar.

Att.

  • Curtir 1
Consultora SAC ACBr

Juliana Tamizou

Gerente de Projetos ACBr / Diretora de Marketing AFRAC
Ajude o Projeto ACBr crescer - Seja Pro

Projeto ACBr     Telefone:(15) 2105-0750 WhatsApp(15)99790-2976.  Discord

Projeto ACBr - A maior comunidade Open Source de Automação Comercial do Brasil


Participe de nosso canal no Discord e fique ainda mais próximo da Comunidade !!

Link para o comentário
Compartilhar em outros sites

  • Este tópico foi criado há 2045 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...