//[WebMethod]
        //[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true, XmlSerializeString = true)]
        public static Retorno GetTarefas()
        {
            //acesso o banco usando o linq e retorna uma lista de eventos do dia conforme o parametro data.
            //dbAgendaDataContext db = new dbAgendaDataContext();
            //List<Evento> listEvento = db.Eventos.Where(e => e.dataEvento == Convert.ToDateTime(data)).OrderBy(e => e.dataEvento).ToList();

            var array = new ArrayList
                            {
                                new ArrayList {"1", "Firefox", "1.0", "true", "true", "true", "A"},
                                new ArrayList {"2", "Opera", "2.0", "false", "false", "true", "B"},
                                new ArrayList {"3", "Explorer", "3.0", "true", "true", "false", "A"},
                            };

            //var d = new Retorno
            //                 {
            //                     aaData = new ArrayList
            //                                {
            //                                    new Evento {Id = 1, Nome = "Tadeu", Sobrenome = "Alves", Status = "Ativo"},
            //                                    new Evento {Id = 2, Nome = "Carlos", Sobrenome = "Pereira", Status = "Ativo"},
            //                                    new Evento {Id = 3, Nome = "Maria", Sobrenome = "Pedrso", Status = "Ativo"},
            //                                    new Evento { Id = 4, Nome = "Filomena", Sobrenome = "Siqueira", Status = "Inativo" },
            //                                    new Evento{Id = 5, Nome = "Joao", Sobrenome = "Silva", Status = "Inativo"},
            //                                    new Evento{Id = 6, Nome = "Ricardo", Sobrenome = "Souza", Status = "Ativo"},
            //                                    new Evento{Id = 7, Nome = "Mariana", Sobrenome = "Pires", Status = "Inativo"},
            //                                    new Evento{Id = 8, Nome = "Sahra", Sobrenome = "Pinto", Status = "Ativo"}
            //                                }
            //                 };
            //var serializer = new JavaScriptSerializer();
            var result = new Retorno { aaData = array.ToArray() };
            return result;
        }
        public Retorno<string> Validade()
        {
            var retorno = new Retorno<string>() { Result = eResult.Invalido };

            var timespanZero = new TimeSpan(0,0,0);
            var timespanMax = new TimeSpan(24,0,0);


            if (this.horaBEC.Inicio > timespanMax)
            {
                retorno.Entidade = "Hora de INÍCIO inválida";
            }
            else if (this.horaBEC.Fim.Equals(timespanZero))
            {
                retorno.Entidade = "Hora de FIM inválida";
            }
            else if (this.horaBEC.Traslado > timespanMax)
            {
                retorno.Entidade = "Hora de Traslado inválida";
            }
            else if (this.horaBEC.Desconto > timespanMax)
            {
                retorno.Entidade = "Hora de DESCONTO inválida";
            }
            else if (this.horaBEC.Inicio >= this.horaBEC.Fim)
            {
                retorno.Entidade = "Período de INÍCIO e FIM inválido";
            }
            else if (total > new TimeSpan(23, 59, 59))
            {
                retorno.Entidade = "Total de horas excedeu 23h59. Por favor, crie outra OS com as horas excedentes.";
            }
            else if (this.horaBEC.Desconto >= this.utilizada)
            {
                retorno.Entidade = "Hora de DESCONTO inválida";
            }
            else
            {
                retorno.Result = eResult.Valido;
            }

            return retorno;
        }
Esempio n. 3
0
        public Retorno<PostBEC> Get(PostFilterBEC filterBEC)
        {
            var retorno = new Retorno<PostBEC> { Result = eResult.Inexistente };

            try
            {
                using (var context = new ContextDB())
                {
                    var post = (from p in context.PostSet
                                where p.id.Equals(filterBEC.id)
                                select new PostBEC
                                {
                                    id = p.id,
                                    Titulo = p.Titulo,
                                    Texto = p.Texto,
                                    Data = p.DataInclusao,
                                    URL = p.URL,
                                    Capa = p.Capa,
                                    TagSet = p.TagSet.Select(s => new PostTagBEC { Nome = s.Tag, URL = s.URL }).ToList(),
                                    Categoria = new PostCategoriaBEC { Nome = p.Categoria.Nome, URL = p.Categoria.URL },
                                    ImagemSet = p.ImagemSet.Select(s => new PostImagemBEC { id = s.id, Extensao = s.Extensao, Legenda = s.Legenda }).ToList(),

                                })
                            .FirstOrDefault();

                    if (post is PostBEC)
                    {
                        retorno.Entidade = post;
                        retorno.Result = eResult.Existente;
                    }

                }
            }
            catch (Exception _ex)
            {
                LogBEC logBEC = new LogBEC { Exception = _ex };
                LogBC.Instance.Log(logBEC);
            }

            return retorno;
        }
        public async Task <OkObjectResult> GetSingle(int id)
        {
            var resultado = new Retorno <UsuarioDto>();

            try
            {
                Usuario usuario = await _usuarioService.ObterPorIdAsync(id);

                resultado.Objeto = new UsuarioDto(usuario);
            }
            catch (Exception)
            {
                resultado.Mensagens.Add(new MensagemSistemaDto()
                {
                    Titulo = "Consulta", Mensagem = string.Format(" Já existe um usuário cadastrado com esse login: {0}", id)
                });
                resultado.Status = ResultadoOperacao.Falha;
                return(Ok(resultado));
            }

            resultado.Status = ResultadoOperacao.Sucesso;

            return(Ok(resultado));
        }
