private async Task <string> GetNotaXmlAsync() { var config = await _configuracaoService.GetConfiguracaoAsync(); var ambiente = config.IsProducao ? Ambiente.Producao : Ambiente.Homologacao; var notaDb = _notaFiscalRepository.GetNotaFiscalByChave(NotaFiscal.Chave); string xml = await notaDb.LoadXmlAsync(); return(xml); }
public MensagemRetornoEventoCancelamento CancelarNotaFiscal(string ufEmitente, CodigoUfIbge codigoUf, Ambiente ambiente, string cnpjEmitente, string chaveNFe, string protocoloAutorizacao, Modelo modeloNota, string justificativa) { var resultadoCancelamento = _nfeCancelamento.CancelarNotaFiscal(ufEmitente, codigoUf, ambiente, cnpjEmitente, chaveNFe, protocoloAutorizacao, modeloNota, justificativa); if (resultadoCancelamento.Status != StatusEvento.SUCESSO) { return(resultadoCancelamento); } var notaFiscalEntity = _notaFiscalRepository.GetNotaFiscalByChave(chaveNFe); _eventoService.Salvar(new EventoEntity { DataEvento = DateTime.ParseExact(resultadoCancelamento.DataEvento, "yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture), TipoEvento = resultadoCancelamento.TipoEvento, Xml = resultadoCancelamento.Xml, NotaId = notaFiscalEntity.Id, ChaveIdEvento = resultadoCancelamento.IdEvento.Replace("ID", string.Empty), MotivoCancelamento = resultadoCancelamento.MotivoCancelamento, ProtocoloCancelamento = resultadoCancelamento.ProtocoloCancelamento }); notaFiscalEntity.Status = (int)Status.CANCELADA; _notaFiscalRepository.Salvar(notaFiscalEntity, null); return(resultadoCancelamento); }
public EventoEntity GetEventoCancelamentoFromXml(string xml, string file, INotaFiscalRepository notaFiscalRepository) { var procEvento = (TProcEvento)XmlUtil.Deserialize <TProcEvento>(xml); var envInfEvento = procEvento.evento.infEvento; var notaFiscal = notaFiscalRepository.GetNotaFiscalByChave(envInfEvento.chNFe, (int)envInfEvento.tpAmb + 1); if (notaFiscal == null) { throw new ArgumentException("Nota fiscal relacionada ao evento não existe na base de dados."); } var evento = new EventoEntity { TipoEvento = envInfEvento.tpEvento, DataEvento = DateTime.ParseExact(envInfEvento.dhEvento, "yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture), ChaveIdEvento = envInfEvento.Id, MotivoCancelamento = envInfEvento.detEvento.Any[2].InnerText, ProtocoloCancelamento = envInfEvento.detEvento.Any[1].InnerText, NotaId = notaFiscal.Id }; return(evento); }
private async void EnviarEmailCmd_Execute(IClosable closable) { var config = await _configuracaoService.GetConfiguracaoAsync(); var notaFiscal = _notaFiscalRepository.GetNotaFiscalByChave(Chave, config.IsProducao ? 1 : 2); string xmlPath = notaFiscal.XmlPath; _mailManager.EnviarEmailDestinatario(Email, xmlPath, notaFiscal); Email = string.Empty; closable.Close(); }
private void EnviarCancelamentoCmd_Execute(Window window) { ValidateModel(); if (!HasErrors) { var mensagemRetorno = _cancelaNotaFiscalService.CancelarNotaFiscal(UF, CodigoUF, Ambiente, Cnpj, Chave, Protocolo, ModeloNota, MotivoCancelamento); if (mensagemRetorno.Status == StatusEvento.SUCESSO) { var notaCancelada = _notaFiscalRepository.GetNotaFiscalByChave(Chave); NotaCanceladaEvent(notaCancelada); MessageBox.Show("Nota cancelada com sucesso!", "Sucesso!", MessageBoxButton.OK, MessageBoxImage.Information); } else { MessageBox.Show(mensagemRetorno.Mensagem, "Erro!", MessageBoxButton.OK, MessageBoxImage.Information); } window.Close(); } }
private async Task ImportarXmlNotasFiscais(string path) { var regex = new Regex(@"[0-9]{44}-nf[c|e][e]?"); var files = Directory.EnumerateFiles(path, "*.xml").Where(f => regex.IsMatch(f)); await Task.Run(() => { foreach (var file in files) { try { var xml = File.ReadAllText(file); var notaFiscal = _notaFiscalRepository.GetNotaFiscalFromNfeProcXml(xml); var notaFiscalDb = _notaFiscalRepository.GetNotaFiscalByChave(notaFiscal.Identificacao.Chave); if (notaFiscalDb != null) { return; } var notaFiscalEntity = new NotaFiscalEntity(); if (notaFiscal.Destinatario != null && notaFiscal.Destinatario.Endereco != null) { notaFiscalEntity.UfDestinatario = notaFiscal.Destinatario.Endereco.UF; } else { notaFiscalEntity.UfDestinatario = notaFiscal.Emitente.Endereco.UF; } notaFiscalEntity.Destinatario = notaFiscal.Destinatario == null ? "CONSUMIDOR NÃO IDENTIFICADO" : notaFiscal.Destinatario.NomeRazao; notaFiscalEntity.DocumentoDestinatario = notaFiscal.Destinatario == null ? null : notaFiscal.Destinatario.Documento; notaFiscalEntity.Status = (int)notaFiscal.Identificacao.Status; notaFiscalEntity.Chave = notaFiscal.Identificacao.Chave; notaFiscalEntity.DataEmissao = notaFiscal.Identificacao.DataHoraEmissao; notaFiscalEntity.Modelo = notaFiscal.Identificacao.Modelo == Modelo.Modelo55 ? "55" : "65"; notaFiscalEntity.Serie = notaFiscal.Identificacao.Serie.ToString(); notaFiscalEntity.TipoEmissao = notaFiscal.Identificacao.TipoEmissao.ToString(); notaFiscalEntity.ValorDesconto = notaFiscal.TotalNFe.IcmsTotal.ValorTotalDesconto; notaFiscalEntity.ValorDespesas = notaFiscal.TotalNFe.IcmsTotal.ValorDespesasAcessorias; notaFiscalEntity.ValorFrete = notaFiscal.TotalNFe.IcmsTotal.ValorTotalFrete; notaFiscalEntity.ValorICMS = notaFiscal.TotalNFe.IcmsTotal.ValorTotalIcms; notaFiscalEntity.ValorProdutos = notaFiscal.ValorTotalProdutos; notaFiscalEntity.ValorSeguro = notaFiscal.TotalNFe.IcmsTotal.ValorTotalSeguro; notaFiscalEntity.ValorTotal = notaFiscal.TotalNFe.IcmsTotal.ValorTotalNFe; notaFiscalEntity.Ambiente = notaFiscal.Identificacao.Ambiente == Ambiente.Homologacao ? 2 : 1; notaFiscalEntity.Numero = notaFiscal.Identificacao.Numero; notaFiscalEntity.IsProducao = notaFiscal.Identificacao.Ambiente == Ambiente.Producao; notaFiscalEntity.DataAutorizacao = DateTime.ParseExact(notaFiscal.DhAutorizacao, "yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture); notaFiscalEntity.Protocolo = notaFiscal.ProtocoloAutorizacao; notaFiscalEntity.XmlPath = GetFullPath(file); _notaFiscalRepository.Salvar(notaFiscalEntity, xml); } catch (Exception e) { log.Error(e); } } }); }
private async Task<List<string>> TransmitirConsultarLoteContingenciaAsync(ConfiguracaoEntity config, List<string> notasNfCe, Modelo modelo) { var retornoTransmissao = TransmitirLoteNotasFiscaisContingencia(notasNfCe, modelo); switch (retornoTransmissao.TipoMensagem) { case TipoMensagem.ErroValidacao: return new List<string> { retornoTransmissao.Mensagem }; case TipoMensagem.ServicoIndisponivel: return new List<string> { MensagemErro }; } var tempoEspera = int.Parse(retornoTransmissao.RetEnviNFeInfRec.tMed) * 1000; var 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 nota = _notaFiscalRepository.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)Status.ENVIADA; var xml = await nota.LoadXmlAsync(); xml = xml.Replace("<protNFe />", resultado.Xml); _notaFiscalRepository.Salvar(nota, xml); } else { if (resultado.Motivo.Contains("Duplicidade")) { X509Certificate2 certificado; var certificadoEntity = _certificadoRepository.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)Status.ENVIADA; var xml = await nota.LoadXmlAsync(); xml = xml.Replace("<protNFe />", protSerialized); _notaFiscalRepository.Salvar(nota, xml); } else { erros.Add( $"Modelo: {nota.Modelo} Nota: {nota.Numero} Série: {nota.Serie} \nMotivo: {resultado.Motivo}"); //O que fazer com essas mensagens de erro? } } else { erros.Add( $"Modelo: {nota.Modelo} Nota: {nota.Numero} Série: {nota.Serie} \nMotivo: {resultado.Motivo}"); //O que fazer com essas mensagens de erro? } } } return erros; }
private async void EnviarNotaNovamenteCmd_ExecuteAsync(NotaFiscalMemento notaPendenteMemento) { IsBusy = true; BusyContent = "Enviando..."; var config = _configuracaoService.GetConfiguracao(); var modelo = notaPendenteMemento.Tipo == "NFC-e" ? Modelo.Modelo65 : Modelo.Modelo55; //Preencher objeto da NotaFiscal a partir do XML e enviar para a correspondente ViewModel NFe ou NFCe var app = Application.Current; var mainWindow = app.MainWindow; if (!_consultaStatusServicoService.ExecutarConsultaStatus(config, modelo)) { MessageBox.Show(mainWindow, "Serviço continua indisponível. Aguarde o reestabelecimento da conexão e tente novamente.", "Erro de conexão ou serviço indisponível", MessageBoxButton.OK, MessageBoxImage.Information); return; } var ambiente = config.IsProducao ? Ambiente.Producao : Ambiente.Homologacao; var notaFiscalDb = _notaFiscalRepository.GetNotaFiscalByChave(notaPendenteMemento.Chave); var xml = await notaFiscalDb.LoadXmlAsync(); var notaFiscalBo = _notaFiscalRepository.GetNotaFiscalFromNfeProcXml(xml); notaFiscalBo.Identificacao.DataHoraEmissao = DateTime.Now; foreach (var prod in notaFiscalBo.Produtos) { var produtoDb = _produtoService.GetByCodigo(prod.Codigo); prod.Id = produtoDb.Id; } try { var cscId = ambiente == Ambiente.Homologacao ? config.CscIdHom : config.CscId; var csc = ambiente == Ambiente.Homologacao ? config.CscHom : config.Csc; _notaFiscalRepository.ExcluirNota(notaPendenteMemento.Chave, ambiente); _enviaNotaFiscalService.EnviarNotaFiscal(notaFiscalBo, cscId, csc); IsBusy = false; var mbResult = MessageBox.Show(mainWindow, "Nota enviada com sucesso! Deseja imprimi-la?", "Emissão NFe", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No); if (mbResult == MessageBoxResult.Yes) { BusyContent = "Gerando impressão..."; IsBusy = true; await GeradorPDF.GerarPdfNotaFiscal(notaFiscalBo); } IsBusy = false; var notaIndex = NotasFiscais.IndexOf(notaPendenteMemento); Destinatario destinatario; var destinatarioUf = notaFiscalBo.Emitente.Endereco.UF; if (notaFiscalBo.Destinatario != null) { destinatario = notaFiscalBo.Destinatario; destinatarioUf = destinatario.Endereco != null ? destinatario.Endereco.UF : destinatarioUf; } else { destinatario = new Destinatario("CONSUMIDOR NÃO IDENTIFICADO"); } var valorTotalProdutos = notaFiscalBo.ValorTotalProdutos.ToString("N2", new CultureInfo("pt-BR")); var notaMemento = new NotaFiscalMemento(notaFiscalBo.Identificacao.Numero, notaFiscalBo.Identificacao.Modelo, notaFiscalBo.Identificacao.DataHoraEmissao, notaFiscalBo.DataHoraAutorização, destinatario.NomeRazao, destinatarioUf, valorTotalProdutos, notaFiscalBo.Identificacao.Status, notaFiscalBo.Identificacao.Chave); NotasFiscais[notaIndex] = notaMemento; NotaPendenteReenviadaEvent(notaFiscalBo); } catch (Exception e) { log.Error(e); MessageBox.Show(mainWindow, "Ocorreram os seguintes erros ao tentar enviar a nota fiscal:\n\n" + e.InnerException.Message, "Erro", MessageBoxButton.OK, MessageBoxImage.Information); } }