public string SolicitarEmissaoNotaFiscalAvulso(CapaAutorizacaoNfse model)
        {
            DataBase.SystemEnvironment = model.Homologacao ? SystemEnvironment.Development : SystemEnvironment.Production;

            NfePrestadorAvulsoEntity PrestadorAvulso;

            if ((PrestadorAvulso = NfePrestadorAvulsoPersistence.Selecionar(new NfePrestadorAvulsoEntity {
                Cnpj = model.Autorizacao.prestador.cnpj
            })) == null)
            {
                throw new Exception("Prestador não encontrado");
            }
            else if (PrestadorAvulso.Token == null)
            {
                throw new Exception("Prestador não possui Token configurado");
            }

            try
            {
                return(new Tools().PostNfse
                       (
                           uri: new NfeConfiguracao().GetRemoteServer() + "?ref=" + model.IdentificadorNota,
                           json: CreateJson(model),
                           token: PrestadorAvulso.Token
                       ));
            }
            catch (Exception ex)
            {
                throw new Exception("Ocorreu um erro ao solicitar a Nota Fiscal (" + model.IdentificadorNota + "): " + ex.Message);
            }
        }
Пример #2
0
 public string SolicitarEmissaoNotaFiscalAvulso(CapaAutorizacaoNfse model)
 {
     try
     {
         return(new NfeSolicitarEmissaoNotaFiscalController().SolicitarEmissaoNotaFiscalAvulso(model));
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
Пример #3
0
        public string SolicitarEmissaoNotaFiscal(CapaAutorizacaoNfse model)
        {
            try
            {
                return(new NfeSolicitarEmissaoNotaFiscalController().SolicitarEmissaoNotaFiscal(model));
            }
            catch (Exception ex)
            {
                new EmailController().Enviar(ex.Message, model.Homologacao);

                throw new Exception(ex.Message);
            }
        }
        private string CreateJson(CapaAutorizacaoNfse model)
        {
            var tools = new Tools();

            string json = tools.ObjToJSON(model.Autorizacao);

            var jsonUtil = new JsonUtil.JsonUtil();

            if (string.IsNullOrWhiteSpace(model.Autorizacao.tomador.cnpj))
            {
                json = jsonUtil.RemoveElement(json, "tomador", "cnpj");
            }
            else
            {
                json = jsonUtil.RemoveElement(json, "tomador", "cpf");
            }

            return(json);
        }
Пример #5
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);
        }
        public int Cadastrar(NfeEntity nfe, CapaAutorizacaoNfse capaAutorizacaoNfse, string resposta, string json)
        {
            var SQL = new StringBuilder();

            SQL.AppendLine("INSERT INTO dbo.tb_dep_nfe_retorno_solicitacao");

            SQL.AppendLine("      (NfeId");
            SQL.AppendLine("      ,NaturezaOperacao");
            SQL.AppendLine("      ,OptanteSimplesNacional");
            SQL.AppendLine("      ,TomadorCpfCnpj");
            SQL.AppendLine("      ,TomadorCnpj");
            SQL.AppendLine("      ,TomadorNomeRazaoSocial");
            SQL.AppendLine("      ,TomadorTelefone");
            SQL.AppendLine("      ,TomadorEmail");
            SQL.AppendLine("      ,TomadorEnderecoLogradouro");
            SQL.AppendLine("      ,TomadorEnderecoNumero");
            SQL.AppendLine("      ,TomadorEnderecoComplemento");
            SQL.AppendLine("      ,TomadorEnderecoBairro");
            SQL.AppendLine("      ,TomadorEnderecoCodigoMunicipio");
            SQL.AppendLine("      ,TomadorEnderecoUf");
            SQL.AppendLine("      ,TomadorEnderecoCep");
            SQL.AppendLine("      ,ServicoAliquota");
            SQL.AppendLine("      ,ServicoDiscriminacao");
            SQL.AppendLine("      ,ServicoIssRetido");
            SQL.AppendLine("      ,ServicoValorIss");
            SQL.AppendLine("      ,ServicoCodigoCnae");
            SQL.AppendLine("      ,ServicoItemListaServico");
            SQL.AppendLine("      ,ServicoValorServicos");
            SQL.AppendLine("      ,ServicoCodigoTributarioMunicipio");
            SQL.AppendLine("      ,RespostaEnvio");
            SQL.AppendLine("      ,Json");
            SQL.AppendLine("      ,DataEmissao)");

            SQL.AppendLine("VALUES");

            SQL.Append("      (").Append(nfe.NfeId).AppendLine();
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(capaAutorizacaoNfse.Autorizacao.natureza_operacao));
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(Convert.ToInt32(bool.Parse(capaAutorizacaoNfse.Autorizacao.optante_simples_nacional)).ToString()));
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(capaAutorizacaoNfse.Autorizacao.tomador.cpf));
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(capaAutorizacaoNfse.Autorizacao.tomador.cnpj));
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(capaAutorizacaoNfse.Autorizacao.tomador.razao_social));
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(capaAutorizacaoNfse.Autorizacao.tomador.telefone));
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(capaAutorizacaoNfse.Autorizacao.tomador.email));
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(capaAutorizacaoNfse.Autorizacao.tomador.endereco.logradouro));
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(capaAutorizacaoNfse.Autorizacao.tomador.endereco.numero));
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(capaAutorizacaoNfse.Autorizacao.tomador.endereco.complemento));
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(capaAutorizacaoNfse.Autorizacao.tomador.endereco.bairro));
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(capaAutorizacaoNfse.Autorizacao.tomador.endereco.codigo_municipio));
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(capaAutorizacaoNfse.Autorizacao.tomador.endereco.uf));
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(capaAutorizacaoNfse.Autorizacao.tomador.endereco.cep));
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(capaAutorizacaoNfse.Autorizacao.servico.aliquota));
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(capaAutorizacaoNfse.Autorizacao.servico.discriminacao));
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(Convert.ToInt32(Convert.ToBoolean(capaAutorizacaoNfse.Autorizacao.servico.iss_retido)).ToString()));
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(capaAutorizacaoNfse.Autorizacao.servico.valor_iss));
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(capaAutorizacaoNfse.Autorizacao.servico.codigo_cnae));
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(capaAutorizacaoNfse.Autorizacao.servico.item_lista_servico));
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(capaAutorizacaoNfse.Autorizacao.servico.valor_servicos));
            SQL.Append("      ,").AppendLine(DataBase.SetNullIfEmpty(capaAutorizacaoNfse.Autorizacao.servico.codigo_tributario_municipio));
            SQL.AppendLine("      ,@RespostaEnvio");
            SQL.AppendLine("      ,@Json");
            SQL.Append("      ,").Append(DataBase.SetNullIfEmpty(capaAutorizacaoNfse.Autorizacao.data_emissao)).AppendLine(")");

            var sqlParameters = new SqlParameter[2];

            sqlParameters[0] = new SqlParameter("@RespostaEnvio", SqlDbType.VarChar)
            {
                Value = resposta
            };

            sqlParameters[1] = new SqlParameter("@Json", SqlDbType.VarChar)
            {
                Value = json
            };

            return(DataBase.ExecuteScopeIdentity(SQL, sqlParameters));
        }