Esempio n. 5
0
        //Camada de anticorrupção
        private List <Temperatura> ToListViewModel(Retorno retorno)
        {
            if (retorno.Success)
            {
                var temperaturas = new List <Temperatura>(retorno.Lista.Count);

                retorno.Lista.ForEach(c =>
                {
                    temperaturas.Add(new Temperatura()
                    {
                        Date         = c.Date,
                        TemperaturaC = c.TemperatureC,
                        TemperaturaF = c.TemperatureF,
                        Sumarry      = c.Summary
                    });
                });

                return(temperaturas);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 6
0
        public Retorno CadastrarUsuario(Usuario usuario)
        {
            Retorno ret = new Retorno();

            try
            {
                Usuario user = new Usuario();
                user = usuario;
                db.Usuario.AddObject(user);
                db.SaveChanges();

                ret.mensagem = "Usuário cadastrado com sucesso!";
                ret.success  = true;
            }
            catch (Exception)
            {
                ret.mensagem = "Ocorreu um erro ao adicionar usuario!";
                ret.success  = false;
            }



            return(ret);
        }
Esempio n. 7
0
        public async Task <ActionResult <Retorno> > GetAsync(int id, string url, string arquivo)
        {
            var novaUrl = System.Net.WebUtility.UrlDecode(url);
            await Db.Connection.OpenAsync();

            var query  = new ClientesQuery(Db);
            var result = await query.FindOneAsync(id);

            if (result is null)
            {
                return(new NotFoundResult());
            }

            var    pasta         = result.Pasta;
            var    caminhoFisico = result.caminhoFisico;
            string pdfgerado     = GeraPDF.RetornaPDF(novaUrl, arquivo, pasta, caminhoFisico, "");

            if (pdfgerado == "pdfGerado" || pdfgerado == "pdfExistente")
            {
                bool pdfNovo = false;
                if (pdfgerado == "pdfGerado")
                {
                    pdfNovo = true;
                }
                var urlDestino = result.Url + "/" + pasta + "/" + arquivo;
                var retorno    = new Retorno();
                retorno.URL           = urlDestino;
                retorno.caminhoFisico = caminhoFisico;
                retorno.Novo          = pdfNovo;
                return(retorno);
            }
            else
            {
                return(new OkObjectResult("Erro"));
            }
        }
        Retorno IPedidoServico.RemoverPedido(int idPedido)
        {
            Retorno retorno;

            if (idPedido <= 0)
            {
                retorno = new Retorno(false);
                retorno.AdicionarMensagemFalha("Nao foi possivel localizar o pedido para remover");
                return(retorno);
            }

            bool removeuCliente;

            try
            {
                Pedido pedido = _pedidoRepositorio.ObterProdutoPorId(idPedido);

                if (pedido == null)
                {
                    retorno = new Retorno(false);
                    retorno.AdicionarMensagemFalha("Nao foi possivel localizar o pedido para remover");
                    return(retorno);
                }

                removeuCliente = _pedidoRepositorio.Remover(pedido);
                retorno        = new Retorno(true);
                retorno.AdicionarMensagemFalha("pedido removido com sucesso");
                return(retorno);
            }
            catch (Exception ex)
            {
                retorno = new Retorno(false);
                retorno.AdicionarMensagemFalha("Não foi possível remover o pedido");
                return(retorno);
            }
        }
Esempio n. 9
0
        public Retorno Salvar(ContaPagar contaPagar)
        {
            try
            {
                var retorno = new Retorno(true);

                foreach (var parcela in contaPagar.Parcelas)
                {
                    parcela.ContaPagar = contaPagar;
                    retorno            = Salvar(parcela);

                    if (!retorno.IsValido)
                    {
                        break;
                    }
                }

                return(retorno);
            }
            catch (Exception ex)
            {
                return(Retorno.CriarRetornoExcecao(ex));
            }
        }
Esempio n. 10
0
        public async Task <ICommandResult> Persistir(DiretorDTO command, ELogin acoes)
        {
            var retorno = new Retorno();

            switch (acoes)
            {
            case ELogin.CADASTRAR:
                retorno = await Cadastrar(command);

                break;

            case ELogin.ATUALIZAR:
                retorno = await Atualizar(command);

                break;

            case ELogin.EXCLUIR:
                retorno = await Excluir(command);

                break;
            }

            return(retorno);
        }
Esempio n. 11
0
        private void btnInserirVertice_Click(object sender, RoutedEventArgs e)
        {
            thriftGrafo.Vertice v1 = new thriftGrafo.Vertice();

            v1.Nome      = Convert.ToInt32(txtNomeVertice.Text);
            v1.Cor       = Convert.ToInt32(txtCorVertice.Text);
            v1.Descricao = txtDescricaoVertice.Text;
            v1.Peso      = Convert.ToDouble(txtPesoVertice.Text);

            Retorno r = client.insertVertice(v1);

            if (r.Sucesso)
            {
                txtNomeVertice.Text      = "";
                txtCorVertice.Text       = "";
                txtDescricaoVertice.Text = "";
                txtPesoVertice.Text      = "";
                MessageBox.Show(r.Mensagem);
            }
            else
            {
                MessageBox.Show(r.Mensagem);
            }
        }
Esempio n. 12
0
        // GET /webpages_Membership/token/colecao/campo/orderBy/pageSize/pageNumber?CAMPO1=VALOR&CAMPO2=VALOR
        public HttpResponseMessage Get(string token, int colecao = 0, int campo = 0, int orderBy = 0, int pageSize = 0, int pageNumber = 0)
        {
            // Abre nova conexão
            using (painel_taxservices_dbContext _db = new painel_taxservices_dbContext())
            {
                tbLogAcessoUsuario log = new tbLogAcessoUsuario();
                try
                {
                    Dictionary <string, string> queryString = Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value);
                    HttpResponseMessage         retorno     = new HttpResponseMessage();

                    log = Bibliotecas.LogAcaoUsuario.New(token, null, "Get", _db);

                    if (Permissoes.Autenticado(token, _db))
                    {
                        Retorno dados = GatewayWebpagesMembership.Get(token, colecao, campo, orderBy, pageSize, pageNumber, queryString, _db);
                        log.codResposta = (int)HttpStatusCode.OK;
                        Bibliotecas.LogAcaoUsuario.Save(log, _db);
                        return(Request.CreateResponse <Retorno>(HttpStatusCode.OK, dados));
                    }
                    else
                    {
                        log.codResposta = (int)HttpStatusCode.Unauthorized;
                        Bibliotecas.LogAcaoUsuario.Save(log, _db);
                        return(Request.CreateResponse(HttpStatusCode.Unauthorized));
                    }
                }
                catch (Exception e)
                {
                    log.codResposta = (int)HttpStatusCode.InternalServerError;
                    log.msgErro     = e.Message;
                    Bibliotecas.LogAcaoUsuario.Save(log);
                    throw new HttpResponseException(HttpStatusCode.InternalServerError);
                }
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Retorna TbAdquirente/TbAdquirente
        /// </summary>
        /// <returns></returns>
        public static Retorno Get(string token, int colecao = 0, int campo = 0, int orderBy = 0, int pageSize = 0, int pageNumber = 0, Dictionary <string, string> queryString = null, painel_taxservices_dbContext _dbContext = null)
        {
            painel_taxservices_dbContext _db;

            if (_dbContext == null)
            {
                _db = new painel_taxservices_dbContext();
            }
            else
            {
                _db = _dbContext;
            }

            try
            {
                //DECLARAÇÕES
                List <dynamic> CollectionTbAdquirente = new List <dynamic>();
                Retorno        retorno = new Retorno();

                string outValue = null;
                Int32  IdGrupo  = Permissoes.GetIdGrupo(token, _db);
                if (IdGrupo != 0)
                {
                    if (queryString.TryGetValue("" + (int)CAMPOS.ID_GRUPO, out outValue))
                    {
                        queryString["" + (int)CAMPOS.ID_GRUPO] = IdGrupo.ToString();
                    }
                    else
                    {
                        queryString.Add("" + (int)CAMPOS.ID_GRUPO, IdGrupo.ToString());
                    }
                }
                string CnpjEmpresa = Permissoes.GetCNPJEmpresa(token, _db);
                if (!CnpjEmpresa.Equals(""))
                {
                    if (queryString.TryGetValue("" + (int)CAMPOS.CNPJ, out outValue))
                    {
                        queryString["" + (int)CAMPOS.CNPJ] = CnpjEmpresa;
                    }
                    else
                    {
                        queryString.Add("" + (int)CAMPOS.CNPJ, CnpjEmpresa);
                    }
                }

                // GET QUERY
                var query = getQuery(_db, colecao, campo, orderBy, pageSize, pageNumber, queryString);


                // TOTAL DE REGISTROS
                retorno.TotalDeRegistros = query.Count();


                // PAGINAÇÃO
                int skipRows = (pageNumber - 1) * pageSize;
                if (retorno.TotalDeRegistros > pageSize && pageNumber > 0 && pageSize > 0)
                {
                    query = query.Skip(skipRows).Take(pageSize);
                }
                else
                {
                    pageNumber = 1;
                }

                retorno.PaginaAtual    = pageNumber;
                retorno.ItensPorPagina = pageSize;

                // COLEÇÃO DE RETORNO
                if (colecao == 1)
                {
                    CollectionTbAdquirente = query.Select(e => new
                    {
                        cdAdquirente = e.cdAdquirente,
                        nmAdquirente = e.nmAdquirente,
                        dsAdquirente = e.dsAdquirente,
                        stAdquirente = e.stAdquirente,
                        hrExecucao   = e.hrExecucao,
                    }).ToList <dynamic>();
                }
                else if (colecao == 0)
                {
                    CollectionTbAdquirente = query.Select(e => new
                    {
                        cdAdquirente = e.cdAdquirente,
                        nmAdquirente = e.nmAdquirente,
                        dsAdquirente = e.dsAdquirente,
                        stAdquirente = e.stAdquirente,
                        hrExecucao   = e.hrExecucao,
                    }).ToList <dynamic>();
                }
                else if (colecao == 2) // Conciliação Relatórios
                {
                    CollectionTbAdquirente = query.Select(e => new
                    {
                        cdAdquirente = e.cdAdquirente,
                        nmAdquirente = e.nmAdquirente,
                        bandeiras    = e.tbBandeiras.Select(b => new
                        {
                            cdBandeira = b.cdBandeira,
                            dsBandeira = b.dsBandeira,

                            ajustesCredito = b.tbRecebimentoAjustes.Where(a => a.vlAjuste > new decimal(0.0)).Count() > 0 ?
                                             b.tbRecebimentoAjustes
                                             .Where(a => a.vlAjuste > new decimal(0.0))
                                             .Sum(a => a.vlAjuste) : new decimal(0.0),
                            ajustesDebito = b.tbRecebimentoAjustes.Where(a => a.vlAjuste > new decimal(0.0)).Count() > 0 ?
                                            b.tbRecebimentoAjustes
                                            .Where(a => a.vlAjuste < new decimal(0.0))
                                            .Sum(a => a.vlAjuste) : new decimal(0.0),
                        }),
                    }).ToList <dynamic>();
                }

                retorno.Registros = CollectionTbAdquirente;

                return(retorno);
            }
            catch (Exception e)
            {
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao listar parâmetros bancários" : erro);
                }
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
            }
            finally
            {
                if (_dbContext == null)
                {
                    // Fecha conexão
                    _db.Database.Connection.Close();
                    _db.Dispose();
                }
            }
        }
Esempio n. 14
0
        public async Task <OkObjectResult> Post(LoginDataDto dados)
        {
            var resultado = new Retorno <LoginDataDto>();

            string identityServer;

            //if (dados.TipoAutenticacao == TipoAutenticacao.Indefinido)
            //{
            //    List<Login> login = _loginEntityService.ObterPorLogin(dados.Username);

            //    if (login.Count == 1)
            //    {
            //        dados.TipoAutenticacao = login[0].TipoAutenticacao;
            //    }
            //    else
            //    {
            //        resultado.AdicionarMensagem("CAD-010");
            //        resultado.Status = ResultadoOperacao.Falha;
            //        return Ok(resultado);
            //    }
            //}

            //if (dados.TipoAutenticacao == TipoAutenticacao.Local)
            //{
            //    identityServer = ConfigurationManager.AppSettings["IdentityServerLocal"];
            //}
            //else if (dados.TipoAutenticacao == TipoAutenticacao.Sparks)
            //{
            //    identityServer = ConfigurationManager.AppSettings["IdentityServerSparks"];
            //}
            //else if (dados.TipoAutenticacao == TipoAutenticacao.Tms)
            //{
            //    identityServer = ConfigurationManager.AppSettings["IdentityServerTms"];
            //}
            //else
            //{
            //    identityServer = ConfigurationManager.AppSettings["IdentityServer"];
            //}

            //var tokenClient = new TokenClient(identityServer + "/connect/token", dados.ClientId, dados.ClientSecret);
            //TokenResponse token = await tokenClient.RequestResourceOwnerPasswordAsync(dados.Username, dados.Password, dados.Scope);

            //dados.Password = string.Empty;

            //if (token == null || string.IsNullOrWhiteSpace(token.AccessToken))
            //{
            //    if (token != null && token.IsError)
            //    {
            //        JToken errorToken;
            //        if (token.Json != null &&
            //            token.Json.TryGetValue("error_description", out errorToken))
            //        {
            //           // throw new TcpMensagemException(errorToken.ToString());
            //        }
            //        else
            //        {
            //            //throw new TcpMensagemException("CAD-011");
            //        }
            //    }
            //    else
            //    {
            //        //throw new TcpMensagemException("CAD-011");
            //    }
            //}
            //else
            //{
            //    dados.RefreshToken = token.RefreshToken ?? "refresh_token";
            //    dados.Token = token.AccessToken;

            //    resultado.Status = ResultadoOperacao.Sucesso;
            //    resultado.Objeto = dados;
            //}

            var login = new LoginDataDto()
            {
                Username     = "******",
                Password     = "******",
                Token        = "root",
                ClientId     = "root",
                ClientSecret = "root",
                Scope        = "root",
                RefreshToken = "root"
            };

            resultado.Objeto = login;

            return(Ok(resultado));
        }
Esempio n. 15
0
        public Retorno RetornaPedidoPorEntregador(DateTime dtDataInicial, DateTime dtDataFinal, int?intFunCodigo, int intCaiCodigo, string strEmpresa)
        {
            var objRetorno = new Retorno();

            try
            {
                var dtIni = new DateTime(dtDataInicial.Year, dtDataInicial.Month, dtDataInicial.Day, 0, 0, 0);
                var dtFim = new DateTime(dtDataFinal.Year, dtDataFinal.Month, dtDataFinal.Day, 23, 59, 59);

                const string strTitulo  = "RELATORIO DE PEDIDOS POR ENTREGADOR";
                var          sbConteudo = new StringBuilder();
                var          objQuery   = _objCtx.tbPedido.AsNoTracking().Include(fun => fun.tbFuncionarioEntregador)
                                          .Where(ped => ped.ped_origem == "E" &&
                                                 (ped.ped_status == "F" || ped.ped_status == "E"))
                                          .AsQueryable();
                objQuery = intCaiCodigo > 0
                    ? objQuery.Where(cai => cai.cai_codigo == intCaiCodigo)
                    : objQuery.Where(ped => ped.ped_data >= dtIni && ped.ped_data <= dtFim);

                if (intFunCodigo != null)
                {
                    objQuery = objQuery.Where(fun => fun.fun_funcionarioEntregador == intFunCodigo);
                }

                var arrPedido = objQuery.OrderBy(ped => ped.fun_funcionarioEntregador).ThenBy(ped => ped.ped_codigo).ToList();

                if (arrPedido.Count > 0)
                {
                    var strFiltro = intCaiCodigo > 0
                        ? "Caixa: " + intCaiCodigo.ToString()
                        : dtDataInicial.ToShortDateString() + "&nbsp;à&nbsp;" + dtDataFinal.ToShortDateString();
                    sbConteudo.Append(RetornaCabecalho(strEmpresa, strTitulo, strFiltro, 1, 1));
                    int?    intFunCodigoAux = 0;
                    decimal decTotal        = 0;
                    arrPedido.ForEach(fun =>
                    {
                        if (intFunCodigoAux != fun.fun_funcionarioEntregador)
                        {
                            if (intFunCodigoAux == 0)
                            {
                                sbConteudo.Append("<table border=\"0\" width=\"100%\">" + Environment.NewLine);
                            }
                            else
                            {
                                sbConteudo.Append(string.Format("<tr><td colspan=\"6\" align=\"right\">Total: R$ {0}</td></tr>" + Environment.NewLine, decTotal.ToString("0.00")));
                            }
                            sbConteudo.Append(string.Format("<tr><td>Funcionário:</td><td>{0}&nbsp;-&nbsp;{1}</td><td>Quantidade:</td><td>{2}</td><td>&nbsp;</td><td>&nbsp;</td></tr>" + Environment.NewLine,
                                                            fun.fun_funcionarioEntregador,
                                                            fun.tbFuncionarioEntregador.fun_nome,
                                                            arrPedido.Count(ped => ped.fun_funcionarioEntregador == fun.fun_funcionarioEntregador).ToString()));
                            sbConteudo.Append("<tr><th align=\"left\">PEDIDO</th><th align=\"left\">CLIENTE</th><th align=\"left\">DATA</th><th align=\"left\">CAIXA</th><th align=\"left\">ORDEM</th><th align=\"right\">VALOR</th></tr>" + Environment.NewLine);
                            intFunCodigoAux = fun.fun_funcionarioEntregador;
                            decTotal        = 0;
                        }
                        if (fun.ped_data != null)
                        {
                            sbConteudo.Append(string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td align=\"right\">R$ {5}</td></tr>" + Environment.NewLine,
                                                            fun.ped_codigo,
                                                            fun.cli_codigo + "&nbsp;-&nbsp;" + fun.ped_nomeCliente,
                                                            fun.ped_data.Value.ToShortDateString(),
                                                            fun.cai_codigo.ToString(),
                                                            fun.ped_ordem,
                                                            fun.ped_valorTotal.ToString("0.00")));
                        }
                        decTotal += fun.ped_valorTotal;
                    });
                    sbConteudo.Append(string.Format("<tr><td colspan=\"6\" align=\"right\">Total: R$ {0}</td></tr>" + Environment.NewLine, decTotal.ToString("0.00")));
                    sbConteudo.Append("</table>" + Environment.NewLine);
                    sbConteudo.Append(RetornaRodape());

                    var objAssembly = Assembly.GetExecutingAssembly();
                    var strTemplate = "&nbsp;";
                    using (var stream = objAssembly.GetManifestResourceStream("BSFood.Dependencia.RelTemplate.html"))
                    {
                        if (stream != null)
                        {
                            using (var reader = new StreamReader(stream, Encoding.GetEncoding(CultureInfo.GetCultureInfo("pt-BR").TextInfo.ANSICodePage)))
                            {
                                strTemplate = reader.ReadToEnd();
                            }
                        }
                    }
                    objRetorno.intCodigoErro = 0;
                    objRetorno.objRetorno    = string.Format(strTemplate, strTitulo, sbConteudo);
                }
                else
                {
                    objRetorno.intCodigoErro = 48;
                    objRetorno.strMsgErro    = "Registro não encontrado";
                }
            }
            catch (Exception ex)
            {
                Util.LogErro(ex);
                objRetorno.intCodigoErro        = 16;
                objRetorno.strMsgErro           = ex.Message;
                objRetorno.strExceptionToString = ex.ToString();
            }
            return(objRetorno);
        }
Esempio n. 16
0
        public Retorno RetornaCupomEntrega(tbPedido objPedido, int?intPedCodigo = null)
        {
            var objRetorno = new Retorno();

            try
            {
                var sbConteudo = new StringBuilder();
                if (intPedCodigo != null)
                {
                    objPedido = _objCtx.tbPedido.AsNoTracking().FirstOrDefault(ped => ped.ped_codigo == intPedCodigo);
                }

                sbConteudo.Append("        COMPROVANTE DE ENTREGA" + Environment.NewLine);
                sbConteudo.Append(" " + Environment.NewLine);
                if (objPedido != null)
                {
                    sbConteudo.Append("PEDIDO..: " + objPedido.ped_codigo.ToString("0000000000") + new string(' ', 5) + " ORDEM: " + objPedido.ped_ordem.ToString() + Environment.NewLine);
                    sbConteudo.Append("CLIENTE.: " + objPedido.ped_nomeCliente.PadRight(30) + Environment.NewLine);
                    sbConteudo.Append((objPedido.ped_logradouro + "," + objPedido.ped_numero).PadRight(30) + Environment.NewLine);
                    if (!string.IsNullOrWhiteSpace(objPedido.ped_complemento))
                    {
                        sbConteudo.Append(objPedido.ped_complemento.PadRight(30) + Environment.NewLine);
                    }
                    sbConteudo.Append("BAIRRO..: " + objPedido.ped_bairro.PadRight(30) + Environment.NewLine);
                    sbConteudo.Append("TELEFONE: " + objPedido.ped_telefone.PadRight(30) + Environment.NewLine);
                    sbConteudo.Append(Environment.NewLine);
                    sbConteudo.Append("QTD PRODUTO               VALOR   TOTAL" + Environment.NewLine);
                    sbConteudo.Append("---------------------------------------" + Environment.NewLine);
                    foreach (var objPedidoProduto in objPedido.tbPedidoProduto)
                    {
                        var strQuantidade = objPedidoProduto.ppr_quantidade.ToString(objPedidoProduto.ppr_quantidade < 1 ? "0.0" : "000");
                        sbConteudo.Append(strQuantidade + " " +
                                          objPedidoProduto.ppr_descricao.PadRight(19, ' ').Substring(0, 19) + " " +
                                          objPedidoProduto.ppr_valorUnitario.ToString("#,##0.00").PadLeft(7) + " " +
                                          objPedidoProduto.ppr_valorTotal.ToString("#,##0.00").PadLeft(7) + Environment.NewLine);
                    }
                    sbConteudo.Append("              TOTAL PRODUTOS -> " + objPedido.ped_valorSubTotal.ToString("#,##0.00").PadLeft(7) + Environment.NewLine);
                    sbConteudo.Append("                                -------" + Environment.NewLine);
                    if (objPedido.ped_valorTaxaEntrega > 0 || objPedido.ped_valorDespesa > 0 || objPedido.ped_valorDesconto > 0)
                    {
                        if (objPedido.ped_valorTaxaEntrega > 0)
                        {
                            sbConteudo.Append("                 TX. ENTREGA -> " + objPedido.ped_valorTaxaEntrega.ToString("#,##0.00").PadLeft(7) + Environment.NewLine);
                        }
                        if (objPedido.ped_valorDespesa > 0)
                        {
                            sbConteudo.Append("                    DESPESAS -> " + objPedido.ped_valorDespesa.ToString("#,##0.00").PadLeft(7) + Environment.NewLine);
                        }
                        if (objPedido.ped_valorDesconto > 0)
                        {
                            sbConteudo.Append("                    DESCONTO -> " + objPedido.ped_valorDesconto.ToString("#,##0.00").PadLeft(7) + Environment.NewLine);
                        }
                        sbConteudo.Append("             TOTAL DO PEDIDO -> " + objPedido.ped_valorTotal.ToString("#,##0.00").PadLeft(7) + Environment.NewLine);
                    }
                    sbConteudo.Append("              VALOR RECEBIDO -> " + objPedido.ped_valorRecebido.ToString("#,##0.00").PadLeft(7) + Environment.NewLine);
                    sbConteudo.Append("                       TROCO -> " + objPedido.ped_valorTroco.ToString("#,##0.00").PadLeft(7) + Environment.NewLine);
                    sbConteudo.Append("FORMA PAGTO: " + objPedido.tbFormaPagamento.fpg_descricao);
                    sbConteudo.Append("OBSERVACOES: " + objPedido.ped_observacao);
                }

                objRetorno.intCodigoErro = 0;
                objRetorno.objRetorno    = sbConteudo.ToString();
            }
            catch (Exception ex)
            {
                Util.LogErro(ex);
                objRetorno.intCodigoErro        = 16;
                objRetorno.strMsgErro           = ex.Message;
                objRetorno.strExceptionToString = ex.ToString();
            }
            return(objRetorno);
        }
Esempio n. 17
0
        public Retorno RetornaTicketConferencia(tbPedido objPedido, int?intPedCodigo = null)
        {
            var objRetorno = new Retorno();

            try
            {
                var sbConteudo = new StringBuilder();
                if (intPedCodigo != null)
                {
                    objPedido = _objCtx.tbPedido.AsNoTracking().FirstOrDefault(ped => ped.ped_codigo == intPedCodigo);
                }

                sbConteudo.Append("         TICKET DE CONFERENCIA" + Environment.NewLine);
                sbConteudo.Append(" " + Environment.NewLine);
                sbConteudo.Append("QTD PRODUTO               VALOR   TOTAL" + Environment.NewLine);
                sbConteudo.Append("---------------------------------------" + Environment.NewLine);
                if (objPedido != null)
                {
                    foreach (var objPedidoProduto in objPedido.tbPedidoProduto)
                    {
                        var strQuantidade = objPedidoProduto.ppr_quantidade.ToString(objPedidoProduto.ppr_quantidade < 1 ? "0.0" : "000");
                        sbConteudo.Append(strQuantidade + " " +
                                          objPedidoProduto.ppr_descricao.PadRight(19, ' ').Substring(0, 19) + " " +
                                          objPedidoProduto.ppr_valorUnitario.ToString("#,##0.00").PadLeft(7) + " " +
                                          objPedidoProduto.ppr_valorTotal.ToString("#,##0.00").PadLeft(7) + Environment.NewLine);
                    }
                    sbConteudo.Append("                    SUBTOTAL -> " + objPedido.ped_valorSubTotal.ToString("#,##0.00").PadLeft(7) + Environment.NewLine);
                    sbConteudo.Append("                                -------" + Environment.NewLine);
                    if (objPedido.ped_valorTaxaEntrega > 0 || objPedido.ped_valorDespesa > 0 || objPedido.ped_valorDesconto > 0)
                    {
                        if (objPedido.ped_valorTaxaEntrega > 0)
                        {
                            sbConteudo.Append("                 TX. ENTREGA -> " + objPedido.ped_valorTaxaEntrega.ToString("#,##0.00").PadLeft(7) + Environment.NewLine);
                        }
                        if (objPedido.ped_valorDespesa > 0)
                        {
                            sbConteudo.Append("                    DESPESAS -> " + objPedido.ped_valorDespesa.ToString("#,##0.00").PadLeft(7) + Environment.NewLine);
                        }
                        if (objPedido.ped_valorDesconto > 0)
                        {
                            sbConteudo.Append("                    DESCONTO -> " + objPedido.ped_valorDesconto.ToString("#,##0.00").PadLeft(7) + Environment.NewLine);
                        }
                        sbConteudo.Append("                       TOTAL -> " + objPedido.ped_valorTotal.ToString("#,##0.00").PadLeft(7) + Environment.NewLine);
                    }
                    sbConteudo.Append("                    RECEBIDO -> " + objPedido.ped_valorRecebido.ToString("#,##0.00").PadLeft(7) + Environment.NewLine);
                    sbConteudo.Append("                       TROCO -> " + objPedido.ped_valorTroco.ToString("#,##0.00").PadLeft(7) + Environment.NewLine);
                    sbConteudo.Append("OBSERVACOES: " + objPedido.ped_observacao + Environment.NewLine);
                }

                objRetorno.intCodigoErro = 0;
                objRetorno.objRetorno    = sbConteudo.ToString();
            }
            catch (Exception ex)
            {
                Util.LogErro(ex);
                objRetorno.intCodigoErro        = 16;
                objRetorno.strMsgErro           = ex.Message;
                objRetorno.strExceptionToString = ex.ToString();
            }
            return(objRetorno);
        }
Esempio n. 18
0
        public Retorno RetornaCaixaFechamento(tbCaixa objCaixa)
        {
            var objRetorno = new Retorno();

            try
            {
                //if (objCaixa.cai_dataFechamento != null)
                //{
                var arrPedidoVista = _objCtx.tbPedido.AsNoTracking().Where(ped => ped.cai_codigo == objCaixa.cai_codigo &&
                                                                           ped.tbFormaPagamento.fpg_cobranca == "V").ToList();
                decimal decTotalVista = 0;
                if (arrPedidoVista.Count > 0)
                {
                    decTotalVista = arrPedidoVista.Sum(ped => ped.ped_valorTotal);
                }


                var arrPedidoPrazo = _objCtx.tbPedido.AsNoTracking().Where(ped => ped.cai_codigo == objCaixa.cai_codigo &&
                                                                           ped.tbFormaPagamento.fpg_cobranca == "P").ToList();
                decimal decTotalPrazo = 0;
                if (arrPedidoPrazo.Count > 0)
                {
                    decTotalPrazo = arrPedidoPrazo.Sum(ped => ped.ped_valorTotal);
                }


                var arrCaixaMovimentoSaida = _objCtx.tbCaixaMovimento.Include(caio => caio.tbCaixaOperacao).AsNoTracking()
                                             .Where(caim => caim.tbCaixaOperacao.caio_tipoOperacao == "S" && caim.cai_codigo == objCaixa.cai_codigo).ToList();

                decimal decTotalSaida = 0;
                if (arrCaixaMovimentoSaida.Count > 0)
                {
                    decTotalSaida = arrCaixaMovimentoSaida.Sum(caim => caim.caim_valor);
                }


                var arrCaixaMovimentoAbertura = _objCtx.tbCaixaMovimento.Include(fpg => fpg.tbFormaPagamento).AsNoTracking()
                                                .Where(caim => caim.caio_codigo == 1 && caim.cai_codigo == objCaixa.cai_codigo).ToList();

                decimal decTotalAbertura = 0;
                if (arrCaixaMovimentoAbertura.Count > 0)
                {
                    decTotalAbertura = arrCaixaMovimentoAbertura.Sum(caim => caim.caim_valor);
                }


                var arrPedidoEntrega = (from ped in _objCtx.tbPedido
                                        .AsNoTracking()
                                        .Where(ped => ped.cai_codigo == objCaixa.cai_codigo &&
                                               ped.ped_origem == "E" &&
                                               (ped.ped_status == "F" || ped.ped_status == "E"))
                                        group ped by new
                {
                    codigo = ped.fun_funcionarioEntregador,
                    nome = ped.tbFuncionarioEntregador.fun_nome
                }
                                        into grupo
                                        select new
                {
                    grupo.Key.codigo,
                    grupo.Key.nome,
                    decValorTotal = grupo.Sum(ped => ped.ped_valorTotal)
                }).ToList();
                decimal decTotalEntrega = 0;
                if (arrPedidoEntrega.Count > 0)
                {
                    decTotalEntrega = arrPedidoEntrega.Sum(ped => ped.decValorTotal);
                }


                var arrPedidoComanda = _objCtx.tbPedido
                                       .AsNoTracking()
                                       .Where(ped => ped.cai_codigo == objCaixa.cai_codigo &&
                                              ped.ped_origem == "C" && ped.ped_status == "F").ToList();
                decimal decTotalComanda = 0;
                if (arrPedidoComanda.Count > 0)
                {
                    decTotalComanda = arrPedidoComanda.Sum(ped => ped.ped_valorTotal);
                }

                var arrPedidoExcluido = _objCtx.tbPedido
                                        .AsNoTracking()
                                        .Where(ped => ped.cai_codigo == objCaixa.cai_codigo &&
                                               ped.ped_status == "X").ToList();
                decimal decTotalExcluido = 0;
                if (arrPedidoExcluido.Count > 0)
                {
                    decTotalExcluido = arrPedidoExcluido.Sum(ped => ped.ped_valorTotal);
                }

                decimal decTotalRecebimento = 0;

                var arrPedidoForma = (from ped in _objCtx.tbPedido
                                      .AsNoTracking()
                                      .Where(ped => ped.cai_codigo == objCaixa.cai_codigo)
                                      group ped by new
                {
                    codigo = ped.fpg_codigo,
                    descricao = ped.tbFormaPagamento.fpg_descricao,
                    cobranca = ped.tbFormaPagamento.fpg_cobranca
                }
                                      into grupo
                                      select new
                {
                    grupo.Key.codigo,
                    grupo.Key.descricao,
                    grupo.Key.cobranca,
                    decValorTotalForma = grupo.Sum(ped => ped.ped_valorTotal)
                }).ToList();
                decimal decTotalForma = 0;
                if (arrPedidoForma.Count > 0)
                {
                    decTotalForma = arrPedidoForma.Sum(ped => ped.decValorTotalForma);
                }

                var sbRelatorio = new StringBuilder();
                sbRelatorio.Append("          FECHAMENTO DE CAIXA          " + Environment.NewLine);
                sbRelatorio.Append(" " + Environment.NewLine);
                if (objCaixa.cai_dataAbertura != null)
                {
                    sbRelatorio.Append("Data da abertura..: " + objCaixa.cai_dataAbertura.Value.ToString("dd/MM/yyyy HH:mm") + Environment.NewLine);
                }
                if (objCaixa.cai_dataFechamento != null)
                {
                    sbRelatorio.Append("Data do fechamento: " + objCaixa.cai_dataFechamento.Value.ToString("dd/MM/yyyy HH:mm") + Environment.NewLine);
                }
                sbRelatorio.Append("Data da impressao.: " + DateTime.Now.ToString("dd/MM/yyyy HH:mm") + Environment.NewLine);
                sbRelatorio.Append(" " + Environment.NewLine);
                sbRelatorio.Append("             RESUMO PEDIDOS            " + Environment.NewLine);
                sbRelatorio.Append(" " + Environment.NewLine);
                sbRelatorio.Append("TOTAL ABERTURA.............: " + decTotalAbertura.ToString("#,##0.00").PadLeft(10) + Environment.NewLine);
                sbRelatorio.Append("TOTAL A VISTA..............: " + decTotalVista.ToString("#,##0.00").PadLeft(10) + Environment.NewLine);
                sbRelatorio.Append("TOTAL A PRAZO..............: " + decTotalPrazo.ToString("#,##0.00").PadLeft(10) + Environment.NewLine);
                sbRelatorio.Append("TOTAL SAIDAS...............: " + decTotalSaida.ToString("#,##0.00").PadLeft(10) + Environment.NewLine);
                sbRelatorio.Append("TOTAL......................: " + ((decTotalAbertura + decTotalVista + decTotalPrazo) - decTotalSaida).ToString("#,##0.00").PadLeft(10) + Environment.NewLine);
                sbRelatorio.Append("---------------------------------------" + Environment.NewLine);
                sbRelatorio.Append("                ABERTURA               " + Environment.NewLine);
                foreach (var objCaixaMovimentoAbertura in arrCaixaMovimentoAbertura)
                {
                    sbRelatorio.Append(objCaixaMovimentoAbertura.tbFormaPagamento.fpg_descricao.PadRight(28).Substring(0, 28) + " " +
                                       objCaixaMovimentoAbertura.caim_valor.ToString("#,##0.00").PadLeft(10) + Environment.NewLine);
                }
                sbRelatorio.Append("TOTAL......................: " + decTotalAbertura.ToString("#,##0.00").PadLeft(10) + Environment.NewLine);
                sbRelatorio.Append("---------------------------------------" + Environment.NewLine);
                sbRelatorio.Append("                A VISTA                " + Environment.NewLine);
                sbRelatorio.Append("ENTREGAS...................: " + decTotalEntrega.ToString("#,##0.00").PadLeft(10) + Environment.NewLine);
                foreach (var objEntregador in arrPedidoEntrega)
                {
                    sbRelatorio.Append("  " +
                                       (objEntregador.codigo.ToString() + " " + objEntregador.nome).PadRight(15).Substring(0, 15) + " " +
                                       (objEntregador.decValorTotal * 14 / 100).ToString("#,##0.00").PadLeft(10) + " " +
                                       objEntregador.decValorTotal.ToString("#,##0.00").PadLeft(10) + Environment.NewLine);
                }
                sbRelatorio.Append("COMANDAS...................: " + decTotalComanda.ToString("#,##0.00").PadLeft(10) + Environment.NewLine);
                sbRelatorio.Append("RECEBIMENTOS...............: " + decTotalRecebimento.ToString("#,##0.00").PadLeft(10) + Environment.NewLine);
                sbRelatorio.Append("---------------------------------------" + Environment.NewLine);
                sbRelatorio.Append("                A PRAZO                " + Environment.NewLine);
                foreach (var objPedidoPrazo in arrPedidoPrazo)
                {
                    sbRelatorio.Append(objPedidoPrazo.ped_nomeCliente.PadRight(28).Substring(0, 28) + " " +
                                       objPedidoPrazo.ped_valorTotal.ToString("#,##0.00").PadLeft(10) + Environment.NewLine);
                }
                sbRelatorio.Append("TOTAL......................: " + decTotalPrazo.ToString("#,##0.00").PadLeft(10) + Environment.NewLine);
                sbRelatorio.Append("---------------------------------------" + Environment.NewLine);
                sbRelatorio.Append("                SAIDAS                 " + Environment.NewLine);
                foreach (var objCaixaMovimento in arrCaixaMovimentoSaida)
                {
                    string strDescricao = objCaixaMovimento.tbCaixaOperacao.caio_descricao + "-" + objCaixaMovimento.caim_observacao;
                    sbRelatorio.Append(strDescricao.PadRight(28).Substring(0, 28) + " " +
                                       objCaixaMovimento.caim_valor.ToString("#,##0.00").PadLeft(10) + Environment.NewLine);
                }
                sbRelatorio.Append("TOTAL......................: " + decTotalSaida.ToString("#,##0.00").PadLeft(10) + Environment.NewLine);
                sbRelatorio.Append("---------------------------------------" + Environment.NewLine);
                sbRelatorio.Append("               EXCLUIDO                " + Environment.NewLine);
                foreach (var objPedidoExcluido in arrPedidoExcluido)
                {
                    if (objPedidoExcluido.ped_nomeCliente != null)
                    {
                        sbRelatorio.Append(objPedidoExcluido.ped_nomeCliente.PadRight(28).Substring(0, 28) + " " +
                                           objPedidoExcluido.ped_valorTotal.ToString("#,##0.00").PadLeft(10) + Environment.NewLine);
                    }
                }
                sbRelatorio.Append("TOTAL......................: " + decTotalExcluido.ToString("#,##0.00").PadLeft(10) + Environment.NewLine);
                sbRelatorio.Append("---------------------------------------" + Environment.NewLine);
                sbRelatorio.Append("RESUMO DE PEDIDOS POR GRUPO DE PRODUTO " + Environment.NewLine);
                //sbRelatorio.Append("C/ CLB.....................: " + Environment.NewLine);
                //sbRelatorio.Append("TOTAL......................: " + Environment.NewLine);
                sbRelatorio.Append("---------------------------------------" + Environment.NewLine);
                sbRelatorio.Append("         REGISTRO DE ALTERACAO         " + Environment.NewLine);
                //sbRelatorio.Append("M FULANO DE VA            VD           " + Environment.NewLine);
                //sbRelatorio.Append("E MARIA DA  VA            VD           " + Environment.NewLine);
                sbRelatorio.Append("---------------------------------------" + Environment.NewLine);
                sbRelatorio.Append("          FORMAS DE PAGAMENTO          " + Environment.NewLine);
                foreach (var objPedidoForma in arrPedidoForma)
                {
                    if (objPedidoForma.descricao != null)
                    {
                        sbRelatorio.Append((objPedidoForma.descricao + "(" + objPedidoForma.cobranca + ")").PadRight(28).Substring(0, 28) + " " +
                                           objPedidoForma.decValorTotalForma.ToString("#,##0.00").PadLeft(10) + Environment.NewLine);
                    }
                }
                sbRelatorio.Append("TOTAL......................: " + decTotalForma.ToString("#,##0.00").PadLeft(10) + Environment.NewLine);

                objRetorno.intCodigoErro = 0;
                objRetorno.objRetorno    = sbRelatorio.ToString();
                //}
                //else
                //{
                //    objRetorno.intCodigoErro = 0;
                //    objRetorno.objRetorno = string.Empty;
                //}
            }
            catch (Exception ex)
            {
                Util.LogErro(ex);
                objRetorno.intCodigoErro        = 16;
                objRetorno.strMsgErro           = ex.Message;
                objRetorno.strExceptionToString = ex.ToString();
            }
            return(objRetorno);
        }
        public Retorno <reportOut> contratopf_padrao_get(
            string primeiro_nome,
            int id_pessoa,
            int nro_contrato_origem,
            int nro_contrato_destino,
            int isExcluirDependente
            )
        {
            Retorno <reportOut> retorno;
            reportOut           obj = new reportOut();

            //--------------------------------------- Nome do RPT/Contato

            //--------------------------------------- DEFINE O TIPO
            rptToPdf.objReporting.RptToPdf.tipoSaidaReport tipoRpt = new RptToPdf.tipoSaidaReport();
            tipoRpt = RptToPdf.tipoSaidaReport.PDF;

            //--------------------------------------- OBTEM OS PARÂMETROS
            System.Collections.Hashtable parametros = new System.Collections.Hashtable();
            parametros.Add("id_pessoa", id_pessoa);
            parametros.Add("nro_contrato_origem", nro_contrato_origem);
            parametros.Add("nro_contrato_destino", nro_contrato_destino);
            parametros.Add("isexcluirdependente", isExcluirDependente);

            //--------------------------------------- GERA O RELATÓRIO
            try
            {
                byte[] arqBinario = mRetornaBytesPdf_Report(
                    5 /*id_cooperativa*/,
                    "rpt_contrato_pj_to_pf",
                    parametros,
                    tipoRpt
                    );
                obj.documento_x64  = Convert.ToBase64String(arqBinario.ToArray());
                obj.documento_nome = "contrato-pf-" + primeiro_nome + ".pdf";

                if (!string.IsNullOrWhiteSpace(obj.documento_x64))
                {
                    retorno = new Retorno <reportOut>(
                        HttpStatusCode.OK,
                        string.Empty,
                        obj
                        );
                }
                else
                {
                    retorno = new Retorno <reportOut>(
                        HttpStatusCode.NotFound,
                        "A execução do relatório não retornou registos.",
                        obj
                        );
                }
            }
            catch (Exception ex)
            {
                string parametos = "primeiro_nome=" + primeiro_nome + " ,id_pessoa=" + id_pessoa.ToString() + " ,nro_contrato_origem=" + nro_contrato_origem.ToString() + " ,nro_contrato_destino=" + nro_contrato_destino.ToString() + " ,isExcluirDependente = " + isExcluirDependente.ToString();

                log.Error("Erro c#:->" + ex.Message + " parâmetros: " + parametos);
                retorno = new Retorno <reportOut>(
                    HttpStatusCode.InternalServerError,
                    ex.Message,
                    obj
                    );
            }
            return(retorno);
        }
Esempio n. 20
0
        /// <summary>
        /// Retorna Pessoa/Pessoa
        /// </summary>
        /// <returns></returns>
        public static Retorno Get(string token, int colecao = 0, int campo = 0, int orderBy = 0, int pageSize = 0, int pageNumber = 0, Dictionary <string, string> queryString = null, painel_taxservices_dbContext _dbContext = null)
        {
            painel_taxservices_dbContext _db;

            if (_dbContext == null)
            {
                _db = new painel_taxservices_dbContext();
            }
            else
            {
                _db = _dbContext;
            }

            DbContextTransaction transaction = _db.Database.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);

            try
            {
                //DECLARAÇÕES
                List <dynamic> CollectionPessoa = new List <dynamic>();
                Retorno        retorno          = new Retorno();

                // GET QUERY
                var query = getQuery(_db, colecao, campo, orderBy, pageSize, pageNumber, queryString);


                // TOTAL DE REGISTROS
                retorno.TotalDeRegistros = query.Count();


                // PAGINAÇÃO
                int skipRows = (pageNumber - 1) * pageSize;
                if (retorno.TotalDeRegistros > pageSize && pageNumber > 0 && pageSize > 0)
                {
                    query = query.Skip(skipRows).Take(pageSize);
                }
                else
                {
                    pageNumber = 1;
                }

                retorno.PaginaAtual    = pageNumber;
                retorno.ItensPorPagina = pageSize;

                // COLEÇÃO DE RETORNO
                if (colecao == 1)
                {
                    CollectionPessoa = query.Select(e => new
                    {
                        id_pesssoa    = e.id_pesssoa,
                        nm_pessoa     = e.nm_pessoa,
                        dt_nascimento = e.dt_nascimento,
                        nu_telefone   = e.nu_telefone,
                        nu_ramal      = e.nu_ramal,
                    }).ToList <dynamic>();
                }
                else if (colecao == 0)
                {
                    CollectionPessoa = query.Select(e => new
                    {
                        id_pesssoa    = e.id_pesssoa,
                        nm_pessoa     = e.nm_pessoa,
                        dt_nascimento = e.dt_nascimento,
                        nu_telefone   = e.nu_telefone,
                        nu_ramal      = e.nu_ramal,
                    }).ToList <dynamic>();
                }

                transaction.Commit();

                retorno.Registros = CollectionPessoa;

                return(retorno);
            }
            catch (Exception e)
            {
                transaction.Rollback();
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao listar pessoa" : erro);
                }
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
            }
            finally
            {
                if (_dbContext == null)
                {
                    // Fecha conexão
                    _db.Database.Connection.Close();
                    _db.Dispose();
                }
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Retorna GetNetSantander/GetNetSantander
        /// </summary>
        /// <returns></returns>
        public static Retorno Get(string token, int colecao = 0, int campo = 0, int orderBy = 0, int pageSize = 0, int pageNumber = 0, Dictionary <string, string> queryString = null)
        {
            //DECLARAÇÕES
            List <dynamic> CollectionGetNetSantander = new List <dynamic>();
            Retorno        retorno = new Retorno();

            // GET QUERY
            var query      = getQuery(colecao, campo, orderBy, pageSize, pageNumber, queryString);
            var queryTotal = query;

            // TOTAL DE REGISTROS
            retorno.TotalDeRegistros = queryTotal.Count();


            // PAGINAÇÃO
            int skipRows = (pageNumber - 1) * pageSize;

            if (retorno.TotalDeRegistros > pageSize && pageNumber > 0 && pageSize > 0)
            {
                query = query.Skip(skipRows).Take(pageSize);
            }
            else
            {
                pageNumber = 1;
            }

            retorno.PaginaAtual    = pageNumber;
            retorno.ItensPorPagina = pageSize;

            // COLEÇÃO DE RETORNO
            if (colecao == 1)
            {
                CollectionGetNetSantander = query.Select(e => new
                {
                    id                  = e.id,
                    bandeira            = e.bandeira,
                    produto             = e.produto,
                    descricaoTransacao  = e.descricaoTransacao,
                    dtaTransacao        = e.dtaTransacao,
                    hraTransacao        = e.hraTransacao,
                    dtahraTransacao     = e.dtahraTransacao,
                    numCartao           = e.numCartao,
                    numCv               = e.numCv,
                    numAutorizacao      = e.numAutorizacao,
                    valorTotalTransacao = e.valorTotalTransacao,
                    totalParcelas       = e.totalParcelas,
                    cnpj                = e.cnpj,
                    idOperadora         = e.idOperadora,
                    idBandeira          = e.idBandeira,
                    dtaRecebimento      = e.dtaRecebimento,
                    idTerminalLogico    = e.idTerminalLogico,
                }).ToList <dynamic>();
            }
            else if (colecao == 0)
            {
                CollectionGetNetSantander = query.Select(e => new
                {
                    id                  = e.id,
                    bandeira            = e.bandeira,
                    produto             = e.produto,
                    descricaoTransacao  = e.descricaoTransacao,
                    dtaTransacao        = e.dtaTransacao,
                    hraTransacao        = e.hraTransacao,
                    dtahraTransacao     = e.dtahraTransacao,
                    numCartao           = e.numCartao,
                    numCv               = e.numCv,
                    numAutorizacao      = e.numAutorizacao,
                    valorTotalTransacao = e.valorTotalTransacao,
                    totalParcelas       = e.totalParcelas,
                    cnpj                = e.cnpj,
                    idOperadora         = e.idOperadora,
                    idBandeira          = e.idBandeira,
                    dtaRecebimento      = e.dtaRecebimento,
                    idTerminalLogico    = e.idTerminalLogico,
                }).ToList <dynamic>();
            }

            retorno.Registros = CollectionGetNetSantander;

            return(retorno);
        }
Esempio n. 22
0
        /// <summary>
        /// Retorna Bandeiras/Bandeiras
        /// </summary>
        /// <returns></returns>
        public static Retorno Get(string token, int colecao = 0, int campo = 0, int orderBy = 0, int pageSize = 0, int pageNumber = 0, Dictionary <string, string> queryString = null)
        {
            //DECLARAÇÕES
            List <dynamic> CollectionBandeiras = new List <dynamic>();
            Retorno        retorno             = new Retorno();

            // GET QUERY
            var query      = getQuery(colecao, campo, orderBy, pageSize, pageNumber, queryString);
            var queryTotal = query;

            // TOTAL DE REGISTROS
            retorno.TotalDeRegistros = queryTotal.Count();


            // PAGINAÇÃO
            int skipRows = (pageNumber - 1) * pageSize;

            if (retorno.TotalDeRegistros > pageSize && pageNumber > 0 && pageSize > 0)
            {
                query = query.Skip(skipRows).Take(pageSize);
            }
            else
            {
                pageNumber = 1;
            }

            retorno.PaginaAtual    = pageNumber;
            retorno.ItensPorPagina = pageSize;

            // COLEÇÃO DE RETORNO
            if (colecao == 1)
            {
                CollectionBandeiras = query.Select(e => new
                {
                    IdBandeira               = e.IdBandeira,
                    DescricaoBandeira        = e.DescricaoBandeira,
                    IdGrupo                  = e.IdGrupo,
                    CodBandeiraERP           = e.CodBandeiraERP,
                    CodBandeiraHostPagamento = e.CodBandeiraHostPagamento,
                    TaxaAdministracao        = e.TaxaAdministracao,
                    IdTipoPagamento          = e.IdTipoPagamento,
                    Sacado = e.Sacado,
                }).ToList <dynamic>();
            }
            else if (colecao == 0)
            {
                CollectionBandeiras = query.Select(e => new
                {
                    IdBandeira               = e.IdBandeira,
                    DescricaoBandeira        = e.DescricaoBandeira,
                    IdGrupo                  = e.IdGrupo,
                    CodBandeiraERP           = e.CodBandeiraERP,
                    CodBandeiraHostPagamento = e.CodBandeiraHostPagamento,
                    TaxaAdministracao        = e.TaxaAdministracao,
                    IdTipoPagamento          = e.IdTipoPagamento,
                    Sacado = e.Sacado,
                }).ToList <dynamic>();
            }

            retorno.Registros = CollectionBandeiras;

            return(retorno);
        }
Esempio n. 23
0
        /// <summary>
        /// Retorna TicketCar/TicketCar
        /// </summary>
        /// <returns></returns>
        public static Retorno Get(string token, int colecao = 0, int campo = 0, int orderBy = 0, int pageSize = 0, int pageNumber = 0, Dictionary <string, string> queryString = null)
        {
            //DECLARAÇÕES
            List <dynamic> CollectionTicketCar = new List <dynamic>();
            Retorno        retorno             = new Retorno();

            // GET QUERY
            var query      = getQuery(colecao, campo, orderBy, pageSize, pageNumber, queryString);
            var queryTotal = query;

            // TOTAL DE REGISTROS
            retorno.TotalDeRegistros = queryTotal.Count();


            // PAGINAÇÃO
            int skipRows = (pageNumber - 1) * pageSize;

            if (retorno.TotalDeRegistros > pageSize && pageNumber > 0 && pageSize > 0)
            {
                query = query.Skip(skipRows).Take(pageSize);
            }
            else
            {
                pageNumber = 1;
            }

            retorno.PaginaAtual    = pageNumber;
            retorno.ItensPorPagina = pageSize;

            // COLEÇÃO DE RETORNO
            if (colecao == 1)
            {
                CollectionTicketCar = query.Select(e => new
                {
                    id               = e.id,
                    dtaTransacao     = e.dtaTransacao,
                    descricao        = e.descricao,
                    tipoTransacao    = e.tipoTransacao,
                    reembolso        = e.reembolso,
                    numCartao        = e.numCartao,
                    numOS            = e.numOS,
                    mercadoria       = e.mercadoria,
                    qtde             = e.qtde,
                    valorUnitario    = e.valorUnitario,
                    valorDesconto    = e.valorDesconto,
                    valorBruto       = e.valorBruto,
                    empresa          = e.empresa,
                    cnpj             = e.cnpj,
                    idOperadora      = e.idOperadora,
                    idBandeira       = e.idBandeira,
                    dtaRecebimento   = e.dtaRecebimento,
                    idTerminalLogico = e.idTerminalLogico,
                }).ToList <dynamic>();
            }
            else if (colecao == 0)
            {
                CollectionTicketCar = query.Select(e => new
                {
                    id               = e.id,
                    dtaTransacao     = e.dtaTransacao,
                    descricao        = e.descricao,
                    tipoTransacao    = e.tipoTransacao,
                    reembolso        = e.reembolso,
                    numCartao        = e.numCartao,
                    numOS            = e.numOS,
                    mercadoria       = e.mercadoria,
                    qtde             = e.qtde,
                    valorUnitario    = e.valorUnitario,
                    valorDesconto    = e.valorDesconto,
                    valorBruto       = e.valorBruto,
                    empresa          = e.empresa,
                    cnpj             = e.cnpj,
                    idOperadora      = e.idOperadora,
                    idBandeira       = e.idBandeira,
                    dtaRecebimento   = e.dtaRecebimento,
                    idTerminalLogico = e.idTerminalLogico,
                }).ToList <dynamic>();
            }

            retorno.Registros = CollectionTicketCar;

            return(retorno);
        }
 public void RetornouServico(Retorno retorno)
 {
     Console.WriteLine(retorno.Mensagem);
 }
Esempio n. 25
0
        /// <summary>
        /// Retorna BaneseCard/BaneseCard
        /// </summary>
        /// <returns></returns>
        public static Retorno Get(string token, int colecao = 0, int campo = 0, int orderBy = 0, int pageSize = 0, int pageNumber = 0, Dictionary <string, string> queryString = null)
        {
            //DECLARAÇÕES
            List <dynamic> CollectionBaneseCard = new List <dynamic>();
            Retorno        retorno = new Retorno();

            // GET QUERY
            var query      = getQuery(colecao, campo, orderBy, pageSize, pageNumber, queryString);
            var queryTotal = query;

            // TOTAL DE REGISTROS
            retorno.TotalDeRegistros = queryTotal.Count();


            // PAGINAÇÃO
            int skipRows = (pageNumber - 1) * pageSize;

            if (retorno.TotalDeRegistros > pageSize && pageNumber > 0 && pageSize > 0)
            {
                query = query.Skip(skipRows).Take(pageSize);
            }
            else
            {
                pageNumber = 1;
            }

            retorno.PaginaAtual    = pageNumber;
            retorno.ItensPorPagina = pageSize;

            // COLEÇÃO DE RETORNO
            if (colecao == 1)
            {
                CollectionBaneseCard = query.Select(e => new
                {
                    id               = e.id,
                    operacao         = e.operacao,
                    dtaVenda         = e.dtaVenda,
                    nsu              = e.nsu,
                    modalidade       = e.modalidade,
                    totalParcelas    = e.totalParcelas,
                    valorBruto       = e.valorBruto,
                    valorLiquido     = e.valorLiquido,
                    cnpj             = e.cnpj,
                    idOperadora      = e.idOperadora,
                    idBandeira       = e.idBandeira,
                    dtaRecebimento   = e.dtaRecebimento,
                    idTerminalLogico = e.idTerminalLogico,
                }).ToList <dynamic>();
            }
            else if (colecao == 0)
            {
                CollectionBaneseCard = query.Select(e => new
                {
                    id               = e.id,
                    operacao         = e.operacao,
                    dtaVenda         = e.dtaVenda,
                    nsu              = e.nsu,
                    modalidade       = e.modalidade,
                    totalParcelas    = e.totalParcelas,
                    valorBruto       = e.valorBruto,
                    valorLiquido     = e.valorLiquido,
                    cnpj             = e.cnpj,
                    idOperadora      = e.idOperadora,
                    idBandeira       = e.idBandeira,
                    dtaRecebimento   = e.dtaRecebimento,
                    idTerminalLogico = e.idTerminalLogico,
                }).ToList <dynamic>();
            }

            retorno.Registros = CollectionBaneseCard;

            return(retorno);
        }
Esempio n. 26
0
        public Retorno Salvar(string numCliente, int indTipo, string objetoSegurado, int?idSeguro = null)
        {
            Retorno retorno = new Retorno(true);

            try
            {
                string message = "";
                if (string.IsNullOrWhiteSpace(numCliente))
                {
                    message = "O campo Cliente é obrigatório.\n";
                }
                else
                {
                    if (numCliente.Length == 14)
                    {
                        if (!Utilitarios.ValidaCPF(numCliente))
                        {
                            message += "O campo Cliente é inválido.\n";
                        }
                    }
                    else
                    {
                        if (!Utilitarios.ValidaCNPJ(numCliente))
                        {
                            message += "O campo Cliente é inválido.\n";
                        }
                    }
                }
                if (indTipo == 0)
                {
                    message += "O campo Tipo é obrigatorio.\n";
                }
                if (string.IsNullOrWhiteSpace(objetoSegurado))
                {
                    message += "O campo Objeto Segurado é obrigatório.\n";
                }
                else
                {
                    if (indTipo == 3)
                    {
                        if (!Utilitarios.ValidaCPF(objetoSegurado))
                        {
                            message += "O campo Objeto Segurado é obrigatório.";
                        }
                    }
                }
                if (!string.IsNullOrWhiteSpace(message))
                {
                    retorno.Sucesso  = false;
                    retorno.Mensagem = message;
                    return(retorno);
                }

                if (idSeguro.HasValue && idSeguro > 0)
                {
                    foreach (Seguro s in Utilitarios.RetornaDadosLogin().listaSeguros)
                    {
                        if (s.id == idSeguro)
                        {
                            s.indTipo        = indTipo;
                            s.objetoSegurado = objetoSegurado;
                            s.numCliente     = numCliente;
                            s.dscTipo        = indTipo == 1 ? "Automóvel" : indTipo == 2 ? "Residencial" : indTipo == 3 ? "Vida" : "";
                        }
                    }

                    retorno.Mensagem = "Alterado com sucesso!";
                }
                else
                {
                    Utilitarios.RetornaDadosLogin().idCount++;

                    Utilitarios.RetornaDadosLogin().listaSeguros.Add(new Seguro()
                    {
                        id             = Utilitarios.RetornaDadosLogin().idCount,
                        indTipo        = indTipo,
                        objetoSegurado = objetoSegurado,
                        numCliente     = numCliente,
                        dscTipo        = indTipo == 1 ? "Automóvel" : indTipo == 2 ? "Residencial" : indTipo == 3 ? "Vida" : ""
                    });
                    retorno.Mensagem = "Salvo com sucesso!";
                }
            }
            catch (Exception ex)
            {
                retorno.Sucesso  = false;
                retorno.Mensagem = "Erro ao salvar. Erro:" + ex.Message;
            }
            return(retorno);
        }
Esempio n. 27
0
        /// <summary>
        /// Retorna TbRecebimentoVenda/TbRecebimentoVenda
        /// </summary>
        /// <returns></returns>
        public static Retorno Get(string token, int colecao = 0, int campo = 0, int orderBy = 0, int pageSize = 0, int pageNumber = 0, Dictionary <string, string> queryString = null, painel_taxservices_dbContext _dbContext = null)
        {
            painel_taxservices_dbContext _db;

            if (_dbContext == null)
            {
                _db = new painel_taxservices_dbContext();
            }
            else
            {
                _db = _dbContext;
            }
            DbContextTransaction transaction = _db.Database.BeginTransaction(IsolationLevel.ReadUncommitted);

            try
            {
                //DECLARAÇÕES
                List <dynamic> CollectionTbRecebimentoVenda = new List <dynamic>();
                Retorno        retorno = new Retorno();

                // Implementar o filtro por Grupo apartir do TOKEN do Usuário
                string outValue = null;
                Int32  IdGrupo  = Permissoes.GetIdGrupo(token, _db);
                if (IdGrupo != 0)
                {
                    if (queryString.TryGetValue("" + (int)CAMPOS.ID_GRUPO, out outValue))
                    {
                        queryString["" + (int)CAMPOS.ID_GRUPO] = IdGrupo.ToString();
                    }
                    else
                    {
                        queryString.Add("" + (int)CAMPOS.ID_GRUPO, IdGrupo.ToString());
                    }
                }
                string CnpjEmpresa = Permissoes.GetCNPJEmpresa(token, _db);
                if (!CnpjEmpresa.Equals(""))
                {
                    if (queryString.TryGetValue("" + (int)CAMPOS.NRCNPJ, out outValue))
                    {
                        queryString["" + (int)CAMPOS.NRCNPJ] = CnpjEmpresa;
                    }
                    else
                    {
                        queryString.Add("" + (int)CAMPOS.NRCNPJ, CnpjEmpresa);
                    }
                }

                // GET QUERY
                var query = getQuery(_db, colecao, campo, orderBy, pageSize, pageNumber, queryString);


                // TOTAL DE REGISTROS
                retorno.TotalDeRegistros = query.Count();

                List <int> vendasConciliadas = new List <int>();
                if (colecao == 2)
                {
                    // Obtém totais
                    retorno.Totais = new Dictionary <string, object>();
                    if (retorno.TotalDeRegistros > 0)
                    {
                        retorno.Totais.Add("valorTotal", query.Select(e => e.vlVenda).Cast <decimal>().Sum());
                        retorno.Totais.Add("totalCorrigidos", query.Where(e => e.dtAjuste != null).Count());
                        retorno.Totais.Add("totalCorrecaoManual", query.Where(e => e.dtAjuste != null && e.dsMensagem != null).Count());
                        string script = "SELECT DISTINCT R.idRecebimentoVenda" +
                                        " FROM pos.Recebimento R (NOLOCK)" +
                                        " WHERE R.idRecebimentoVenda IN (" + string.Join(", ", query.Select(e => e.idRecebimentoVenda)) + ")";
                        vendasConciliadas = _db.Database.SqlQuery <int>(script).ToList();

                        retorno.Totais.Add("totalConciliados", vendasConciliadas.Count);
                    }
                    else
                    {
                        retorno.Totais.Add("valorTotal", new decimal(0.0));
                        retorno.Totais.Add("totalCorrigidos", 0);
                        retorno.Totais.Add("totalConciliados", 0);
                        retorno.Totais.Add("totalCorrecaoManual", 0);
                    }

                    query = query.OrderBy(e => e.dtVenda).ThenBy(e => e.empresa.ds_fantasia) /*.ThenBy(e => e.tbAdquirente.nmAdquirente)*/.ThenBy(e => e.vlVenda).ThenBy(e => e.nrNSU);
                }

                // PAGINAÇÃO
                int skipRows = (pageNumber - 1) * pageSize;
                if (retorno.TotalDeRegistros > pageSize && pageNumber > 0 && pageSize > 0)
                {
                    query = query.Skip(skipRows).Take(pageSize);
                }
                else
                {
                    pageNumber = 1;
                }

                retorno.PaginaAtual    = pageNumber;
                retorno.ItensPorPagina = pageSize;

                // COLEÇÃO DE RETORNO
                if (colecao == 1)
                {
                    CollectionTbRecebimentoVenda = query.Select(e => new
                    {
                        idRecebimentoVenda = e.idRecebimentoVenda,
                        nrCNPJ             = e.nrCNPJ,
                        nrNSU        = e.nrNSU,
                        dtVenda      = e.dtVenda,
                        cdAdquirente = e.cdAdquirente,
                        dsBandeira   = e.dsBandeira,
                        vlVenda      = e.vlVenda,
                        qtParcelas   = e.qtParcelas,
                        cdERP        = e.cdERP,
                        cdSacado     = e.cdSacado,
                        dsMensagem   = e.dsMensagem,
                        dtAjuste     = e.dtAjuste,
                        dsDetalhe    = e.dsDetalhe,
                    }).ToList <dynamic>();
                }
                else if (colecao == 0)
                {
                    CollectionTbRecebimentoVenda = query.Select(e => new
                    {
                        idRecebimentoVenda = e.idRecebimentoVenda,
                        nrCNPJ             = e.nrCNPJ,
                        nrNSU        = e.nrNSU,
                        dtVenda      = e.dtVenda,
                        cdAdquirente = e.cdAdquirente,
                        dsBandeira   = e.dsBandeira,
                        vlVenda      = e.vlVenda,
                        qtParcelas   = e.qtParcelas,
                        cdERP        = e.cdERP,
                        dsMensagem   = e.dsMensagem,
                        dtAjuste     = e.dtAjuste,
                        cdSacado     = e.cdSacado,
                        dsDetalhe    = e.dsDetalhe,
                    }).ToList <dynamic>();
                }
                else if (colecao == 2) // PORTAL: Consulta Vendas ERP
                {
                    CollectionTbRecebimentoVenda = query.Select(e => new
                    {
                        idRecebimentoVenda = e.idRecebimentoVenda,
                        nrNSU   = e.nrNSU,
                        empresa = _db.empresas.Where(f => f.nu_cnpj.Equals(e.nrCNPJ))
                                  .Select(f => new
                        {
                            f.nu_cnpj,
                            f.ds_fantasia,
                            f.filial
                        })
                                  .FirstOrDefault(),
                        dtVenda      = e.dtVenda,
                        tbAdquirente = _db.tbAdquirentes.Where(a => a.cdAdquirente == e.cdAdquirente)
                                       .Select(a => new
                        {
                            a.cdAdquirente,
                            a.nmAdquirente
                        })
                                       .FirstOrDefault(),
                        dsBandeira = e.dsBandeira,
                        vlVenda    = e.vlVenda,
                        qtParcelas = e.qtParcelas,
                        cdERP      = e.cdERP,
                        cdSacado   = e.cdSacado,
                        dsMensagem = e.dsMensagem,
                        dtAjuste   = e.dtAjuste,
                        dsDetalhe  = e.dsDetalhe,
                        conciliado = vendasConciliadas.Contains(e.idRecebimentoVenda)
                    }).ToList <dynamic>();
                }

                transaction.Commit();

                retorno.Registros = CollectionTbRecebimentoVenda;

                return(retorno);
            }
            catch (Exception e)
            {
                transaction.Rollback();
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao consultar vendas" : erro);
                }
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
            }
            finally
            {
                if (_dbContext == null)
                {
                    // Fecha conexão
                    _db.Database.Connection.Close();
                    _db.Dispose();
                }
            }
        }
