Exemplo n.º 1
0
        private List <string> GerarNotaFiscal(int grvId, string identificadorNota, int usuarioId, bool isDev)
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("pt-BR");

            DataBase.SystemEnvironment = isDev ? SystemEnvironment.Development : SystemEnvironment.Production;

            DataBase.SetContextInfo(usuarioId);

            var acao = Acao.Solicitação;

            var returnList = new List <string>();

            #region NFe
            var NfeList = new List <NfeEntity>();

            // STATUS:
            //   C: Cadastro;
            //   A: Aguardando Processamento (envio da solicitação com sucesso, para a Prefeitura);
            //   P: Processado (download da Nfe e atualização da Nfe no Sistema concluídos com sucesso);
            //   R: Reprocessar (marcação manual para o envio de uma nova solicitação de Nfe para o mesmo GRV, esta opção gera um novo registro de Nfe);
            //   S: Aguardando Reprocessamento;
            //   T: Reprocessado (conclusão do reprocessamento);
            //   N: CaNcelado.
            //   E: Erro (quando a Prefeitura indicou algum problema);
            //   I: Inválido (quando ocorreu um erro Mob-Link);
            //   M: Cadastro Manual

            var Nfe = new NfeEntity
            {
                GrvId = grvId,

                IdentificadorNota = identificadorNota
            };

            if (!string.IsNullOrWhiteSpace(Nfe.IdentificadorNota))
            {
                Nfe = new NfeController().Selecionar(Nfe, true);

                if (Nfe == null)
                {
                    new NfeWsErroController().CadastrarErroGenerico(Nfe.GrvId, usuarioId, Nfe.IdentificadorNota, OrigemErro.MobLink, acao, "Nota Fiscal não encontrada");

                    returnList.Add("AVISO: Nota Fiscal não encontrada");

                    return(returnList);
                }

                // Erro / Inválido / Cancelado
                if (Nfe.Status != 'E' && Nfe.Status != 'I' && Nfe.Status != 'N')
                {
                    new NfeWsErroController().CadastrarErroGenerico(Nfe.GrvId, usuarioId, Nfe.IdentificadorNota, OrigemErro.MobLink, acao, "Nota Fiscal não está apto para reprocessamento");

                    returnList.Add("AVISO: Nota Fiscal não está apto para reprocessamento");

                    return(returnList);
                }
            }
            else if ((NfeList = new NfeController().Listar(Nfe)) != null)
            {
                var status = new char[] { 'C', 'A', 'P', 'R', 'S', 'T', 'M' };

                if (NfeList.Where(w => status.Contains(w.Status)).Count() > 0)
                {
                    if (NfeList.Count == 1)
                    {
                        Nfe = NfeList.FirstOrDefault();

                        if (Nfe.Status == 'C' && Nfe.DataCadastro.Date < DateTime.Now.Date)
                        {
                            Nfe.Status = 'I';

                            new NfeController().Atualizar(Nfe);
                        }
                        else
                        {
                            new NfeWsErroController().CadastrarErroGenerico(grvId, usuarioId, identificadorNota, OrigemErro.MobLink, acao, "GRV já possui Nota Fiscal cadastrada");

                            returnList.Add("AVISO: GRV já possui Nota Fiscal cadastrada");

                            return(returnList);
                        }
                    }
                    else
                    {
                        new NfeWsErroController().CadastrarErroGenerico(grvId, usuarioId, identificadorNota, OrigemErro.MobLink, acao, "GRV já possui Nota Fiscal cadastrada");

                        returnList.Add("AVISO: GRV já possui Nota Fiscal cadastrada");

                        return(returnList);
                    }
                }
            }
            #endregion NFe

            // GRV
            var grv = new GrvController().Selecionar(grvId);

            // Cliente
            var Cliente = new ClienteController().Selecionar(grv.ClienteId);

            // Depósito
            var Deposito = new DepositoController().Selecionar(grv.DepositoId);

            // Cliente Depósito
            var ClienteDeposito = new ClienteDepositoController().Selecionar(new ClienteDepositoEntity {
                ClienteId = grv.ClienteId, DepositoId = grv.DepositoId
            });

            #region Regras da Nfe
            var NfeRegras = new NfeRegraController().Listar(new NfeRegraEntity
            {
                ClienteDepositoId = ClienteDeposito.ClienteDepositoId,

                Ativo = 1,

                RegraAtivo = 1
            });
            #endregion Regras da Nfe

            #region Regras do Faturamento
            if (new RegraFaturamentoController().Selecionar(grv.ClienteId, grv.DepositoId, new TipoRegraFaturamentoController().Selecionar("NFE").FaturamentoRegraTipoId) == null)
            {
                new NfeWsErroController().CadastrarErroGenerico(grvId, usuarioId, identificadorNota, OrigemErro.MobLink, acao, "CLIDEP sem regra de NFE definido");

                returnList.Add("AVISO: CLIDEP sem regra de NFE definido");

                return(returnList);
            }
            #endregion Regras do Faturamento

            #region Empresa
            var Empresa = new EmpresaEntity();

            if ((Empresa = new EmpresaController().Selecionar(new EmpresaEntity {
                EmpresaId = ClienteDeposito.EmpresaId
            })) == null)
            {
                new NfeWsErroController().CadastrarErroGenerico(grvId, usuarioId, identificadorNota, OrigemErro.MobLink, acao, "Empresa associada não encontrada");

                returnList.Add("AVISO: Empresa associada não encontrada");

                return(returnList);
            }
            #endregion Empresa

            #region Atendimento
            var Atendimento = new AtendimentoEntity();

            if ((Atendimento = new AtendimentoController().Selecionar(grvId)) == null)
            {
                new NfeWsErroController().CadastrarErroGenerico(grvId, usuarioId, identificadorNota, OrigemErro.MobLink, acao, "Atendimento não encontrado");

                returnList.Add("AVISO: Atendimento não encontrado");

                return(returnList);
            }
            #endregion Atendimento

            #region Faturamento
            var Faturamentos = new List <FaturamentoEntity>();

            if ((Faturamentos = new FaturamentoController().Listar(Atendimento.AtendimentoId, 'P')) == null)
            {
                new NfeWsErroController().CadastrarErroGenerico(grvId, usuarioId, identificadorNota, OrigemErro.MobLink, acao, "Faturamento não encontrado");

                returnList.Add("AVISO: Faturamento não encontrado ou sem valor para pagamento");

                return(returnList);
            }
            #endregion Faturamento

            #region Valores somados da Composição do Faturamento
            var ComposicoesAgrupadas = new List <NfeViewFaturamentoComposicaoAgrupadoEntity>();

            if ((ComposicoesAgrupadas = new NfeViewFaturamentoComposicaoAgrupadoController().Listar(grvId)) == null)
            {
                new NfeWsErroController().CadastrarErroGenerico(grvId, usuarioId, identificadorNota, OrigemErro.MobLink, acao, "Composição do Faturamento não encontrada");

                returnList.Add("AVISO: Composição do Faturamento não encontrado");

                return(returnList);
            }
            #endregion Valores somados da Composição do Faturamento

            #region Valores somados da Composição do Faturamento
            var ComposicoesAgrupadasDescricao = new List <NfeViewFaturamentoComposicaoAgrupadoDescricaoEntity>();

            if ((ComposicoesAgrupadasDescricao = new NfeViewFaturamentoComposicaoAgrupadoDescricaoController().Listar(grvId)) == null)
            {
                new NfeWsErroController().CadastrarErroGenerico(grvId, usuarioId, identificadorNota, OrigemErro.MobLink, acao, "Composição do Faturamento não encontrada");

                returnList.Add("AVISO: Composição do Faturamento não encontrado");

                return(returnList);
            }
            #endregion Valores somados da Composição do Faturamento

            #region Composições
            var Composicoes = new List <NfeViewFaturamentoComposicaoEntity>();

            if ((Composicoes = new NfeViewFaturamentoComposicaoController().Listar(grvId, Nfe.NfeId)) == null)
            {
                new NfeWsErroController().CadastrarErroGenerico(grvId, usuarioId, identificadorNota, OrigemErro.MobLink, acao, "Composição do Faturamento da Nota Fiscal não encontrada");

                returnList.Add("AVISO: Composição do Faturamento não encontrado");

                return(returnList);
            }
            #endregion Composições

            if (Nfe.NfeId > 0)
            {
                var Composicao = Composicoes.FirstOrDefault();

                ComposicoesAgrupadas = ComposicoesAgrupadas.Where(w => w.CnaeId == Composicao.CnaeId && w.ListaServicoId == Composicao.ListaServicoId).ToList();

                ComposicoesAgrupadasDescricao = ComposicoesAgrupadasDescricao.Where(w => w.CnaeId == Composicao.CnaeId && w.ListaServicoId == Composicao.ListaServicoId).ToList();
            }

            var CapaAutorizacaoNfse = new CapaAutorizacaoNfse();

            string json;

            List <NfeFaturamentoComposicaoEntity> NfeFaturamentoComposicaoList;

            StringBuilder descricaoConfiguracaoNfe = new StringBuilder();

            foreach (var agrupamento in ComposicoesAgrupadas)
            {
                descricaoConfiguracaoNfe = new StringBuilder();

                var aux = ComposicoesAgrupadasDescricao.Where(w => w.CnaeId == agrupamento.CnaeId && w.ListaServicoId == agrupamento.ListaServicoId).ToList();

                foreach (var item in aux)
                {
                    if (item.TipoDesconto != '\0')
                    {
                        descricaoConfiguracaoNfe.Append(item.DescricaoConfiguracaoNfe).Append(". QTD: ").Append(string.Format("{0:N2}", item.QuantidadeComposicao)).Append(". VALOR: R$ ").Append(string.Format("{0:N2}", item.ValorTipoComposicao)).Append(". DSCT: R$ ").Append(string.Format("{0:N2}", item.ValorDesconto)).Append(". TOT: R$ ").AppendLine(string.Format("{0:N2}", item.TotalComDesconto));
                    }
                    else
                    {
                        descricaoConfiguracaoNfe.Append(item.DescricaoConfiguracaoNfe).Append(". QTD: ").Append(string.Format("{0:N2}", item.QuantidadeComposicao)).Append(". VALOR: R$ ").Append(string.Format("{0:N2}", item.ValorTipoComposicao)).Append(". TOT: R$ ").AppendLine(string.Format("{0:N2}", item.TotalComDesconto));
                    }
                }

                #region Preenchimento da Entidade
                try
                {
                    CapaAutorizacaoNfse = new CapaAutorizacaoNfse
                    {
                        GrvId = grvId,

                        IdentificadorNota = new DetranController().GetDetranSequence("NFE"),

                        UsuarioId = usuarioId,

                        Homologacao = isDev,

                        Autorizacao = Autorizar(grv, Deposito, ClienteDeposito, NfeRegras, Empresa, Atendimento, agrupamento, descricaoConfiguracaoNfe.ToString().Trim(), isDev)
                    };
                }
                catch (Exception ex)
                {
                    new NfeWsErroController().CadastrarErroGenerico(grvId, usuarioId, identificadorNota, OrigemErro.MobLink, acao, ex.Message);

                    returnList.Add(ex.Message);

                    continue;
                }
                #endregion Preenchimento da Entidade


                #region Cadastro do Envio/Reenvio
                try
                {
                    if (Nfe.NfeId == 0)
                    {
                        // Cadastro do Envio
                        Nfe = CadastrarNfe(grvId, Empresa.Cnpj, CapaAutorizacaoNfse.IdentificadorNota, usuarioId);
                    }
                    else
                    {
                        // Cadastro do Reenvio
                        Nfe = CadastrarNfe(grvId, Empresa.Cnpj, CapaAutorizacaoNfse.IdentificadorNota, usuarioId, Nfe.NfeId);
                    }
                }
                catch (Exception ex)
                {
                    new NfeWsErroController().CadastrarErroGenerico(grvId, usuarioId, identificadorNota, OrigemErro.MobLink, acao, ex.Message);

                    returnList.Add("Erro ao cadastrar a NF: " + ex.Message);

                    continue;
                }

                Nfe.Cliente = Cliente.Nome;

                Nfe.Deposito = Deposito.Descricao;

                #endregion Cadastro do Envio/Reenvio


                #region Cadastro da Composição da Nota Fiscal

                NfeFaturamentoComposicaoList = new List <NfeFaturamentoComposicaoEntity>();

                try
                {
                    new NfeFaturamentoComposicaoController().Cadastrar(Nfe.NfeId, Composicoes.Where(w => w.Servico == agrupamento.Servico).ToList());
                }
                catch (Exception ex)
                {
                    new NfeWsErroController().CadastrarErroGenerico(grvId, usuarioId, identificadorNota, OrigemErro.MobLink, acao, ex.Message);

                    returnList.Add("Erro ao cadastrar a composição da NF: " + ex.Message);

                    continue;
                }
                #endregion Cadastro da Composição da Nota Fiscal


                #region Execução do Web Service
                try
                {
                    json = new NfeSolicitarEmissaoNotaFiscalController().SolicitarEmissaoNotaFiscal(CapaAutorizacaoNfse);
                }
                catch (Exception ex)
                {
                    new NfeWsErroController().CadastrarErroGenerico(grvId, usuarioId, identificadorNota, OrigemErro.MobLink, acao, ex.Message);

                    returnList.Add("Erro na Execução do Web Service: " + ex.Message);

                    continue;
                }

                returnList.Add(json);
                #endregion Execução do Web Service


                #region Processamento do resultado
                try
                {
                    if (!ProcessarResultado(json, usuarioId, Nfe))
                    {
                        continue;
                    }
                }
                catch (Exception ex)
                {
                    new NfeWsErroController().CadastrarErroGenerico(grvId, usuarioId, identificadorNota, OrigemErro.MobLink, acao, ex.Message);

                    returnList.Add("Erro no processamento do resultado do Web Service: " + ex.Message);

                    continue;
                }
                finally
                {
                    Nfe = new NfeEntity();
                }
                #endregion Processamento do resultado

                Nfe = new NfeEntity();
            }

            return(returnList);
        }
        private byte[] BaixarImagem(int clienteId, int depositoId, string identificadorNota, Consulta identificaoNotaFiscal, string url)
        {
            byte[] imagemNotaFiscal;

            NfeConfiguracaoImagemEntity ConfiguracaoImagem;

            NfeConfiguracaoImagemController NfeConfiguracaoImagemController = new NfeConfiguracaoImagemController();

            if ((ConfiguracaoImagem = NfeConfiguracaoImagemController.Selecionar(new NfeConfiguracaoImagemEntity {
                ClienteId = clienteId, DepositoId = depositoId
            })) == null)
            {
                ConfiguracaoImagem = new NfeConfiguracaoImagemEntity
                {
                    ClienteDepositoId = new ClienteDepositoController().Selecionar(new ClienteDepositoEntity {
                        ClienteId = clienteId, DepositoId = depositoId
                    }).ClienteDepositoId,

                    ValueX = 10,

                    ValueY = 10,

                    Height = 500,

                    Width = 500
                };

                ConfiguracaoImagem.ConfiguracaoImagemId = NfeConfiguracaoImagemController.Cadastrar(ConfiguracaoImagem);
            }

            string directory;

            string drive = new Tools().DriveToSave();

            directory = $@"{drive}Sistemas\GeradorNF\NFE\" + DataBase.SystemEnvironment.ToString() + "\\" + DateTime.Now.Year + "\\" + DateTime.Now.ToString("MM") + "\\" + DateTime.Now.ToString("dd") + "\\";

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            List <NfeRegraEntity> regrasNfe = new NfeRegraController().Listar(new NfeRegraEntity()
            {
                ClienteId  = clienteId,
                DepositoId = depositoId
            });

            if (regrasNfe?.Count(w => w.RegraCodigo.Equals("NFPDF") && w.Ativo.Equals(1)) > 0 || url.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase))
            {
                using (WebClient webClient = new WebClient())
                {
                    string str1 = directory + identificadorNota + "Original.pdf";
                    string str2 = directory + identificadorNota + ".jpg";

                    webClient.Headers.Add("user-agent", "Mob-Link");

                    webClient.DownloadFile(url, str1);

                    new PdfToJpg().Process(str1, str2);

                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        Image.FromFile(str2).Save(memoryStream, ImageFormat.Jpeg);

                        imagemNotaFiscal = memoryStream.ToArray();
                    }
                }
            }
            else
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    new Tools().ObterImagemEndereco(url).Save(memoryStream, ImageFormat.Jpeg);

                    imagemNotaFiscal = memoryStream.ToArray();
                }

                try
                {
                    if (!IsImage(imagemNotaFiscal))
                    {
                        throw new Exception("A Imagem retornada nao é uma Imagem válida");
                    }
                }
                catch (Exception)
                {
                    throw new Exception("Ocorreu um erro ao analisar a Imagem retornada");
                }

                #region Início do trecho para testes
                //if (new[] { "BETODELL", "BETOLENOVO", "SUPREMELEADER" }.Contains(SystemInformation.ComputerName))
                //{
                //    configuracaoImagem.ValueX = 0; // Margem Esquerda
                //    configuracaoImagem.ValueY = 0; // Margem Superior
                //    configuracaoImagem.Width = 1035; // Margem Direita
                //    configuracaoImagem.Height = 1315; // Margem Inferior
                //}
                #endregion Fim do trecho para testes

                try
                {
                    if (!identificaoNotaFiscal.BaixarImagemOriginal)
                    {
                        imagemNotaFiscal = CropImage(imagemNotaFiscal, new Rectangle(ConfiguracaoImagem.ValueX, ConfiguracaoImagem.ValueY, ConfiguracaoImagem.Width, ConfiguracaoImagem.Height));

                        // File.WriteAllBytes(directory + identificadorNota + "Recortado.jpg", ImagemNotaFiscal);

                        if (!IsImage(imagemNotaFiscal))
                        {
                            throw new Exception("A Imagem recortada nao é uma Imagem válida");
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Ocorreu um erro ao recortar a Imagem retornada: " + ex.Message);
                }
            }

            return(imagemNotaFiscal);
        }