Пример #7
0
        private static void Processamentos(bool isDevelopment, int grvId, int identificadorNota = 0)
        {
            //DataBase.DisconnectDataBase();

            //if (DataBase.SystemEnvironment == SystemEnvironment.Development)
            //{
            //    DataBase.ConnectDataBase("Data Source=187.84.228.60;Initial Catalog=dbMobLinkDepositoPublicoDesenvolvimento;Persist Security Info=True;User ID=dp_user_dev;Password=5y3d#%&&!x");
            //}
            //else
            //{
            //    DataBase.ConnectDataBase("Data Source=187.84.228.60;Initial Catalog=dbMobLinkDepositoPublicoProducao;Persist Security Info=True;User ID=dp_user_prd;Password=4y3d#%&&!x");
            //}

            // DataBase.ConnectDataBase();

            // var grvs = new GrvController().Listar(new GrvEntity { StatusOperacaoId = 'E', ClienteId = 49 });

            // 943312
            // 877968

            var grvs = new GrvController().Listar(new GrvEntity {
                NumeroFormularioGrv = "900691870"
            });

            foreach (var grv in grvs)
            {
                try
                {
                    var nfe = new NfeGerarNotaFiscalController().GerarNotaFiscal
                              (
                        grvId: grv.GrvId,

                        usuarioId: 1,

                        isDev: isDevelopment
                              );

                    for (int i = 0; i < nfe.Count; i++)
                    {
                        Console.WriteLine("MENSAGEM: " + nfe[i]);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("ERRO: " + ex.Message);
                }
            }

            if (grvs != null)
            {
                grvId = grvs[0].GrvId;

                if (grvs.Count > 1)
                {
                    Debug.WriteLine($"FORAM ENCONTRADOS MAIS DE UM GRV");

                    Console.WriteLine($"FORAM ENCONTRADOS MAIS DE UM GRV");

                    Console.ReadLine();

                    Environment.Exit(-1);
                }
            }
            else
            {
                Debug.WriteLine($"NÚMERO DE GRV NÃO ENCONTRADO");

                Console.WriteLine($"NÚMERO DE GRV NÃO ENCONTRADO");

                Console.ReadLine();

                Environment.Exit(-1);
            }

            Debug.WriteLine($"GRV ID: {grvId}");

            Console.WriteLine($"GRV ID: {grvId}");

            // NfeExcluirController.Excluir(749458);

            grvId = 949073;

            #region Teste de Solicitação Simplificado
            try
            {
                var nfe = new NfeGerarNotaFiscalController().GerarNotaFiscal
                          (
                    grvId: grvId,

                    usuarioId: 1,

                    isDev: isDevelopment
                          );

                for (int i = 0; i < nfe.Count; i++)
                {
                    Console.WriteLine("MENSAGEM: " + nfe[i]);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERRO: " + ex.Message);
            }
            #endregion Teste de Solicitação Simplificado


            grvId = 949073;

            #region Teste de Solicitação de uma nova NF
            try
            {
                var novaNfe = new NfeGerarNotaFiscalController().GerarNovaNotaFiscal
                              (
                    grvId: grvId,

                    identificadorNota: "801814",

                    usuarioId: 1,

                    isDev: isDevelopment
                              );

                Console.WriteLine("MENSAGEM: " + novaNfe[0]);

                //novaNfe = new NfeGerarNotaFiscalController().GerarNovaNotaFiscal
                //(
                //    grvId: grvId,

                //    identificadorNota: 753803,

                //    usuarioId: 1,

                //    isDev: IsTestEnvironment
                //);

                //Console.WriteLine("MENSAGEM: " + novaNfe[0]);
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERRO: " + ex.Message);
            }
            #endregion Teste de Solicitação de uma nova NF


            #region Teste de retorno da Nota Fiscal (Download da NF)
            try
            {
                var aux = new NfeReceberNotaFiscalController().ReceberNotaFiscal(new Consulta
                {
                    GrvId = grvId,

                    IdentificadorNota = "762905",

                    Homologacao = isDevelopment,

                    UsuarioId = 1
                });

                Console.WriteLine("MENSAGEM: " + aux);

                if (true)
                {
                }

                //aux = new NfeReceberNotaFiscalController().ReceberNotaFiscal(new Consulta
                //{
                //    GrvId = grvId,

                //    IdentificadorNota = "751627",

                //    Homologacao = IsTestEnvironment,

                //    UsuarioId = 1
                //});

                //Console.WriteLine("MENSAGEM: " + aux);
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERRO: " + ex.Message);
            }
            #endregion Teste de retorno da Nota Fiscal (Download da NF)


            #region Teste de cancelamento da Nota Fiscal
            //try
            //{
            //    var aux = new NfeCancelamentoController().CancelarNotaFiscal(new Cancelamento
            //    {
            //        GrvId = grvId,

            //        IdentificadorNota = "",

            //        Justificativa = "TESTE",

            //        Homologacao = IsTestEnvironment,

            //        UsuarioId = 1
            //    });

            //    Console.WriteLine("MENSAGEM: " + aux);
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine("ERRO: " + ex.Message);
            //}
            #endregion Teste de cancelamento da Nota Fiscal
            // using NFSE.Domain.Entities.NFe;
            var capaAutorizacaoNfse = new CapaAutorizacaoNfse
            {
                IdentificadorNota = "",

                Autorizacao = new Autorizacao
                {
                    data_emissao             = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss"),
                    natureza_operacao        = "1",
                    optante_simples_nacional = "false",

                    prestador = new Prestador
                    {
                        cnpj                = "08397160003658",
                        codigo_municipio    = "5103403",
                        inscricao_municipal = "172692"
                    },

                    servico = new Servico
                    {
                        aliquota    = "5.00",
                        codigo_cnae = "5223100",
                        codigo_tributario_municipio = "",
                        discriminacao      = "ISS Tributado de acordo com a Lei Complementar Nº 460 de 22/10/2008 Processo Nº 9094604500 - Carga Tributária 18,45% fonte IBPT Serviços de Transporte/Remoção de Veículos",
                        item_lista_servico = "1101",
                        iss_retido         = "false",
                        valor_iss          = "0.05",
                        valor_servicos     = "1.0"
                    },

                    tomador = new Tomador()
                    {
                        cpf          = "07172853750",
                        email        = "*****@*****.**",
                        razao_social = "CRISTINEY SOARES",
                        telefone     = "2199999999",

                        endereco = new Endereco
                        {
                            bairro      = "Maria Paula",
                            cep         = "24756660",
                            complemento = "Bloco 12 Apto 403",
                            logradouro  = "estrada da paciencia",
                            numero      = "2939",
                            uf          = "RJ"
                        }
                    }
                }
            };

            try
            {
                var nfe = new NfeSolicitarEmissaoNotaFiscalController().SolicitarEmissaoNotaFiscalAvulso(capaAutorizacaoNfse);

                // Console.WriteLine(result + Environment.NewLine);
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERRO: " + ex.Message);
            }
        }
        public string SolicitarEmissaoNotaFiscal(CapaAutorizacaoNfse model)
        {
            DataBase.SystemEnvironment = model.Homologacao ? SystemEnvironment.Development : SystemEnvironment.Production;

            var nfe = new NfeController().ConsultarNotaFiscal(model.GrvId, model.UsuarioId, model.IdentificadorNota, Acao.Solicitação);

            var grv = new GrvController().Selecionar(model.GrvId);

            var ClienteDeposito = new ClienteDepositoController().Selecionar(new ClienteDepositoEntity {
                ClienteId = grv.ClienteId, DepositoId = grv.DepositoId
            });

            #region Empresa
            EmpresaEntity Empresa;

            if ((Empresa = new EmpresaController().Selecionar(new EmpresaEntity {
                EmpresaId = ClienteDeposito.EmpresaId
            })) == null)
            {
                new NfeWsErroController().CadastrarErroGenerico(model.GrvId, model.UsuarioId, null, OrigemErro.MobLink, Acao.Retorno, "Empresa associada não encontrada");

                throw new Exception("Empresa associada não encontrada");
            }
            #endregion Empresa

            string resposta;

            string json;

            try
            {
                json = CreateJson(model);
            }
            catch (Exception ex)
            {
                nfe.Status = 'E';

                new NfeController().Atualizar(nfe);

                new NfeWsErroController().CadastrarErroGenerico(model.GrvId, model.UsuarioId, nfe.IdentificadorNota, OrigemErro.WebService, Acao.Solicitação, "Ocorreu um erro ao criar o JSON da Nota Fiscal: " + ex.Message);

                throw new Exception("Ocorreu um erro ao criar o JSON da Nota Fiscal (" + model.IdentificadorNota + "): " + ex.Message);
            }

            try
            {
                resposta = new Tools().PostNfse
                           (
                    uri: new NfeConfiguracao().GetRemoteServer() + "?ref=" + model.IdentificadorNota,
                    json: json,
                    token: Empresa.Token
                           );
            }
            catch (Exception ex)
            {
                nfe.Status = 'E';

                new NfeController().Atualizar(nfe);

                new NfeWsErroController().CadastrarErroGenerico(model.GrvId, model.UsuarioId, nfe.IdentificadorNota, OrigemErro.WebService, Acao.Solicitação, "Ocorreu um erro ao solicitar a Nota Fiscal: " + ex.Message);

                throw new Exception("Ocorreu um erro ao solicitar a Nota Fiscal (" + model.IdentificadorNota + "): " + ex.Message);
            }

            try
            {
                new NfeRetornoSolicitacaoController().Cadastrar(nfe, model, resposta, json);
            }
            catch (Exception ex)
            {
                nfe.Status = 'E';

                new NfeController().Atualizar(nfe);

                new NfeWsErroController().CadastrarErroGenerico(model.GrvId, model.UsuarioId, nfe.IdentificadorNota, OrigemErro.MobLink, Acao.Solicitação, "Ocorreu um erro ao cadastrar a solicitação da Nota Fiscal: " + ex.Message);

                throw new Exception("Ocorreu um erro ao cadastrar a solicitação da Nota Fiscal (" + model.IdentificadorNota + "): " + ex.Message);
            }

            return(resposta);
        }