Esempio n. 28
0
        /// <summary>
        /// Retorna TbCatalogo/TbCatalogo
        /// </summary>
        /// <returns></returns>
        public static Retorno Get(string token, int colecao = 0, int campo = 0, int orderBy = 0, int pageSize = 0, int pageNumber = 0, Dictionary <string, string> queryString = null)
        {
            try
            {
                //DECLARAÇÕES
                List <dynamic> CollectionTbCatalogo = new List <dynamic>();
                Retorno        retorno = new Retorno();

                // Atualiza o contexto
                ((IObjectContextAdapter)_db).ObjectContext.Refresh(RefreshMode.StoreWins, _db.ChangeTracker.Entries().Select(c => c.Entity));

                // GET QUERY
                var query      = getQuery(colecao, campo, orderBy, pageSize, pageNumber, queryString);
                var queryTotal = query;

                // TOTAL DE REGISTROS
                retorno.TotalDeRegistros = queryTotal.Count();


                // PAGINAÇÃO
                int skipRows = (pageNumber - 1) * pageSize;
                if (retorno.TotalDeRegistros > pageSize && pageNumber > 0 && pageSize > 0)
                {
                    query = query.Skip(skipRows).Take(pageSize);
                }
                else
                {
                    pageNumber = 1;
                }

                retorno.PaginaAtual    = pageNumber;
                retorno.ItensPorPagina = pageSize;

                // Pegar id do usuário pelo token
                var idUsers = Permissoes.GetIdUser(token);

                // COLEÇÃO DE RETORNO
                if (colecao == 1)
                {
                    CollectionTbCatalogo = query.Select(e => new
                    {
                        cdCatalogo = e.cdCatalogo,
                        dsCatalogo = e.dsCatalogo,
                    }).ToList <dynamic>();
                }
                else if (colecao == 0)
                {
                    CollectionTbCatalogo = query.Select(e => new
                    {
                        cdCatalogo = e.cdCatalogo,
                        dsCatalogo = e.dsCatalogo,
                    }).ToList <dynamic>();
                }
                else if (colecao == 2)
                {
                    CollectionTbCatalogo = query
                                           // .Where(e => _db.tbAssinantes.Where(a => a.id_users == idUsers).Select(a => a.cdCatalogo).Contains(e.cdCatalogo))
                                           .Select(e => new
                    {
                        cdCatalogo = e.cdCatalogo,
                        dsCatalogo = e.dsCatalogo,
                        flInscrito = _db.tbAssinantes
                                     .Where(a => a.id_users == idUsers)
                                     .Select(a => a.cdCatalogo)
                                     .Contains(e.cdCatalogo)
                    }).ToList <dynamic>();
                }

                retorno.Registros = CollectionTbCatalogo;

                return(retorno);
            }
            catch (Exception e)
            {
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao listar TbCatalogo" : erro);
                }
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Retorna TbBancoParametro/TbBancoParametro
        /// </summary>
        /// <returns></returns>
        public static Retorno Get(string token, int colecao = 0, int campo = 0, int orderBy = 0, int pageSize = 0, int pageNumber = 0, Dictionary <string, string> queryString = null, painel_taxservices_dbContext _dbContext = null)
        {
            painel_taxservices_dbContext _db;

            if (_dbContext == null)
            {
                _db = new painel_taxservices_dbContext();
            }
            else
            {
                _db = _dbContext;
            }
            DbContextTransaction transaction = _db.Database.BeginTransaction(IsolationLevel.ReadUncommitted);

            try
            {
                //DECLARAÇÕES
                List <dynamic> CollectionTbBancoParametro = new List <dynamic>();
                Retorno        retorno = new Retorno();

                // FILTRO DE GRUPO
                string outValue = null;
                Int32  IdGrupo  = Permissoes.GetIdGrupo(token, _db);
                if (IdGrupo != 0)
                {
                    if (queryString.TryGetValue("" + (int)CAMPOS.ID_GRUPO, out outValue))
                    {
                        queryString["" + (int)CAMPOS.ID_GRUPO] = IdGrupo.ToString();
                    }
                    else
                    {
                        queryString.Add("" + (int)CAMPOS.ID_GRUPO, IdGrupo.ToString());
                    }
                }
                // FILTRO DE FILIAL
                string CnpjEmpresa = Permissoes.GetCNPJEmpresa(token, _db);
                if (!CnpjEmpresa.Equals(""))
                {
                    if (queryString.TryGetValue("" + (int)CAMPOS.NRCNPJ, out outValue))
                    {
                        queryString["" + (int)CAMPOS.NRCNPJ] = CnpjEmpresa;
                    }
                    else
                    {
                        queryString.Add("" + (int)CAMPOS.NRCNPJ, CnpjEmpresa);
                    }
                }

                // POR DEFAULT, LISTA SOMENTE OS QUE ESTÃO VISÍVEIS
                //if (!queryString.TryGetValue("" + (int)CAMPOS.FLVISIVEL, out outValue))
                //    queryString.Add("" + (int)CAMPOS.FLVISIVEL, Convert.ToString(true));

                // GET QUERY
                var query = getQuery(_db, colecao, campo, orderBy, pageSize, pageNumber, queryString);

                // TOTAL DE REGISTROS
                retorno.TotalDeRegistros = query.Count();


                // PAGINAÇÃO
                int skipRows = (pageNumber - 1) * pageSize;
                if (retorno.TotalDeRegistros > pageSize && pageNumber > 0 && pageSize > 0)
                {
                    query = query.Skip(skipRows).Take(pageSize);
                }
                else
                {
                    pageNumber = 1;
                }

                retorno.PaginaAtual    = pageNumber;
                retorno.ItensPorPagina = pageSize;

                // COLEÇÃO DE RETORNO
                if (colecao == 1)
                {
                    CollectionTbBancoParametro = query.Select(e => new
                    {
                        cdBanco       = e.cdBanco,
                        dsMemo        = e.dsMemo,
                        cdAdquirente  = e.cdAdquirente,
                        dsTipo        = e.dsTipo,
                        flVisivel     = e.flVisivel,
                        nrCnpj        = e.nrCnpj,
                        dsTipoCartao  = e.dsTipoCartao.TrimEnd(),
                        cdBandeira    = e.cdBandeira,
                        flAntecipacao = e.flAntecipacao,
                        cdGrupo       = e.cdGrupo,
                    }).ToList <dynamic>();
                }
                else if (colecao == 0)
                {
                    CollectionTbBancoParametro = query.Select(e => new
                    {
                        cdBanco       = e.cdBanco,
                        dsMemo        = e.dsMemo,
                        cdAdquirente  = e.cdAdquirente,
                        dsTipo        = e.dsTipo,
                        flVisivel     = e.flVisivel,
                        nrCnpj        = e.nrCnpj,
                        dsTipoCartao  = e.dsTipoCartao.TrimEnd(),
                        cdBandeira    = e.cdBandeira,
                        flAntecipacao = e.flAntecipacao,
                        cdGrupo       = e.cdGrupo,
                    }).ToList <dynamic>();
                }
                else if (colecao == 2) // [WEB]
                {
                    List <dynamic> bancoParametros = query.Select(e => new
                    {
                        dsMemo     = e.dsMemo,
                        adquirente = e.cdAdquirente == null ? null : new
                        {
                            cdAdquirente = e.tbAdquirente.cdAdquirente,
                            nmAdquirente = e.tbAdquirente.nmAdquirente,
                            dsAdquirente = e.tbAdquirente.dsAdquirente,
                            stAdquirente = e.tbAdquirente.stAdquirente,
                        },
                        dsTipo        = e.dsTipo,
                        flVisivel     = e.flVisivel,
                        flAntecipacao = e.flAntecipacao,
                        dsTipoCartao  = e.dsTipoCartao.TrimEnd(),
                        empresa       = e.nrCnpj == null ? null : new
                        {
                            nu_cnpj     = e.empresa.nu_cnpj,
                            ds_fantasia = e.empresa.ds_fantasia,
                            filial      = e.empresa.filial
                        },
                        grupoempresa = new
                        {
                            id_grupo = e.cdGrupo,
                            ds_nome  = e.grupo_empresa.ds_nome
                        },
                        bandeira = e.cdBandeira == null ? null : new
                        {
                            cdBandeira = e.tbBandeira.cdBandeira,
                            dsBandeira = e.tbBandeira.dsBandeira,
                            dsTipo     = e.tbBandeira.dsTipo
                        },
                        banco = new { Codigo = e.cdBanco, NomeExtenso = "" }, // Não dá para chamar a função direto daqui pois esse código é convertido em SQL e não acessa os dados de um objeto em memória
                    }).ToList <dynamic>();

                    // Após transformar em lista (isto é, trazer para a memória), atualiza o valor do NomeExtenso associado ao banco
                    foreach (var bancoParametro in bancoParametros)
                    {
                        CollectionTbBancoParametro.Add(new
                        {
                            dsMemo        = bancoParametro.dsMemo,
                            adquirente    = bancoParametro.adquirente,
                            dsTipo        = bancoParametro.dsTipo,
                            flVisivel     = bancoParametro.flVisivel,
                            flAntecipacao = bancoParametro.flAntecipacao,
                            empresa       = bancoParametro.empresa,
                            grupoempresa  = bancoParametro.grupoempresa,
                            bandeira      = bancoParametro.bandeira,
                            dsTipoCartao  = bancoParametro.dsTipoCartao,
                            banco         = new { Codigo = bancoParametro.banco.Codigo, NomeExtenso = GatewayBancos.Get(bancoParametro.banco.Codigo) },
                        });
                    }
                }

                transaction.Commit();

                retorno.Registros = CollectionTbBancoParametro;

                return(retorno);
            }
            catch (Exception e)
            {
                transaction.Rollback();
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao listar parâmetros bancários" : erro);
                }
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
            }
            finally
            {
                if (_dbContext == null)
                {
                    // Fecha conexão
                    _db.Database.Connection.Close();
                    _db.Dispose();
                }
            }
        }
