Ejemplo n.º 1
0
        public static bool Excluir(string identificadorNota)
        {
            List <NfeEntity> nfes = new NfeController().ListarPorIdentificadorNota(identificadorNota);

            if (nfes == null)
            {
                return(false);
            }

            var nfe = nfes.First();

            DataBase.Execute("DELETE FROM tb_dep_nfe_faturamento_composicao WHERE NfeID = " + nfe.NfeId);

            DataBase.Execute("DELETE FROM tb_dep_nfe_imagens WHERE NfeID = " + nfe.NfeId);

            DataBase.Execute("DELETE FROM tb_dep_nfe_mensagens WHERE NfeID = " + nfe.NfeId);

            DataBase.Execute("DELETE FROM tb_dep_nfe_nota_fiscal WHERE NfeID = " + nfe.NfeId);

            DataBase.Execute("DELETE FROM tb_dep_nfe_retorno_solicitacao WHERE NfeID = " + nfe.NfeId);

            DataBase.Execute($"DELETE FROM tb_dep_nfe_ws_erros WHERE GrvId = {nfe.GrvId} AND IdentificadorNota = '{nfe.IdentificadorNota}'");

            DataBase.Execute("DELETE FROM tb_dep_nfe WHERE NfeID = " + nfe.NfeId);

            return(true);
        }
        public RetornoNotaFiscalEntity ReceberNotaFiscalAvulso(Consulta model)
        {
            DataBase.SystemEnvironment = model.Homologacao ? SystemEnvironment.Development : SystemEnvironment.Production;

            NfeEntity nfe = new NfeController().ConsultarNotaFiscal(model.IdentificadorNota);

            model.NfeId = nfe.NfeId;

            #region Empresa
            EmpresaEntity Empresa;

            if ((Empresa = new EmpresaController().Selecionar(new EmpresaEntity {
                Cnpj = model.Cnpj
            })) == null)
            {
                throw new Exception("Empresa associada não encontrada");
            }

            if (Empresa.Token == null)
            {
                throw new Exception("O Token não foi configurado");
            }
            #endregion Empresa

            string json;

Outer:

            try
            {
                json = new Tools().GetNfse(new NfeConfiguracao().GetRemoteServer() + "/" + model.IdentificadorNota, Empresa.Token);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("por minuto"))
                {
                    goto Outer;
                }

                AtualizarNotaFiscal(nfe);

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

            try
            {
                return(ProcessarRetornoAvulso(nfe, model, json));
            }
            catch (Exception ex)
            {
                AtualizarNotaFiscal(nfe);

                throw new Exception("Ocorreu um erro ao cadastrar a Nota Fiscal (" + model.IdentificadorNota + "): " + ex.Message);
            }
        }
Ejemplo n.º 3
0
        public string CancelarNotaFiscalAvulso(Cancelamento model)
        {
            DataBase.SystemEnvironment = model.Homologacao ? SystemEnvironment.Development : SystemEnvironment.Production;

            var nfe = new NfeController().ConsultarNotaFiscal(model.IdentificadorNota);

            if (nfe == null)
            {
                new NfeWsErroController().CadastrarErroGenerico(model.GrvId, model.UsuarioId, model.IdentificadorNota, OrigemErro.MobLink, Acao.Retorno, "Nota Fiscal não encontrada");

                throw new Exception("Nota Fiscal não encontrada");
            }

            #region Empresa
            EmpresaEntity Empresa;

            if ((Empresa = new EmpresaController().Selecionar(new EmpresaEntity {
                Cnpj = model.Cnpj
            })) == null)
            {
                throw new Exception("Empresa associada não encontrada");
            }
            #endregion Empresa

            var tools = new Tools();

            string jsonEnvio = tools.ObjToJSON(new Dictionary <string, string>()
            {
                {
                    "justificativa",
                    model.Justificativa
                }
            });

            string jsonRetorno;

            try
            {
                jsonRetorno = tools.CancelarNfse(new NfeConfiguracao().GetRemoteServer() + "/" + model.IdentificadorNota, jsonEnvio, Empresa.Token);
            }
            catch (Exception ex)
            {
                throw new Exception("Ocorreu um erro ao cancelar a Nota Fiscal (" + model.IdentificadorNota + "): " + ex.Message);
            }

            nfe.Status = 'N';

            new NfeController().Atualizar(nfe);

            return(jsonRetorno);
        }