Esempio n. 30
0
        private void ConcluirChamada(ObservableCollection <AlunoChamadaVO> sourceList)
        {
            List <AlunoChamadaAlteracaoVO> alunosPresentes = new List <AlunoChamadaAlteracaoVO>();

            foreach (AlunoChamadaVO aluno in sourceList)
            {
                if (aluno.Selected)
                {
                    alunosPresentes.Add(new AlunoChamadaAlteracaoVO
                    {
                        Id                = aluno.Id,
                        chamadaId         = chamada.Id,
                        sitAlunoChamadaId = (int)SitAlunoChamadaEnum.PresencaConfirmada
                    });
                }
            }

            Retorno param = new Retorno();

            param.ObjRetorno  = chamada;
            param.ListRetorno = alunosPresentes.Cast <object>().ToList();

            ConsumeRest concluirChamada = new ConsumeRest();

            concluirChamada.PostResponse <Retorno>("chamada/ConcluirChamada", param).ContinueWith(t =>
            {
                if (t.IsCompleted && t.Result != null)
                {
                    Device.BeginInvokeOnMainThread(async() =>
                    {
                        if ((TpRetornoEnum)t.Result.TpRetorno == TpRetornoEnum.Sucesso)
                        {
                            conteudo = new StackLayout
                            {
                                Padding  = new Thickness(10, Device.OnPlatform(20, 0, 0), 10, 5),
                                Children =
                                {
                                    info
                                }
                            };

                            Label lb = GetLabelDefaul();

                            lb.Text = t.Result.RetornoMensagem + ((!string.IsNullOrWhiteSpace(t.Result.RetornoDescricao)) ?
                                                                  (Environment.NewLine + t.Result.RetornoDescricao) : "");

                            info.BackgroundColor = Color.FromHex("328325");
                            info.IsVisible       = true;
                            info.Content         = lb;

                            await Task.Delay(500);
                            App.GetHome();
                        }
                        else if ((TpRetornoEnum)t.Result.TpRetorno == TpRetornoEnum.Erro)
                        {
                            await DisplayAlert(t.Result.RetornoMensagem, t.Result.RetornoDescricao, "OK");
                        }
                    });
                }
            });
        }
Esempio n. 31
0
        /// <summary>
        /// Retorna LogExecutionException/LogExecutionException
        /// </summary>
        /// <returns></returns>
        public static Retorno Get(string token, int colecao = 0, int campo = 0, int orderBy = 0, int pageSize = 0, int pageNumber = 0, Dictionary <string, string> queryString = null)
        {
            try
            {
                //DECLARAÇÕES
                List <dynamic> CollectionLogExecutionException = new List <dynamic>();
                Retorno        retorno = new Retorno();

                // GET QUERY
                var query      = getQuery(colecao, campo, orderBy, pageSize, pageNumber, queryString);
                var queryTotal = query;

                // TOTAL DE REGISTROS
                retorno.TotalDeRegistros = queryTotal.Count();


                // PAGINAÇÃO
                int skipRows = (pageNumber - 1) * pageSize;
                if (retorno.TotalDeRegistros > pageSize && pageNumber > 0 && pageSize > 0)
                {
                    query = query.Skip(skipRows).Take(pageSize);
                }
                else
                {
                    pageNumber = 1;
                }

                retorno.PaginaAtual    = pageNumber;
                retorno.ItensPorPagina = pageSize;

                // COLEÇÃO DE RETORNO
                if (colecao == 1)
                {
                    CollectionLogExecutionException = query.Select(e => new
                    {
                        id             = e.id,
                        idLogExecution = e.idLogExecution,
                        textError      = e.textError,
                    }).ToList <dynamic>();
                }
                else if (colecao == 0)
                {
                    CollectionLogExecutionException = query.Select(e => new
                    {
                        id             = e.id,
                        idLogExecution = e.idLogExecution,
                        textError      = e.textError,
                    }).ToList <dynamic>();
                }

                retorno.Registros = CollectionLogExecutionException;

                return(retorno);
            }
            catch (Exception e)
            {
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao listar logexecutionexception" : erro);
                }
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
            }
        }