Ejemplo n.º 4
0
        public NfeEntity ConsultarNotaFiscal(string identificadorNota)
        {
            List <NfeEntity> nfe;

            try
            {
                if ((nfe = new NfeController().ListarPorIdentificadorNota(identificadorNota)) == null)
                {
                    throw new Exception("Nota Fiscal não encontrada no cadastro do Depósito Público (" + identificadorNota + ")");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Ocorreu um erro ao consultar a Nota Fiscal (" + identificadorNota + "): " + ex.Message);
            }

            return(nfe.FirstOrDefault());
        }
Ejemplo n.º 5
0
        public NfeEntity ConsultarNotaFiscal(int grvId, int usuarioId, string identificadorNota, Acao acao)
        {
            List <NfeEntity> nfe;

            try
            {
                if ((nfe = new NfeController().ListarPorIdentificadorNota(identificadorNota)) == null)
                {
                    new NfeWsErroController().CadastrarErroGenerico(grvId, usuarioId, identificadorNota, OrigemErro.MobLink, acao, "Nota Fiscal não encontrada no cadastro do Depósito Público");

                    throw new Exception("Nota Fiscal não encontrada no cadastro do Depósito Público (" + identificadorNota + ")");
                }
            }
            catch (Exception ex)
            {
                new NfeWsErroController().CadastrarErroGenerico(grvId, usuarioId, identificadorNota, OrigemErro.MobLink, acao, "Ocorreu um erro ao consultar a Nota Fiscal: " + ex.Message);

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

            return(nfe.FirstOrDefault());
        }
Ejemplo n.º 6
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 RetornoNotaFiscalEntity ReceberNotaFiscal(Consulta identificaoNotaFiscal)
        {
            DataBase.SystemEnvironment = identificaoNotaFiscal.Homologacao ? SystemEnvironment.Development : SystemEnvironment.Production;

            NfeEntity nfe = new NfeController().ConsultarNotaFiscal(identificaoNotaFiscal.GrvId, identificaoNotaFiscal.UsuarioId, identificaoNotaFiscal.IdentificadorNota, Acao.Retorno);

            identificaoNotaFiscal.NfeId = nfe.NfeId;

            GrvEntity grv = new GrvController().Selecionar(identificaoNotaFiscal.GrvId);

            ClienteDepositoEntity 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(identificaoNotaFiscal.GrvId, identificaoNotaFiscal.UsuarioId, null, OrigemErro.MobLink, Acao.Retorno, "Empresa associada não encontrada");

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

            if (Empresa.Token == null)
            {
                new NfeWsErroController().CadastrarErroGenerico(identificaoNotaFiscal.GrvId, identificaoNotaFiscal.UsuarioId, null, OrigemErro.MobLink, Acao.Retorno, "O Token não foi configurado");

                throw new Exception("O Token não foi configurado");
            }
            #endregion Empresa

            string json;

Outer:

            try
            {
                json = new Tools().GetNfse(new NfeConfiguracao().GetRemoteServer() + "/" + identificaoNotaFiscal.IdentificadorNota, Empresa.Token);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("por minuto"))
                {
                    goto Outer;
                }

                AtualizarNotaFiscal(nfe);

                new NfeWsErroController().CadastrarErroGenerico(nfe.GrvId, identificaoNotaFiscal.UsuarioId, nfe.IdentificadorNota, OrigemErro.WebService, Acao.Retorno, "Ocorreu um erro ao receber a Nota Fiscal: " + ex.Message);

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

            try
            {
                return(ProcessarRetorno(grv, nfe, identificaoNotaFiscal, json));
            }
            catch (Exception ex)
            {
                AtualizarNotaFiscal(nfe);

                new NfeWsErroController().CadastrarErroGenerico(nfe.GrvId, identificaoNotaFiscal.UsuarioId, nfe.IdentificadorNota, OrigemErro.MobLink, Acao.Retorno, "Ocorreu um erro ao cadastrar a Nota Fiscal: " + ex.Message);

                throw new Exception("Ocorreu um erro ao cadastrar a Nota Fiscal (" + identificaoNotaFiscal.IdentificadorNota + "): " + ex.Message);
            }
        }
Ejemplo n.º 8
0
        public string CancelarNotaFiscal(Cancelamento model)
        {
            DataBase.SystemEnvironment = model.Homologacao ? SystemEnvironment.Development : SystemEnvironment.Production;

            var nfe = new NfeController().ConsultarNotaFiscal(model.GrvId, model.UsuarioId, model.IdentificadorNota, Acao.Cancelamento);

            if (nfe == null)
            {
                new NfeWsErroController().CadastrarErroGenerico(model.GrvId, model.UsuarioId, model.IdentificadorNota, OrigemErro.MobLink, Acao.Retorno, "Nota Fiscal não encontrada");

                return($"Nota Fiscal {model.GrvId}/{model.IdentificadorNota} não encontrada");
            }

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

            #region Empresa
            EmpresaEntity Empresa;

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

                return("Empresa associada não encontrada");
            }
            else if (Empresa.Token == null)
            {
                new NfeWsErroController().CadastrarErroGenerico(model.GrvId, model.UsuarioId, model.IdentificadorNota, OrigemErro.MobLink, Acao.Retorno, $"Empresa {Empresa.Nome} sem Token cadastrado");

                return($"Empresa {Empresa.Nome} sem Token cadastrado");
            }
            #endregion Empresa

            var tools = new Tools();

            string jsonEnvio = tools.ObjToJSON(new Dictionary <string, string>()
            {
                {
                    "justificativa",
                    model.Justificativa
                }
            });

            string jsonRetorno;

            try
            {
                jsonRetorno = tools.CancelarNfse(new NfeConfiguracao().GetRemoteServer() + "/" + model.IdentificadorNota, jsonEnvio, Empresa.Token);
            }
            catch (Exception ex)
            {
                new NfeWsErroController().CadastrarErroGenerico(nfe.GrvId, model.UsuarioId, nfe.IdentificadorNota, OrigemErro.WebService, Acao.Cancelamento, "Ocorreu um erro ao cancelar a Nota Fiscal: " + ex.Message);

                return($"Ocorreu um erro ao cancelar a Nota Fiscal ({model.GrvId}/{model.IdentificadorNota}): {ex.Message}");
            }

            try
            {
                var retornoConsulta = new JavaScriptSerializer()
                {
                    MaxJsonLength = int.MaxValue
                }.Deserialize <RetornoCancelamentoEntity>(jsonRetorno);

                if (retornoConsulta.erros != null)
                {
                    var retornoErro = new NfeWsErroModel();

                    foreach (var erro in retornoConsulta.erros)
                    {
                        retornoErro.GrvId             = model.GrvId;
                        retornoErro.IdentificadorNota = model.IdentificadorNota;
                        retornoErro.UsuarioId         = model.UsuarioId;
                        retornoErro.Acao       = (char)Acao.Retorno;
                        retornoErro.OrigemErro = (char)OrigemErro.WebService;
                        retornoErro.Status     = retornoConsulta.status.Trim().ToUpper();

                        if (erro.codigo != null)
                        {
                            retornoErro.CodigoErro = erro.codigo.Replace("  ", " ").Trim().ToUpper();
                        }

                        if (erro.mensagem != null)
                        {
                            retornoErro.MensagemErro = erro.mensagem.Replace("  ", " ").Trim();
                        }

                        if (erro.correcao != null)
                        {
                            retornoErro.CorrecaoErro = erro.correcao.Replace("  ", " ").Trim();
                        }

                        retornoErro.ErroId = new NfeWsErroController().Cadastrar(retornoErro);
                    }

                    return(jsonRetorno);
                }
            }
            catch (Exception ex)
            {
                if (true)
                {
                }
            }



            nfe.Status = 'N';

            new NfeController().Atualizar(nfe);

            return(jsonRetorno);
        }
        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);
        }