Esempio n. 32
0
        private async Task RetrieveLocation()
        {
            try
            {
                if (Titulo_entry.Text.Equals(""))
                {
                    await DisplayAlert("Atenção!",
                                       "Título deve ser preenchido!", "Ok");
                }
                else if (Descricao_entry.Text.Equals(""))
                {
                    await DisplayAlert("Atenção!",
                                       "Descrição deve ser preenchida!", "Ok");
                }
                else if (file == null)
                {
                    await DisplayAlert("Atenção!",
                                       "Foto é obrigatória!", "Ok");
                }
                else
                {
                    var location = await Geolocation.GetLocationAsync();

                    Publicacao publicacao = new Publicacao();
                    publicacao.Origem    = "APP";
                    publicacao.Login     = "******";
                    publicacao.Titulo    = Titulo_entry.Text;
                    publicacao.Descricao = Descricao_entry.Text;
                    publicacao.Longitude = location.Longitude.ToString();
                    publicacao.Altitude  = location.Altitude.ToString();
                    publicacao.Latitude  = location.Latitude.ToString();
                    publicacao.Imagem    = await ConvertToBase64(file.GetStream());

                    PublicacaoService publicacaoService = new PublicacaoService();
                    Retorno           retorno           = publicacaoService.NovaPublicacao(publicacao);

                    if (retorno != null)
                    {
                        await DisplayAlert("",
                                           "Publicação criada com sucesso!", "Ok");

                        await Navigation.PushAsync(new Publicacoes());
                    }
                    else
                    {
                        await DisplayAlert("Atenção!",
                                           "Problemas ao gravar publicação!", "Ok");
                    }
                }
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                await DisplayAlert("Handle not supported on device exception",
                                   fnsEx.Message, "Ok");
            }
            catch (PermissionException pEx)
            {
                await DisplayAlert("Handle permission exception",
                                   pEx.Message, "Ok");
            }
            catch (Exception ex)
            {
                await DisplayAlert("Unable to get location",
                                   ex.Message, "Ok");
            }
        }
Esempio n. 33
0
        /// <summary>
        /// Retorna Webpages_Users/Webpages_Users
        /// </summary>
        /// <returns></returns>
        public static Retorno Get(string token, int colecao = 0, int campo = 0, int orderBy = 0, int pageSize = 0, int pageNumber = 0, Dictionary <string, string> queryString = null, painel_taxservices_dbContext _dbContext = null)
        {
            painel_taxservices_dbContext _db;

            if (_dbContext == null)
            {
                _db = new painel_taxservices_dbContext();
            }
            else
            {
                _db = _dbContext;
            }

            DbContextTransaction transaction = _db.Database.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);

            try
            {
                //DECLARAÇÕES
                List <dynamic> CollectionWebpages_Users = new List <dynamic>();
                Retorno        retorno = new Retorno();

                // Se for uma consulta por um login ou e-mail específico na coleção 0, não força filtro por empresa, filial e rolelevel
                string  outValue      = null;
                Boolean FiltroForcado = true;

                if (colecao == 0)
                {
                    Boolean filtroLogin = queryString.TryGetValue("" + (int)CAMPOS.DS_LOGIN, out outValue);
                    Boolean filtroEmail = queryString.TryGetValue("" + (int)CAMPOS.DS_EMAIL, out outValue);

                    if (filtroLogin && filtroEmail)
                    {
                        FiltroForcado = queryString["" + (int)CAMPOS.DS_LOGIN].Contains("%") || queryString["" + (int)CAMPOS.DS_EMAIL].Contains("%");
                    }
                    else if (filtroLogin)
                    {
                        FiltroForcado = queryString["" + (int)CAMPOS.DS_LOGIN].Contains("%");
                    }
                    else if (filtroEmail)
                    {
                        FiltroForcado = queryString["" + (int)CAMPOS.DS_EMAIL].Contains("%");
                    }
                }

                // Implementar o filtro por Grupo apartir do TOKEN do Usuário
                Int32 IdGrupo = 0;
                if (FiltroForcado)
                {
                    IdGrupo = Permissoes.GetIdGrupo(token, _db);
                    if (IdGrupo != 0)
                    {
                        if (queryString.TryGetValue("" + (int)CAMPOS.ID_GRUPO, out outValue))
                        {
                            queryString["" + (int)CAMPOS.ID_GRUPO] = IdGrupo.ToString();
                        }
                        else
                        {
                            queryString.Add("" + (int)CAMPOS.ID_GRUPO, IdGrupo.ToString());
                        }
                    }
                    string CnpjEmpresa = Permissoes.GetCNPJEmpresa(token, _db);
                    if (!CnpjEmpresa.Equals(""))
                    {
                        if (queryString.TryGetValue("" + (int)CAMPOS.NU_CNPJEMPRESA, out outValue))
                        {
                            queryString["" + (int)CAMPOS.NU_CNPJEMPRESA] = CnpjEmpresa;
                        }
                        else
                        {
                            queryString.Add("" + (int)CAMPOS.NU_CNPJEMPRESA, CnpjEmpresa);
                        }
                    }
                }

                if (colecao == 3)
                {
                    int IdUsers = Permissoes.GetIdUser(token, _db);
                    if (IdUsers != 0)
                    {
                        if (queryString.TryGetValue("" + (int)CAMPOS.ID_USERS, out outValue))
                        {
                            queryString["" + (int)CAMPOS.ID_USERS] = IdUsers.ToString();
                        }
                        else
                        {
                            queryString.Add("" + (int)CAMPOS.ID_USERS, IdUsers.ToString());
                        }
                    }
                }

                // GET QUERY
                var query = getQuery(_db, colecao, campo, orderBy, pageSize, pageNumber, queryString);


                if (colecao != 3) // [WEB] A coleção 3 permite que o usuário de qualquer perfil obtenha os seus próprios dados
                {
                    if (FiltroForcado)
                    {
                        // Restringe consulta pelo perfil do usuário logado
                        Int32 RoleLevelMin = Permissoes.GetRoleLevelMin(token, _db);
                        //String RoleName = Permissoes.GetRoleName(token).ToUpper();
                        bool isAtosVendedor = Permissoes.isAtosRoleVendedor(token, _db);
                        if (IdGrupo == 0 && isAtosVendedor)//RoleName.Equals("COMERCIAL"))
                        {
                            // Perfil Comercial tem uma carteira de clientes específica
                            List <Int32> listaIdsGruposEmpresas = Permissoes.GetIdsGruposEmpresasVendedor(token, _db);
                            query = query.Where(e => e.webpages_Membership.webpages_UsersInRoles.FirstOrDefault().webpages_Roles.RoleLevel >= RoleLevelMin &&
                                                e.id_grupo != null && listaIdsGruposEmpresas.Contains(e.id_grupo ?? -1)).AsQueryable <webpages_Users>();
                        }
                        else if (Permissoes.isAtosRole(token, _db) && !isAtosVendedor)//RoleName.Equals("COMERCIAL"))
                        // ATOS de nível mais alto: Lista os usuários que não tem role associada ou aqueles de RoleLevel permitido para o usuário logado consultar
                        {
                            query = query.Where(e => e.webpages_Membership.webpages_UsersInRoles.ToList <dynamic>().Count == 0 || e.webpages_Membership.webpages_UsersInRoles.FirstOrDefault().webpages_Roles.RoleLevel >= RoleLevelMin).AsQueryable <webpages_Users>();
                        }
                        else
                        {
                            // Só exibe os usuários de RoleLevelMin
                            query = query.Where(e => e.webpages_Membership.webpages_UsersInRoles.FirstOrDefault().webpages_Roles.RoleLevel >= RoleLevelMin).AsQueryable <webpages_Users>();
                        }
                    }
                }

                // TOTAL DE REGISTROS
                retorno.TotalDeRegistros = query.Count();


                // PAGINAÇÃO
                int skipRows = (pageNumber - 1) * pageSize;
                if (retorno.TotalDeRegistros > pageSize && pageNumber > 0 && pageSize > 0)
                {
                    query = query.Skip(skipRows).Take(pageSize);
                }
                else
                {
                    pageNumber = 1;
                }

                retorno.PaginaAtual    = pageNumber;
                retorno.ItensPorPagina = pageSize;

                // COLEÇÃO DE RETORNO
                if (colecao == 1)
                {
                    CollectionWebpages_Users = query.Select(e => new
                    {
                        id_users           = e.id_users,
                        ds_login           = e.ds_login,
                        ds_email           = e.ds_email,
                        id_grupo           = e.id_grupo,
                        fl_ativo           = e.fl_ativo,
                        nu_cnpjEmpresa     = e.nu_cnpjEmpresa,
                        nu_cnpjBaseEmpresa = e.nu_cnpjBaseEmpresa,
                        id_pessoa          = e.id_pessoa,
                    }).ToList <dynamic>();
                }
                else if (colecao == 0)
                {
                    CollectionWebpages_Users = query.Select(e => new
                    {
                        id_users           = e.id_users,
                        ds_login           = e.ds_login,
                        ds_email           = e.ds_email,
                        id_grupo           = e.id_grupo,
                        fl_ativo           = e.fl_ativo,
                        nu_cnpjEmpresa     = e.nu_cnpjEmpresa,
                        nu_cnpjBaseEmpresa = e.nu_cnpjBaseEmpresa,
                        id_pessoa          = e.id_pessoa,
                    }).ToList <dynamic>();
                }
                else if (colecao == 2 || colecao == 3) // [WEB] Dados do Usuário Logado COLEÇÃO 3
                {
                    CollectionWebpages_Users = query.Select(
                        e => new
                    {
                        webpagesusers = new
                        {
                            id_users           = e.id_users,
                            ds_login           = e.ds_login,
                            ds_email           = e.ds_email,
                            id_grupo           = e.id_grupo,
                            fl_ativo           = e.fl_ativo,
                            nu_cnpjEmpresa     = e.nu_cnpjEmpresa,
                            nu_cnpjBaseEmpresa = e.nu_cnpjBaseEmpresa,
                            id_pessoa          = e.id_pessoa
                        },
                        pessoa = new
                        {
                            nm_pessoa     = e.pessoa.nm_pessoa,
                            dt_nascimento = e.pessoa.dt_nascimento,
                            nu_telefone   = e.pessoa.nu_telefone,
                            nu_ramal      = e.pessoa.nu_ramal
                        },
                        webpagesusersinroles = _db.webpages_UsersInRoles.Where(r => r.RoleId > 50).Where(r => r.UserId == e.id_users).Select(r => new { RoleId = r.RoleId, RoleName = r.webpages_Roles.RoleName, RolePrincipal = r.RolePrincipal }).ToList(),
                        grupoempresa         = e.grupo_empresa.ds_nome,
                        empresa     = e.empresa.ds_fantasia + (e.empresa.filial != null ? " " + e.empresa.filial : ""),
                        podeExcluir = e.LogAcesso1.Count() == 0,
                        //gruposempresasvendedor2 = _db.grupo_empresa.Where(g => g.id_vendedor == e.id_users).Select(g => new { g.id_grupo, g.ds_nome }).ToList(),
                        gruposvendedor = e.grupo_empresa_vendedor.Select(g => new { g.id_grupo, g.ds_nome }).ToList()
                    }).ToList <dynamic>();
                }
                else if (colecao == 3) // [WEB] Dados do Usuário Logado
                {
                    // OBS: UTILIZADO EM CONJUNTO COM A COLEÇÃO 2
                }

                else if (colecao == 4)
                {
                    if (queryString.TryGetValue("" + (int)CAMPOS.DS_LOGIN, out outValue))
                    {
                        string ds_login = queryString[((int)CAMPOS.DS_LOGIN).ToString()];
                        retorno.TotalDeRegistros = _db.webpages_Users.Where(e => e.ds_login.Equals(ds_login)).Count();
                    }
                    else if (queryString.TryGetValue("" + (int)CAMPOS.DS_EMAIL, out outValue))
                    {
                        string ds_email = queryString[((int)CAMPOS.DS_EMAIL).ToString()];
                        retorno.TotalDeRegistros = _db.webpages_Users.Where(e => e.ds_email.Equals(ds_email)).Count();
                    }
                    else if (queryString.TryGetValue("" + (int)CAMPOS.ID_USERS, out outValue))
                    {
                        Int32 id_users = Convert.ToInt32(queryString[((int)CAMPOS.ID_USERS).ToString()]);
                        retorno.TotalDeRegistros = _db.LogAcesso1.Where(e => e.idUsers == id_users).Count() > 0 ? 1 : 0;
                    }
                    else
                    {
                        retorno.TotalDeRegistros = 0;
                    }
                }

                /*else if (colecao == 5) // se o usuário tiver atividade no log, retorno = false
                 * {
                 *  int idUsers = int.Parse(queryString[((int)CAMPOS.ID_USERS).ToString()]);
                 *
                 *  var o = new
                 *  {
                 *      log = _db.LogAcesso1.Where(e => e.idUsers == idUsers).Count() == 0
                 *  };
                 *  CollectionWebpages_Users.Add(o);
                 * }*/

                transaction.Commit();

                retorno.Registros = CollectionWebpages_Users;

                return(retorno);
            }
            catch (Exception e)
            {
                transaction.Rollback();
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao listar usuário" : erro);
                }
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
            }
            finally
            {
                if (_dbContext == null)
                {
                    // Fecha conexão
                    _db.Database.Connection.Close();
                    _db.Dispose();
                }
            }
        }
Esempio n. 34
0
        public Retorno CriaUsuario(Usuario usuario)
        {
            Retorno    r           = new Retorno();
            ValidaForm vlform      = ValidaUsuario(usuario);
            bool       emailexiste = false;

            emailexiste = db.Usuarios.Where(x => x.Email == usuario.Email).Any();
            if (emailexiste)
            {
                r.responseStatus = "NOK";
                r.desc           = "Email já existente.";
                return(r);
            }
            if (!vlform.Valido)
            {
                r.responseStatus = "NOK";
                r.desc           = vlform.Erro;
                return(r);
            }
            else
            {
                usuario.CriadoEm     = DateTime.Now;
                usuario.AtualizadoEm = DateTime.Now;
                db.Usuarios.Add(usuario);

                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateException)
                {
                    if (!UsuarioExists(usuario.UsuarioId))
                    {
                        r.responseStatus = "NOK";
                        r.desc           = "Usuário não existe.";
                        return(r);
                    }
                    else
                    {
                        r.responseStatus = "NOK";
                        r.desc           = "Algum erro ocorreu. Tente mais tarde.";
                        return(r);
                    }
                }
                try
                {
                    string urltemplate = ActualHost + "/emailtemplate/bemvindo";
                    string envio       = F.SendMail("", usuario.Email, "Confirme seu Cadastro", urltemplate, true, usuario.Nome);
                    if (envio == "OK")
                    {
                        r.responseStatus = "OK";
                    }
                    else
                    {
                        r.responseStatus = "NOK";
                        r.desc           = envio;
                    }
                }
                catch (Exception e)
                {
                    r.responseStatus = "NOK";
                    r.desc           = e.ToString();
                }
                return(r);
            }
        }