Beispiel #1
0
        /// <summary>
        /// Retorna o relatório de conciliação de títulos
        /// </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> CollectionRelatorioConciliacaoTitulos = new List <dynamic>();
                Retorno        retorno = new Retorno();


                // QUERIES DE FILTRO
                string outValue = null;
                Dictionary <string, string> queryStringRecebimentoParcela = new Dictionary <string, string>();
                //Dictionary<string, string> queryStringTbRecebimentoTitulo = new Dictionary<string, string>();
                // DATA
                string data = String.Empty;
                if (queryString.TryGetValue("" + (int)CAMPOS.DATA, out outValue))
                {
                    data = queryString["" + (int)CAMPOS.DATA];
                    queryStringRecebimentoParcela.Add("" + (int)GatewayRecebimentoParcela.CAMPOS.DTARECEBIMENTOEFETIVO, data);
                    //queryStringTbRecebimentoTitulo.Add("" + (int)GatewayTbRecebimentoTitulo.CAMPOS.DTTITULO, data);
                }
                // GRUPO EMPRESA => OBRIGATÓRIO!
                Int32 IdGrupo = Permissoes.GetIdGrupo(token, _db);
                if (IdGrupo == 0 && queryString.TryGetValue("" + (int)CAMPOS.ID_GRUPO, out outValue))
                {
                    IdGrupo = Convert.ToInt32(queryString["" + (int)CAMPOS.ID_GRUPO]);
                }
                if (IdGrupo != 0)
                {
                    queryStringRecebimentoParcela.Add("" + (int)GatewayRecebimentoParcela.CAMPOS.ID_GRUPO, IdGrupo.ToString());
                    //queryStringTbRecebimentoTitulo.Add("" + (int)GatewayTbRecebimentoTitulo.CAMPOS.ID_GRUPO, IdGrupo.ToString());
                }
                else
                {
                    throw new Exception("Um grupo deve ser selecionado como filtro de relatório de conciliação de títulos!");
                }
                // FILIAL
                string CnpjEmpresa = Permissoes.GetCNPJEmpresa(token, _db);
                if (CnpjEmpresa.Equals("") && queryString.TryGetValue("" + (int)CAMPOS.NU_CNPJ, out outValue))
                {
                    CnpjEmpresa = queryString["" + (int)CAMPOS.NU_CNPJ];
                }
                if (!CnpjEmpresa.Equals(""))
                {
                    queryStringRecebimentoParcela.Add("" + (int)GatewayRecebimentoParcela.CAMPOS.NU_CNPJ, CnpjEmpresa);
                    //queryStringTbRecebimentoTitulo.Add("" + (int)GatewayTbRecebimentoTitulo.CAMPOS.NRCNPJ, CnpjEmpresa);
                }
                else
                {
                    throw new Exception("Uma filial deve ser selecionada como filtro de relatório de conciliação de títulos!");
                }
                // ADQUIRENTE
                string cdAdquirente = String.Empty;
                if (queryString.TryGetValue("" + (int)CAMPOS.CDADQUIRENTE, out outValue))
                {
                    cdAdquirente = queryString["" + (int)CAMPOS.CDADQUIRENTE];
                    queryStringRecebimentoParcela.Add("" + (int)GatewayRecebimentoParcela.CAMPOS.CDADQUIRENTE, cdAdquirente);
                    // queryStringTbRecebimentoTitulo.Add("" + (int)GatewayTbRecebimentoTitulo.CAMPOS.CDADQUIRENTE, cdAdquirente);
                }

                // SOMENTE AS PARCELAS QUE TEM TÍTULOS CONCILIADOS
                //queryStringRecebimentoParcela.Add("" + (int)GatewayRecebimentoParcela.CAMPOS.IDRECEBIMENTOTITULO, "0");

                // CONEXÃO
                SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["painel_taxservices_dbContext"].ConnectionString);

                try
                {
                    connection.Open();
                }
                catch
                {
                    throw new Exception("Não foi possível estabelecer conexão com a base de dados");
                }

                try
                {
                    #region OBTÉM A QUERY
                    //IQueryable<RecebimentoParcela> queryRecebimentoParcela = GatewayRecebimentoParcela.getQuery(_db, 0, (int)GatewayRecebimentoParcela.CAMPOS.DTARECEBIMENTO, 0, 0, 0, queryStringRecebimentoParcela);
                    SimpleDataBaseQuery dataBaseQuery = GatewayRecebimentoParcela.getQuery((int)GatewayRecebimentoParcela.CAMPOS.DTARECEBIMENTOEFETIVO, 0, queryStringRecebimentoParcela);

                    // RECEBIMENTO PARCELA
                    if (!dataBaseQuery.join.ContainsKey("INNER JOIN pos.Recebimento " + GatewayRecebimento.SIGLA_QUERY))
                    {
                        dataBaseQuery.join.Add("INNER JOIN pos.Recebimento " + GatewayRecebimento.SIGLA_QUERY, " ON " + GatewayRecebimento.SIGLA_QUERY + ".id = " + GatewayRecebimentoParcela.SIGLA_QUERY + ".idRecebimento");
                    }
                    if (!dataBaseQuery.join.ContainsKey("INNER JOIN card.tbBandeira " + GatewayTbBandeira.SIGLA_QUERY))
                    {
                        dataBaseQuery.join.Add("INNER JOIN card.tbBandeira " + GatewayTbBandeira.SIGLA_QUERY, " ON " + GatewayTbBandeira.SIGLA_QUERY + ".cdBandeira = " + GatewayRecebimento.SIGLA_QUERY + ".cdBandeira");
                    }
                    if (!dataBaseQuery.join.ContainsKey("INNER JOIN card.tbAdquirente " + GatewayTbAdquirente.SIGLA_QUERY))
                    {
                        dataBaseQuery.join.Add("INNER JOIN card.tbAdquirente " + GatewayTbAdquirente.SIGLA_QUERY, " ON " + GatewayTbAdquirente.SIGLA_QUERY + ".cdAdquirente = " + GatewayTbBandeira.SIGLA_QUERY + ".cdAdquirente");
                    }
                    if (!dataBaseQuery.join.ContainsKey("INNER JOIN cliente.empresa " + GatewayEmpresa.SIGLA_QUERY))
                    {
                        dataBaseQuery.join.Add("INNER JOIN cliente.empresa " + GatewayEmpresa.SIGLA_QUERY, " ON " + GatewayRecebimento.SIGLA_QUERY + ".cnpj = " + GatewayEmpresa.SIGLA_QUERY + ".nu_cnpj");
                    }
                    // JOINS para Título
                    if (!dataBaseQuery.join.ContainsKey("LEFT JOIN card.tbRecebimentoTitulo " + GatewayTbRecebimentoTitulo.SIGLA_QUERY))
                    {
                        dataBaseQuery.join.Add("LEFT JOIN card.tbRecebimentoTitulo " + GatewayTbRecebimentoTitulo.SIGLA_QUERY, " ON " + GatewayTbRecebimentoTitulo.SIGLA_QUERY + ".idRecebimentoTitulo = " + GatewayRecebimentoParcela.SIGLA_QUERY + ".idRecebimentoTitulo");
                    }
                    if (!dataBaseQuery.join.ContainsKey("LEFT JOIN cliente.empresa " + GatewayEmpresa.SIGLA_QUERY + "2"))
                    {
                        dataBaseQuery.join.Add("LEFT JOIN cliente.empresa " + GatewayEmpresa.SIGLA_QUERY + "2", " ON " + GatewayEmpresa.SIGLA_QUERY + "2.nu_cnpj = " + GatewayTbRecebimentoTitulo.SIGLA_QUERY + ".nrCNPJ");
                    }
                    //if (!dataBaseQuery.join.ContainsKey("LEFT JOIN card.tbAdquirente " + GatewayTbAdquirente.SIGLA_QUERY + "2"))
                    //    dataBaseQuery.join.Add("LEFT JOIN card.tbAdquirente " + GatewayTbAdquirente.SIGLA_QUERY + "2", " ON " + GatewayTbAdquirente.SIGLA_QUERY + "2.cdAdquirente = " + GatewayTbRecebimentoTitulo.SIGLA_QUERY + ".cdAdquirente");

                    // SELECT
                    dataBaseQuery.select = new string[] { // RECEBIMENTO PARCELA
                        "R_Id = " + GatewayRecebimento.SIGLA_QUERY + ".id",
                        "R_NumParcela = " + GatewayRecebimentoParcela.SIGLA_QUERY + ".numParcela",
                        "R_Nsu = " + GatewayRecebimento.SIGLA_QUERY + ".nsu",
                        "R_ValorLiquido = ISNULL(" + GatewayRecebimentoParcela.SIGLA_QUERY + ".valorParcelaLiquida, 0.0)",
                        "R_DataVenda = " + GatewayRecebimento.SIGLA_QUERY + ".dtaVenda",
                        "R_DataPrevista = " + GatewayRecebimentoParcela.SIGLA_QUERY + ".dtaRecebimento",
                        "R_DataEfetiva = " + GatewayRecebimentoParcela.SIGLA_QUERY + ".dtaRecebimentoEfetivo",
                        "R_Filial = UPPER(" + GatewayEmpresa.SIGLA_QUERY + ".ds_fantasia + CASE WHEN " + GatewayEmpresa.SIGLA_QUERY + ".filial IS NOT NULL THEN ' ' + " + GatewayEmpresa.SIGLA_QUERY + ".filial ELSE '' END)",
                        "R_Valor = " + GatewayRecebimentoParcela.SIGLA_QUERY + ".valorParcelaBruta",
                        "R_ValorVenda = " + GatewayRecebimento.SIGLA_QUERY + ".valorVendaBruta",
                        "R_Adquirente = " + GatewayTbAdquirente.SIGLA_QUERY + ".nmAdquirente",
                        // TÍTULO
                        "T_Id = " + GatewayTbRecebimentoTitulo.SIGLA_QUERY + ".idRecebimentoTitulo",
                        "T_NumParcela = " + GatewayTbRecebimentoTitulo.SIGLA_QUERY + ".nrParcela",
                        "T_Nsu = " + GatewayTbRecebimentoTitulo.SIGLA_QUERY + ".nrNSU",
                        "T_DataVenda = " + GatewayTbRecebimentoTitulo.SIGLA_QUERY + ".dtVenda",
                        "T_Data = " + GatewayTbRecebimentoTitulo.SIGLA_QUERY + ".dtTitulo",
                        "T_Filial = UPPER(" + GatewayEmpresa.SIGLA_QUERY + "2.ds_fantasia + CASE WHEN " + GatewayEmpresa.SIGLA_QUERY + "2.filial IS NOT NULL THEN ' ' + " + GatewayEmpresa.SIGLA_QUERY + "2.filial ELSE '' END)",
                        "T_Valor = " + GatewayTbRecebimentoTitulo.SIGLA_QUERY + ".vlParcela",
                        "T_ValorVenda = " + GatewayTbRecebimentoTitulo.SIGLA_QUERY + ".vlVenda",
                        //"T_Adquirente = " + GatewayTbAdquirente.SIGLA_QUERY + "2.nmAdquirente",
                        "T_Adquirente = (SELECT TOP 1 UPPER(nmAdquirente) FROM card.tbAdquirente (NOLOCK) WHERE cdAdquirente = CASE WHEN " + GatewayTbRecebimentoTitulo.SIGLA_QUERY + ".cdAdquirente IS NOT NULL THEN " + GatewayTbRecebimentoTitulo.SIGLA_QUERY + ".cdAdquirente ELSE " + GatewayTbRecebimentoTitulo.SIGLA_QUERY + ".cdAdquirenteNew) END)",
                    };
                    dataBaseQuery.orderby = new string[] { "CASE WHEN " + GatewayRecebimentoParcela.SIGLA_QUERY + ".idRecebimentoTitulo IS NOT NULL THEN 0 ELSE 1 END", // prioriza os que tem títulos
                                                           "CASE WHEN " + GatewayRecebimentoParcela.SIGLA_QUERY + ".dtaRecebimentoEfetivo IS NOT NULL THEN " + GatewayRecebimentoParcela.SIGLA_QUERY + ".dtaRecebimentoEfetivo ELSE " + GatewayRecebimentoParcela.SIGLA_QUERY + ".dtaRecebimento END",
                                                           GatewayTbAdquirente.SIGLA_QUERY + ".nmAdquirente",
                                                           GatewayRecebimento.SIGLA_QUERY + ".dtaVenda",
                                                           GatewayRecebimentoParcela.SIGLA_QUERY + ".valorParcelaBruta" };

                    // Tipo
                    if (queryString.TryGetValue("" + (int)CAMPOS.TIPO, out outValue))
                    {
                        Int32 tipo = Convert.ToInt32(queryString["" + (int)CAMPOS.TIPO]);
                        if (tipo == TIPO_FILIAL_DIFERENTE)
                        {   // Somente as parcelas que foram conciliados com um título de filial diferente
                            //queryRecebimentoParcela = queryRecebimentoParcela
                            //                        .Where(t => t.idRecebimentoTitulo != null && !t.Recebimento.cnpj.Equals(t.tbRecebimentoTitulo.nrCNPJ));
                            dataBaseQuery.AddWhereClause(GatewayRecebimentoParcela.SIGLA_QUERY + ".idRecebimentoTitulo IS NOT NULL AND " + GatewayRecebimento.SIGLA_QUERY + ".cnpj != " + GatewayTbRecebimentoTitulo.SIGLA_QUERY + ".nrCNPJ");
                        }
                        else if (tipo == TIPO_NAO_CONCILIADO)
                        {   // Somente as parcelas que não foram conciliadas
                            //queryRecebimentoParcela = queryRecebimentoParcela
                            //                        .Where(t => t.idRecebimentoTitulo == null);
                            dataBaseQuery.AddWhereClause(GatewayRecebimentoParcela.SIGLA_QUERY + ".idRecebimentoTitulo IS NULL");
                        }
                        else
                        {
                            throw new Exception("Filtro de tipo informado é inválido!");
                        }
                    }
                    else if (queryString.TryGetValue("" + (int)CAMPOS.NU_CNPJ_TITULO, out outValue))
                    {
                        string cnpjTitulo = queryString["" + (int)CAMPOS.NU_CNPJ_TITULO];
                        //queryRecebimentoParcela = queryRecebimentoParcela
                        //    // Somente as parcelas que foram conciliados com um título de filial igual ao cnpj enviado
                        //                            .Where(t => t.idRecebimentoTitulo != null && t.tbRecebimentoTitulo.nrCNPJ.Equals(cnpjTitulo));
                        dataBaseQuery.AddWhereClause(GatewayRecebimentoParcela.SIGLA_QUERY + ".idRecebimentoTitulo IS NOT NULL AND " + GatewayTbRecebimentoTitulo.SIGLA_QUERY + ".nrCNPJ = '" + cnpjTitulo + "'");
                    }

                    /*else
                     * {
                     *  queryRecebimentoParcela = queryRecebimentoParcela
                     *                              // Somente as parcelas que não foram conciliadas ou aquelas que foram conciliados com um título de filial diferente
                     *                              .Where(t => t.idRecebimentoTitulo == null || (t.idRecebimentoTitulo != null && !t.Recebimento.cnpj.Equals(t.tbRecebimentoTitulo.nrCNPJ)));
                     * }*/

                    dataBaseQuery.readUncommited = true;
                    #endregion

                    List <IDataRecord> resultado = DataBaseQueries.SqlQuery(dataBaseQuery.Script(), connection);

                    if (resultado != null && resultado.Count > 0)
                    {
                        CollectionRelatorioConciliacaoTitulos = resultado.Select(t => new
                        {
                            Titulo = t["T_Id"].Equals(DBNull.Value) ? null : new
                            {
                                Id         = Convert.ToInt32(t["T_Id"]),
                                NumParcela = Convert.ToInt32(t["T_NumParcela"]),
                                Nsu        = Convert.ToString(t["T_Nsu"].Equals(DBNull.Value) ? "" : t["T_Nsu"]),
                                DataVenda  = t["T_DataVenda"].Equals(DBNull.Value) ? (DateTime?)null : (DateTime)t["T_DataVenda"],
                                Valor      = Convert.ToDecimal(t["T_Valor"]),
                                Data       = (DateTime)t["T_Data"],
                                Filial     = Convert.ToString(t["T_Filial"]),
                                ValorVenda = Convert.ToDecimal(t["T_ValorVenda"].Equals(DBNull.Value) ? 0.0 : t["T_ValorVenda"]),
                            },
                            RecebimentoParcela = new
                            {
                                Id         = Convert.ToInt32(t["R_Id"]),
                                NumParcela = Convert.ToInt32(t["R_NumParcela"]),
                                Nsu        = Convert.ToString(t["R_Nsu"]),
                                //CodResumoVendas = recebimento.CodResumoVendas,
                                DataVenda    = (DateTime)t["R_DataVenda"],
                                Valor        = Convert.ToDecimal(t["R_Valor"]),
                                ValorLiquido = Convert.ToDecimal(t["R_ValorLiquido"]),
                                //Bandeira = recebimento.Bandeira,
                                Data        = (DateTime)t["R_DataPrevista"],
                                DataEfetiva = t["R_DataEfetiva"].Equals(DBNull.Value) ? (DateTime?)null : (DateTime)t["R_DataEfetiva"],
                                Filial      = Convert.ToString(t["R_Filial"]),
                                ValorVenda  = Convert.ToDecimal(t["R_ValorVenda"]),
                            },
                            Adquirente = Convert.ToString(t["R_Adquirente"]),
                        }).ToList <dynamic>();
                    }
                }
                catch (Exception e)
                {
                    if (e is DbEntityValidationException)
                    {
                        string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                        throw new Exception(erro.Equals("") ? "Falha ao listar recebimento parcela" : erro);
                    }
                    throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
                }
                finally
                {
                    try
                    {
                        connection.Close();
                    }
                    catch { }
                }

                //List<dynamic> rRecebimentoParcela = queryRecebimentoParcela
                //                                            .Select(t => new
                //                                            {
                //                                                idRecebimento = t.idRecebimento,
                //                                                dtaRecebimento = t.dtaRecebimentoEfetivo != null ? t.dtaRecebimentoEfetivo.Value : t.dtaRecebimento,
                //                                                filial = t.Recebimento.empresa.ds_fantasia.ToUpper() + (t.Recebimento.empresa.filial != null ? " " + t.Recebimento.empresa.filial.ToUpper() : ""),
                //                                                adquirente = t.Recebimento.tbBandeira.tbAdquirente.nmAdquirente.ToUpper(),
                //                                                //bandeira = t.Recebimento.tbBandeira.dsBandeira,
                //                                                valorBruto = t.valorParcelaBruta,
                //                                                valorLiquido = t.valorParcelaLiquida != null ? t.valorParcelaLiquida.Value : new decimal(0.0),
                //                                                valorVenda = t.Recebimento.valorVendaBruta,
                //                                                idRecebimentoTitulo = t.idRecebimentoTitulo,
                //                                                dtaVenda = t.Recebimento.dtaVenda,
                //                                                nsu = t.Recebimento.nsu,
                //                                                numParcela = t.numParcela,
                //                                                //codResumoVenda = t.Recebimento.codResumoVenda,
                //                                            }).OrderBy(t => t.filial)
                //                                              // prioriza os conciliados
                //                                              .ThenByDescending(t => t.idRecebimentoTitulo.HasValue)
                //                                              .ThenBy(t => t.dtaRecebimento)
                //                                              .ThenBy(t => t.adquirente)
                //                                              .ThenBy(t => t.dtaVenda.Year)
                //                                              .ThenBy(t => t.dtaVenda.Month)
                //                                              .ThenBy(t => t.dtaVenda.Day)
                //                                              .ThenBy(t => t.valorBruto)
                //                                              .ToList<dynamic>();

                // TOTAL DE REGISTROS
                //retorno.TotalDeRegistros = rRecebimentoParcela.Count;

                //// PAGINAÇÃO
                //int skipRows = (pageNumber - 1) * pageSize;
                //if (rRecebimentoParcela.Count > pageSize && pageNumber > 0 && pageSize > 0)
                //    rRecebimentoParcela = rRecebimentoParcela.Skip(skipRows).Take(pageSize).ToList<dynamic>();
                //else
                //    pageNumber = 1;
                retorno.TotalDeRegistros = CollectionRelatorioConciliacaoTitulos.Count;

                // TOTAL
                retorno.Totais = new Dictionary <string, object>();
                retorno.Totais.Add("valorTotalBruto", CollectionRelatorioConciliacaoTitulos.Select(r => r.RecebimentoParcela.Valor).Cast <decimal>().Sum());
                retorno.Totais.Add("valorTotalERP", CollectionRelatorioConciliacaoTitulos.Where(r => r.Titulo != null).Select(r => r.Titulo.Valor).Cast <decimal>().Sum());
                List <dynamic> filiais = CollectionRelatorioConciliacaoTitulos.Where(t => t.Titulo != null)
                                         .GroupBy(t => t.Titulo.Filial)
                                         .OrderBy(t => t.Key)
                                         .Select(t => new
                {
                    filial   = t.Key,
                    valor    = t.Select(x => x.RecebimentoParcela.Valor).Cast <decimal>().Sum(),
                    valorERP = t.Select(x => x.Titulo.Valor).Cast <decimal>().Sum()
                }).ToList <dynamic>();

                if (filiais.Count > 0)
                {
                    foreach (var filial in filiais)
                    {
                        retorno.Totais.Add("(valorTotalBruto) " + filial.filial, filial.valor);
                        retorno.Totais.Add("(valorTotalERP) " + filial.filial, filial.valorERP);
                    }
                }

                // PAGINAÇÃO
                int skipRows = (pageNumber - 1) * pageSize;
                if (CollectionRelatorioConciliacaoTitulos.Count > pageSize && pageNumber > 0 && pageSize > 0)
                {
                    CollectionRelatorioConciliacaoTitulos = CollectionRelatorioConciliacaoTitulos.Skip(skipRows).Take(pageSize).ToList <dynamic>();
                }
                else
                {
                    pageNumber = 1;
                }


                //foreach (var recebParcela in rRecebimentoParcela)
                //{
                //    ConciliacaoTitulos recebimento = new ConciliacaoTitulos
                //    {
                //        Tipo = GatewayConciliacaoTitulos.TIPO_RECEBIMENTO, // recebimento
                //        Id = recebParcela.idRecebimento,
                //        NumParcela = recebParcela.numParcela,
                //        Nsu = recebParcela.nsu,
                //        ValorLiquido = /*decimal.Round(*/recebParcela.valorLiquido/*, 2)*/,
                //        //CodResumoVendas = recebParcela.codResumoVenda,
                //        //Bandeira = recebParcela.bandeira,
                //        DataVenda = recebParcela.dtaVenda,
                //        Data = recebParcela.dtaRecebimento,
                //        Filial = recebParcela.filial,
                //        Valor = /*decimal.Round(*/recebParcela.valorBruto/*, 2)*/,
                //        ValorVenda = /*decimal.Round(*/recebParcela.valorVenda/*, 2)*/,
                //        Adquirente = recebParcela.adquirente,
                //    };

                //    if (recebParcela.idRecebimentoTitulo != null)
                //    {
                //        // PARCELA CONCILIADA
                //        Int32 idRecebimentoTitulo = recebParcela.idRecebimentoTitulo;

                //        ConciliacaoTitulos titulo = _db.tbRecebimentoTitulos
                //                                                .Where(e => e.idRecebimentoTitulo == idRecebimentoTitulo)
                //                                                .Select(e => new ConciliacaoTitulos
                //                                                {
                //                                                    Tipo = GatewayConciliacaoTitulos.TIPO_TITULO, // título
                //                                                    Id = e.idRecebimentoTitulo,
                //                                                    NumParcela = e.nrParcela,
                //                                                    Nsu = e.nrNSU,
                //                                                    //Bandeira = e.dsBandeira.ToUpper(),
                //                                                    DataVenda = e.dtVenda,
                //                                                    Data = e.dtTitulo,
                //                                                    Filial = e.empresa.ds_fantasia.ToUpper() + (e.empresa.filial != null ? " " + e.empresa.filial.ToUpper() : ""),
                //                                                    Valor = e.vlParcela,
                //                                                    ValorVenda = e.vlVenda,
                //                                                    Adquirente = e.tbAdquirente.nmAdquirente.ToUpper(),
                //                                                }).FirstOrDefault<ConciliacaoTitulos>();

                //        if (titulo == null)
                //            continue; // falha!

                //        // Adiciona
                //        CollectionRelatorioConciliacaoTitulos.Add(new
                //        {
                //            Titulo = new
                //            {
                //                Id = titulo.Id,
                //                NumParcela = titulo.NumParcela,
                //                Nsu = titulo.Nsu,
                //                DataVenda = titulo.DataVenda,
                //                Valor = titulo.Valor,
                //                //Bandeira = titulo.Bandeira,
                //                Data = titulo.Data,
                //                Filial = titulo.Filial,
                //                ValorVenda = titulo.ValorVenda,
                //            },
                //            RecebimentoParcela = new
                //            {
                //                Id = recebimento.Id,
                //                NumParcela = recebimento.NumParcela,
                //                Nsu = recebimento.Nsu,
                //                //CodResumoVendas = recebimento.CodResumoVendas,
                //                DataVenda = recebimento.DataVenda,
                //                Valor = recebimento.Valor,
                //                ValorLiquido = recebimento.ValorLiquido,
                //                //Bandeira = recebimento.Bandeira,
                //                Data = recebimento.Data,
                //                Filial = recebimento.Filial,
                //                ValorVenda = recebimento.ValorVenda,
                //            },
                //            Adquirente = recebimento.Adquirente,
                //        });
                //    }
                //    else
                //    {
                //        // PARCELA NÃO CONCILIADA
                //        CollectionRelatorioConciliacaoTitulos.Add(new
                //        {
                //            Titulo = (string)null,
                //            RecebimentoParcela = new
                //            {
                //                Id = recebimento.Id,
                //                NumParcela = recebimento.NumParcela,
                //                Nsu = recebimento.Nsu,
                //                //CodResumoVendas = recebimento.CodResumoVendas,
                //                DataVenda = recebimento.DataVenda,
                //                Valor = recebimento.Valor,
                //                ValorLiquido = recebimento.ValorLiquido,
                //                //Bandeira = recebimento.Bandeira,
                //                Data = recebimento.Data,
                //                Filial = recebimento.Filial,
                //                ValorVenda = recebimento.ValorVenda,
                //            },
                //            Adquirente = recebimento.Adquirente,
                //        });
                //    }
                //}

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

                retorno.Registros = CollectionRelatorioConciliacaoTitulos;

                return(retorno);
            }
            catch (Exception e)
            {
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao listar adquirente" : 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();
                }
            }
        }
Beispiel #2
0
        /// <summary>
        /// Retorna TbRecebimentoTitulo/TbRecebimentoTitulo
        /// </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> CollectionTbRecebimentoTitulo = 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> titulosConciliados = new List <int>();

                if (colecao == 2 || colecao == 3)
                {
                    // Obtém totais
                    retorno.Totais = new Dictionary <string, object>();
                    retorno.Totais.Add("valorTotal", retorno.TotalDeRegistros > 0 ? query.Select(e => e.vlParcela).Cast <decimal>().Sum() : new decimal(0.0));
                    retorno.Totais.Add("totalBaixados", retorno.TotalDeRegistros > 0 ? query.Where(e => e.dtBaixaERP != null).Count() : 0);
                    if (colecao == 3)
                    {
                        //retorno.Totais.Add("totalConciliados", retorno.TotalDeRegistros > 0 ? query.Where(e => e.RecebimentoParcelas.Count > 0).Count() : 0);

                        if (retorno.TotalDeRegistros == 0)
                        {
                            retorno.Totais.Add("totalConciliados", 0);
                        }
                        else
                        {
                            titulosConciliados = _db.Database.SqlQuery <int>("SELECT DISTINCT P.idRecebimentoTitulo" +
                                                                             " FROM pos.RecebimentoParcela P (NOLOCK)" +
                                                                             " WHERE P.idRecebimentoTitulo IN (" + string.Join(", ", query.Select(e => e.idRecebimentoTitulo)) + ")"
                                                                             ).ToList();

                            retorno.Totais.Add("totalConciliados", titulosConciliados.Count);
                        }

                        query = query.OrderBy(e => e.dtTitulo).ThenBy(e => e.dtVenda).ThenBy(e => e.empresa.ds_fantasia).ThenBy(e => e.vlParcela).ThenBy(e => e.nrNSU);
                    }
                    else
                    {
                        query = query.OrderBy(e => e.empresa.ds_fantasia).ThenBy(e => e.dtTitulo).ThenBy(e => e.dtVenda).ThenBy(e => e.vlParcela).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)
                {
                    CollectionTbRecebimentoTitulo = query.Select(e => new
                    {
                        idRecebimentoTitulo = e.idRecebimentoTitulo,
                        nrCNPJ  = e.nrCNPJ,
                        nrNSU   = e.nrNSU,
                        dtVenda = e.dtVenda,
                        //cdAdquirente = e.cdAdquirente,
                        cdAdquirente = e.cdAdquirente != null ? e.cdAdquirente : e.cdAdquirenteNew,
                        dsBandeira   = e.dsBandeira,
                        vlVenda      = e.vlVenda,
                        qtParcelas   = e.qtParcelas,
                        dtTitulo     = e.dtTitulo,
                        vlParcela    = e.vlParcela,
                        nrParcela    = e.nrParcela,
                        cdERP        = e.cdERP,
                        dtBaixaERP   = e.dtBaixaERP,
                        cdSacado     = e.cdSacado,
                    }).ToList <dynamic>();
                }
                else if (colecao == 0)
                {
                    CollectionTbRecebimentoTitulo = query.Select(e => new
                    {
                        idRecebimentoTitulo = e.idRecebimentoTitulo,
                        nrCNPJ  = e.nrCNPJ,
                        nrNSU   = e.nrNSU,
                        dtVenda = e.dtVenda,
                        //cdAdquirente = e.cdAdquirente,
                        cdAdquirente = e.cdAdquirente != null ? e.cdAdquirente : e.cdAdquirenteNew,
                        dsBandeira   = e.dsBandeira,
                        vlVenda      = e.vlVenda,
                        qtParcelas   = e.qtParcelas,
                        dtTitulo     = e.dtTitulo,
                        vlParcela    = e.vlParcela,
                        nrParcela    = e.nrParcela,
                        cdERP        = e.cdERP,
                        dtBaixaERP   = e.dtBaixaERP,
                        cdSacado     = e.cdSacado,
                    }).ToList <dynamic>();
                }
                else if (colecao == 2) // PORTAL: Consulta Títulos ERP (Conciliação Bancária)
                {
                    CollectionTbRecebimentoTitulo = query.Select(e => new
                    {
                        Id         = e.idRecebimentoTitulo,
                        NumParcela = e.nrParcela,
                        Filial     = e.empresa.ds_fantasia.ToUpper() + (e.empresa.filial != null ? " " + e.empresa.filial.ToUpper() : ""),
                        Documento  = e.nrNSU,
                        DataVenda  = e.dtVenda,
                        //Adquirente = e.tbAdquirente.dsAdquirente.ToUpper(),
                        Adquirente   = _db.tbAdquirentes.Where(t => t.cdAdquirente == (e.cdAdquirente != null ? e.cdAdquirente : e.cdAdquirenteNew)).Select(t => t.nmAdquirente.ToUpper()).FirstOrDefault(),
                        Bandeira     = e.dsBandeira,
                        DataPrevista = e.dtTitulo,
                        Valor        = e.vlParcela,
                        Baixado      = e.dtBaixaERP != null,
                    }).ToList <dynamic>();

                    //retorno.Totais = new Dictionary<string, object>();
                    //retorno.Totais.Add("valorTotal", retorno.TotalDeRegistros > 0 ? CollectionTbRecebimentoTitulo.Select(e => e.Valor).Cast<decimal>().Sum() : new decimal(0.0));
                    //retorno.Totais.Add("totalBaixados", retorno.TotalDeRegistros > 0 ? CollectionTbRecebimentoTitulo.Where(e => e.Baixado == true).Count() : 0);
                }
                else if (colecao == 3) // PORTAL: Consulta Títulos ERP
                {
                    CollectionTbRecebimentoTitulo = query.Select(e => new
                    {
                        idRecebimentoTitulo = e.idRecebimentoTitulo,
                        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 != null ? e.cdAdquirente : e.cdAdquirenteNew)).Select(a => new
                        {
                            a.cdAdquirente,
                            a.nmAdquirente
                        })
                                       .FirstOrDefault(),
                        dsBandeira = e.dsBandeira,
                        vlVenda    = e.vlVenda,
                        qtParcelas = e.qtParcelas,
                        dtTitulo   = e.dtTitulo,
                        vlParcela  = e.vlParcela,
                        nrParcela  = e.nrParcela,
                        cdERP      = e.cdERP,
                        dtBaixaERP = e.dtBaixaERP,
                        cdSacado   = e.cdSacado,
                        //conciliado = e.RecebimentoParcelas.Count > 0
                        conciliado = titulosConciliados.Contains(e.idRecebimentoTitulo)
                    }).ToList <dynamic>();
                }

                transaction.Commit();

                retorno.Registros = CollectionTbRecebimentoTitulo;

                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 títulos" : 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();
                }
            }
        }
Beispiel #3
0
        /// <summary>
        /// Retorna TbContaCorrente_tbLoginAdquirenteEmpresa/TbContaCorrente_tbLoginAdquirenteEmpresa
        /// </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> CollectionTbContaCorrente_tbLoginAdquirenteEmpresa = new List <dynamic>();
                Retorno        retorno = new Retorno();

                // Implementar o filtro por Grupo apartir do TOKEN do Usuário
                string outValue = null;
                Int32  IdGrupo  = 0;
                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_CNPJ, out outValue))
                    {
                        queryString["" + (int)CAMPOS.NU_CNPJ] = CnpjEmpresa;
                    }
                    else
                    {
                        queryString.Add("" + (int)CAMPOS.NU_CNPJ, CnpjEmpresa);
                    }
                }

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

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


                if (colecao != 5)
                {
                    // 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)
                {
                    CollectionTbContaCorrente_tbLoginAdquirenteEmpresa = query.Select(e => new
                    {
                        cdContaCorrente          = e.cdContaCorrente,
                        cdLoginAdquirenteEmpresa = e.cdLoginAdquirenteEmpresa,
                        dtInicio = e.dtInicio,
                        dtFim    = e.dtFim,
                    }).ToList <dynamic>();
                }
                else if (colecao == 0)
                {
                    CollectionTbContaCorrente_tbLoginAdquirenteEmpresa = query.Select(e => new
                    {
                        cdContaCorrente          = e.cdContaCorrente,
                        cdLoginAdquirenteEmpresa = e.cdLoginAdquirenteEmpresa,
                        dtInicio = e.dtInicio,
                        dtFim    = e.dtFim,
                    }).ToList <dynamic>();
                }
                else if (colecao == 2) // [WEB] Vigência da Conta Corrente
                {
                    CollectionTbContaCorrente_tbLoginAdquirenteEmpresa = query.Select(e => new
                    {
                        dtInicio = e.dtInicio,
                        dtFim    = e.dtFim,
                        cdLoginAdquirenteEmpresa = e.tbLoginAdquirenteEmpresa.cdLoginAdquirenteEmpresa,
                        adquirente = new
                        {
                            cdAdquirente = e.tbLoginAdquirenteEmpresa.tbAdquirente.cdAdquirente,
                            nmAdquirente = e.tbLoginAdquirenteEmpresa.tbAdquirente.nmAdquirente,
                            dsAdquirente = e.tbLoginAdquirenteEmpresa.tbAdquirente.dsAdquirente,
                            stAdquirente = e.tbLoginAdquirenteEmpresa.tbAdquirente.stAdquirente,
                        },
                        empresa = new
                        {
                            nu_cnpj     = e.tbLoginAdquirenteEmpresa.empresa.nu_cnpj,
                            ds_fantasia = e.tbLoginAdquirenteEmpresa.empresa.ds_fantasia,
                            filial      = e.tbLoginAdquirenteEmpresa.empresa.filial
                        },
                        stLoginAdquirente = e.tbLoginAdquirenteEmpresa.stLoginAdquirente,
                        //stLoginAdquirenteEmpresa = l.tbLoginAdquirenteEmpresa.stLoginAdquirenteEmpresa // controle de bruno
                    }).ToList <dynamic>();
                }
                else if (colecao == 3) // [WEB] Filiais
                {
                    CollectionTbContaCorrente_tbLoginAdquirenteEmpresa = query
                                                                         .Where(e => e.tbLoginAdquirenteEmpresa.empresa.fl_ativo == 1)
                                                                         .GroupBy(e => e.tbLoginAdquirenteEmpresa.empresa.nu_cnpj)
                                                                         .Select(e => new
                    {
                        nu_cnpj     = e.Key,
                        ds_fantasia = e.Select(f => f.tbLoginAdquirenteEmpresa.empresa.ds_fantasia).FirstOrDefault(),
                        filial      = e.Select(f => f.tbLoginAdquirenteEmpresa.empresa.filial).FirstOrDefault(),
                        adquirentes = e.Select(f => new
                        {
                            cdAdquirente = f.tbLoginAdquirenteEmpresa.tbAdquirente.cdAdquirente,
                            nmAdquirente = f.tbLoginAdquirenteEmpresa.tbAdquirente.nmAdquirente,
                            stAdquirente = f.tbLoginAdquirenteEmpresa.tbAdquirente.stAdquirente,
                        }).OrderBy(f => f.nmAdquirente).ToList <dynamic>(),
                    }).OrderBy(e => e.ds_fantasia).ThenBy(e => e.filial).ToList <dynamic>();
                }
                else if (colecao == 4) // [WEB] Adquirentes
                {
                    CollectionTbContaCorrente_tbLoginAdquirenteEmpresa = query
                                                                         .Where(e => e.tbLoginAdquirenteEmpresa.tbAdquirente.stAdquirente == 1)
                                                                         .GroupBy(e => e.tbLoginAdquirenteEmpresa.tbAdquirente.cdAdquirente)
                                                                         .Select(e => new
                    {
                        cdAdquirente = e.Key,
                        nmAdquirente = e.Select(f => f.tbLoginAdquirenteEmpresa.tbAdquirente.nmAdquirente).FirstOrDefault(),
                        stAdquirente = e.Select(f => f.tbLoginAdquirenteEmpresa.tbAdquirente.stAdquirente).FirstOrDefault(),
                    }).OrderBy(e => e.nmAdquirente).ToList <dynamic>();
                }
                else if (colecao == 5) // [WEB] Relação adquirente-filial por conta
                {
                    List <dynamic> tbLoginAdquirenteEmpresas = query
                                                               .Where(e => e.tbLoginAdquirenteEmpresa.empresa.fl_ativo == 1)
                                                               .Select(e => new
                    {
                        tbContaCorrente = new
                        {
                            e.tbContaCorrente.cdContaCorrente,
                            //e.tbContaCorrente.cdBanco,
                            banco = new { Codigo = e.tbContaCorrente.cdBanco, NomeExtenso = "" },
                            e.tbContaCorrente.nrAgencia,
                            e.tbContaCorrente.nrConta
                        },
                        empresa = new
                        {
                            e.tbLoginAdquirenteEmpresa.empresa.nu_cnpj,
                            e.tbLoginAdquirenteEmpresa.empresa.ds_fantasia,
                            e.tbLoginAdquirenteEmpresa.empresa.filial
                        },
                        tbAdquirente = new
                        {
                            e.tbLoginAdquirenteEmpresa.tbAdquirente.cdAdquirente,
                            e.tbLoginAdquirenteEmpresa.tbAdquirente.nmAdquirente
                        },
                        cdEstabelecimento         = e.tbLoginAdquirenteEmpresa.cdEstabelecimento,
                        cdEstabelecimentoConsulta = e.tbLoginAdquirenteEmpresa.cdEstabelecimentoConsulta,
                        status   = e.tbLoginAdquirenteEmpresa.stLoginAdquirente,
                        dtInicio = e.dtInicio,
                        dtFim    = e.dtFim
                    })
                                                               .OrderBy(e => e.empresa.nu_cnpj)
                                                               .ThenBy(e => e.tbAdquirente.nmAdquirente)
                                                               .ThenBy(e => e.tbContaCorrente.banco.Codigo)
                                                               .ThenBy(e => e.tbContaCorrente.nrAgencia)
                                                               .ThenBy(e => e.tbContaCorrente.nrConta)
                                                               .ToList <dynamic>();

                    // PAGINAÇÃO
                    int skipRows = (pageNumber - 1) * pageSize;
                    if (tbLoginAdquirenteEmpresas.Count > pageSize && pageNumber > 0 && pageSize > 0)
                    {
                        tbLoginAdquirenteEmpresas = tbLoginAdquirenteEmpresas.Skip(skipRows).Take(pageSize).ToList <dynamic>();
                    }
                    else
                    {
                        pageNumber = 1;
                    }

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

                    // Após transformar em lista (isto é, trazer para a memória), atualiza o valor do NomeExtenso associado ao banco
                    foreach (var tbLoginAdquirenteEmpresa in tbLoginAdquirenteEmpresas)
                    {
                        CollectionTbContaCorrente_tbLoginAdquirenteEmpresa.Add(new
                        {
                            tbContaCorrente = new {
                                cdContaCorrente = tbLoginAdquirenteEmpresa.tbContaCorrente.cdContaCorrente,
                                //e.tbContaCorrente.cdBanco,
                                banco     = new { Codigo = tbLoginAdquirenteEmpresa.tbContaCorrente.banco.Codigo, NomeExtenso = GatewayBancos.Get(tbLoginAdquirenteEmpresa.tbContaCorrente.banco.Codigo) },
                                nrAgencia = tbLoginAdquirenteEmpresa.tbContaCorrente.nrAgencia,
                                nrConta   = tbLoginAdquirenteEmpresa.tbContaCorrente.nrConta,
                            },
                            empresa                   = tbLoginAdquirenteEmpresa.empresa,
                            tbAdquirente              = tbLoginAdquirenteEmpresa.tbAdquirente,
                            cdEstabelecimento         = tbLoginAdquirenteEmpresa.cdEstabelecimento,
                            cdEstabelecimentoConsulta = tbLoginAdquirenteEmpresa.cdEstabelecimentoConsulta,
                            status   = tbLoginAdquirenteEmpresa.status,
                            dtInicio = tbLoginAdquirenteEmpresa.dtInicio,
                            dtFim    = tbLoginAdquirenteEmpresa.dtFim
                        });
                    }
                }

                transaction.Commit();

                retorno.Registros = CollectionTbContaCorrente_tbLoginAdquirenteEmpresa;

                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 adquirente empresa" : 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();
                }
            }
        }
        public void initList()
        {
            // Erro!
            if (filtro.Token == null || !Permissoes.Autenticado(filtro.Token))
            {
                list = null;
                return;
            }

            // YYYYMM
            int ano = filtro.Data.Length >= 4 ? Convert.ToInt32(filtro.Data.Substring(0, 4)) : DateTime.Now.Year;
            int mes = filtro.Data.Length >= 6 ? Convert.ToInt32(filtro.Data.Substring(4, 2)) : DateTime.Now.Month;

            script = @"
                        SELECT
                        pos.LogExecution.id,
                        pos.LogExecution.dtaFiltroTransacoes,
                        pos.LogExecution.statusExecution,
                        pos.LogExecution.idLoginOperadora,
                        pos.LogExecution.dtaExecucaoFim,
                        pos.LogExecution.dtaExecucaoProxima,
                        pos.LoginOperadora.status,
                        cliente.grupo_empresa.id_grupo,
                        cliente.grupo_empresa.ds_nome,
                        cliente.empresa.nu_cnpj,
                        cliente.empresa.ds_fantasia,
                        cliente.empresa.filial,
                        pos.Operadora.id AS idOperadora,
                        pos.Operadora.nmOperadora

                        FROM
                        pos.LogExecution
                        INNER JOIN pos.LoginOperadora ON pos.LogExecution.idLoginOperadora = pos.LoginOperadora.id
                        INNER JOIN cliente.empresa ON pos.LoginOperadora.cnpj = cliente.empresa.nu_cnpj
                        INNER JOIN pos.Operadora ON pos.LoginOperadora.idOperadora = pos.Operadora.id
                        INNER JOIN cliente.grupo_empresa ON pos.LoginOperadora.idGrupo = cliente.grupo_empresa.id_grupo                        

                        WHERE YEAR(pos.LogExecution.dtaFiltroTransacoes) = " + ano +
                     @" AND MONTH(pos.LogExecution.dtaFiltroTransacoes) = " + mes;

            // Usuário está amarrado a um grupo empresa?
            Int32 IdGrupo = Permissoes.GetIdGrupo(filtro.Token);

            if (IdGrupo != 0)
            {
                script += @" AND cliente.grupo_empresa.id_grupo = " + IdGrupo;
            }
            else if (Permissoes.isAtosRoleVendedor(filtro.Token))
            {
                // Perfil Comercial tem uma carteira de clientes específica
                List <Int32> listaIdsGruposEmpresas = Permissoes.GetIdsGruposEmpresasVendedor(filtro.Token);
                if (listaIdsGruposEmpresas.Count > 0)
                {
                    script += @" AND (cliente.grupo_empresa.id_grupo = " + listaIdsGruposEmpresas[0];
                    for (int k = 1; k < listaIdsGruposEmpresas.Count; k++)
                    {
                        script += @" OR cliente.grupo_empresa.id_grupo = " + listaIdsGruposEmpresas[k];
                    }
                    script += @")";
                }
            }
            else if (filtro.IdGrupo > 0)
            {
                script += @" AND cliente.grupo_empresa.id_grupo = " + filtro.IdGrupo;
            }

            // Usuário está amarrado a uma filial?
            string CnpjEmpresa = Permissoes.GetCNPJEmpresa(filtro.Token);

            if (!CnpjEmpresa.Equals(""))
            {
                script += @" AND cliente.empresa.nu_cnpj = '" + CnpjEmpresa + @"'";
            }
            else if (!filtro.NuCnpj.Equals(""))
            {
                script += @" AND cliente.empresa.nu_cnpj = '" + filtro.NuCnpj + @"'";
            }

            if (filtro.CdAdquirente > 0)
            {
                script += @" AND pos.Operadora.id = " + filtro.CdAdquirente;
            }

            // Filtro de status é feito no momento do agrupamento!

            semaforoExecucao.WaitOne();

            try
            {
                if (connection == null)
                {
                    connection = new SqlConnection(ConfigurationManager.ConnectionStrings["painel_taxservices_dbContext"].ConnectionString);
                }

                // Obtém novo comando
                command = new SqlCommand(script, connection);

                // Registra evento de notificação
                registraEventoNotificacao();


                if (!connection.State.Equals(ConnectionState.Open))
                {
                    connection.Open();
                }

                using (var reader = command.ExecuteReader())
                {
                    //if (list != null) list.Clear();

                    //semaforo.WaitOne();

                    list = reader.Cast <IDataRecord>()
                           .Select(e => new MonitorCargas
                    {
                        id = Convert.ToInt32(e["id"]),
                        dtaFiltroTransacoes = (DateTime)e["dtaFiltroTransacoes"],
                        statusExecution     = Convert.ToString(e["statusExecution"]),
                        dtaExecucaoFim      = e["dtaExecucaoFim"].Equals(DBNull.Value) ? (DateTime?)null : (DateTime)e["dtaExecucaoFim"],
                        dtaExecucaoProxima  = e["dtaExecucaoProxima"].Equals(DBNull.Value) ? (DateTime?)null : (DateTime)e["dtaExecucaoProxima"],
                        loginOperadora      = new LoginOperadoraMonitor
                        {
                            id     = Convert.ToInt32(e["idLoginOperadora"]),
                            status = Convert.ToBoolean(e["status"]),
                        },
                        grupoempresa = new GrupoEmpresaMonitor
                        {
                            id_grupo = Convert.ToInt32(e["id_grupo"]),
                            ds_nome  = Convert.ToString(e["ds_nome"]),
                        },
                        empresa = new EmpresaMonitor
                        {
                            nu_cnpj     = Convert.ToString(e["nu_cnpj"]),
                            ds_fantasia = Convert.ToString(e["ds_fantasia"]),
                            filial      = Convert.ToString(e["filial"]),
                        },
                        operadora = new OperadoraMonitor
                        {
                            id          = Convert.ToInt32(e["idOperadora"]),
                            nmOperadora = Convert.ToString(e["nmOperadora"])
                        }
                    }).ToList <MonitorCargas>();

                    alterouFiltro = false;

                    //semaforo.Release(1);
                }
            }
            catch (Exception e)
            {
            }

            semaforoExecucao.Release(1);
        }
Beispiel #5
0
        /// <summary>
        /// Retorna Operadora/Operadora
        /// </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
            {
                // Implementar o filtro por Grupo apartir do TOKEN do Usuário
                string outValue = null;
                Int32  IdGrupo  = Permissoes.GetIdGrupo(token);
                if (IdGrupo != 0)
                {
                    if (queryString.TryGetValue("" + (int)CAMPOS.IDGRUPOEMPRESA, out outValue))
                    {
                        queryString["" + (int)CAMPOS.IDGRUPOEMPRESA] = IdGrupo.ToString();
                    }
                    else
                    {
                        queryString.Add("" + (int)CAMPOS.IDGRUPOEMPRESA, IdGrupo.ToString());
                    }
                }
                string CnpjEmpresa = Permissoes.GetCNPJEmpresa(token);
                if (!CnpjEmpresa.Equals(""))
                {
                    if (queryString.TryGetValue("" + (int)CAMPOS.NU_CNPJ, out outValue))
                    {
                        queryString["" + (int)CAMPOS.NU_CNPJ] = CnpjEmpresa;
                    }
                    else
                    {
                        queryString.Add("" + (int)CAMPOS.NU_CNPJ, CnpjEmpresa);
                    }
                }

                //DECLARAÇÕES
                List <dynamic> CollectionOperadora = 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)
                {
                    CollectionOperadora = query.Select(e => new
                    {
                        id             = e.id,
                        nmOperadora    = e.nmOperadora,
                        idGrupoEmpresa = e.idGrupoEmpresa,
                    }).ToList <dynamic>();
                }
                else if (colecao == 0)
                {
                    CollectionOperadora = query.Select(e => new
                    {
                        id             = e.id,
                        nmOperadora    = e.nmOperadora,
                        idGrupoEmpresa = e.idGrupoEmpresa,
                    }).ToList <dynamic>();
                }

                retorno.Registros = CollectionOperadora;

                return(retorno);
            }
            catch (Exception e)
            {
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao listar operadora" : erro);
                }
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
            }
        }
Beispiel #6
0
        /// <summary>
        /// Retorna LogAcesso/LogAcesso
        /// </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> CollectionLogAcesso = new List <dynamic>();
                Retorno        retorno             = new Retorno();
                string         outValue            = null;

                Int32 IdGrupo = Permissoes.GetIdGrupo(token);
                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);
                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);
                    }
                }

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

                // Restringe consulta pelo perfil do usuário logado
                Int32 RoleLevelMin   = Permissoes.GetRoleLevelMin(token);
                bool  isAtosVendedor = Permissoes.isAtosRoleVendedor(token);
                if (IdGrupo == 0 && isAtosVendedor)
                {
                    // Perfil Comercial tem uma carteira de clientes específica
                    List <Int32> listaIdsGruposEmpresas = Permissoes.GetIdsGruposEmpresasVendedor(token);
                    query = query.Where(e => e.webpages_Users.webpages_Membership.webpages_UsersInRoles.FirstOrDefault().webpages_Roles.RoleLevel >= RoleLevelMin &&
                                        e.webpages_Users.id_grupo != null && listaIdsGruposEmpresas.Contains(e.webpages_Users.id_grupo ?? -1)).AsQueryable <LogAcesso1>();
                }
                else if (Permissoes.isAtosRole(token) && !isAtosVendedor)
                {
                    // 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_Users.webpages_Membership.webpages_UsersInRoles.ToList <dynamic>().Count == 0 || e.webpages_Users.webpages_Membership.webpages_UsersInRoles.FirstOrDefault().webpages_Roles.RoleLevel >= RoleLevelMin).AsQueryable <LogAcesso1>();
                }
                else
                {
                    // Só exibe os usuários de RoleLevelMin
                    query = query.Where(e => e.webpages_Users.webpages_Membership.webpages_UsersInRoles.FirstOrDefault().webpages_Roles.RoleLevel >= RoleLevelMin).AsQueryable <LogAcesso1>();
                }

                // 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)
                {
                    CollectionLogAcesso = query.Select(e => new
                    {
                        idUsers      = e.idUsers,
                        idController = e.idController,
                        idMethod     = e.idMethod,
                        dtAcesso     = e.dtAcesso,
                        flMobile     = e.flMobile,
                        dsUserAgent  = e.dsUserAgent
                    }).ToList <dynamic>();
                }
                else if (colecao == 0)
                {
                    CollectionLogAcesso = query.Select(e => new
                    {
                        idUsers      = e.idUsers,
                        idController = e.idController,
                        idMethod     = e.idMethod,
                        dtAcesso     = e.dtAcesso,
                        flMobile     = e.flMobile,
                        dsUserAgent  = e.dsUserAgent
                    }).ToList <dynamic>();
                }
                else if (colecao == 2)
                {
                    CollectionLogAcesso = query.Select(e => new
                    {
                        webpagesusers = new
                        {
                            id_users = e.idUsers,
                            ds_login = e.webpages_Users.ds_login
                        },
                        controller = new
                        {
                            id_controller = e.idController,
                            ds_controller = e.webpages_Controllers != null && e.idController > 50 ?
                                            (e.webpages_Controllers.id_subController != null && e.webpages_Controllers.webpages_Controllers2.id_subController != null ?
                                             e.webpages_Controllers.webpages_Controllers2.webpages_Controllers2.ds_controller + " > " : "") +
                                            (e.webpages_Controllers.id_subController != null ?
                                             e.webpages_Controllers.webpages_Controllers2.ds_controller + " > " : "") +
                                            e.webpages_Controllers.ds_controller :
                                            "Login",
                        },
                        dtAcesso    = e.dtAcesso,
                        dsAplicacao = e.flMobile ? "Mobile" : "Portal",
                        dsUserAgent = e.dsUserAgent
                    }).ToList <dynamic>();
                }

                transaction.Commit();

                retorno.Registros = CollectionLogAcesso;

                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 logs" : 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();
                }
            }
        }
Beispiel #7
0
        /// <summary>
        /// Retorna TbEmpresa/TbEmpresa
        /// </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
            {
                // FILTRO
                string outValue = null;
                Int32  IdGrupo  = Permissoes.GetIdGrupo(token, _db);
                if (IdGrupo != 0)
                {
                    if (queryString.TryGetValue("" + (int)CAMPOS.CDEMPRESAGRUPO, out outValue))
                    {
                        queryString["" + (int)CAMPOS.CDEMPRESAGRUPO] = IdGrupo.ToString();
                    }
                    else
                    {
                        queryString.Add("" + (int)CAMPOS.CDEMPRESAGRUPO, IdGrupo.ToString());
                    }
                }
                string CnpjEmpresa = Permissoes.GetCNPJEmpresa(token, _db);
                if (!CnpjEmpresa.Equals(""))
                {
                    string CnpjBaseEmpresa = CnpjEmpresa.Substring(0, 8);
                    if (queryString.TryGetValue("" + (int)CAMPOS.NRCNPJBASE, out outValue))
                    {
                        queryString["" + (int)CAMPOS.NRCNPJBASE] = CnpjBaseEmpresa;
                    }
                    else
                    {
                        queryString.Add("" + (int)CAMPOS.NRCNPJBASE, CnpjBaseEmpresa);
                    }
                }

                //DECLARAÇÕES
                List <dynamic> CollectionTbEmpresa = new List <dynamic>();
                Retorno        retorno             = new Retorno();
                retorno.Totais = new Dictionary <string, object>();

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

                // Vendedor ATOS sem estar associado com um grupo empresa?
                if (IdGrupo == 0 && Permissoes.isAtosRoleVendedor(token, _db))
                {
                    // Perfil Comercial tem uma carteira de clientes específica
                    List <Int32> listaIdsGruposEmpresas = Permissoes.GetIdsGruposEmpresasVendedor(token, _db);
                    query = query.Where(e => listaIdsGruposEmpresas.Contains(e.cdEmpresaGrupo)).AsQueryable <tbEmpresa>();
                }

                // 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) // Consulta de todas as empresas aptas a importação XML
                {
                    CollectionTbEmpresa = _db.tbEmpresas
                                          .Join(_db.tbEmpresaFiliais, e => e.nrCNPJBase, f => f.nrCNPJBase, (e, f) => new { e, f })
                                          .Join(_db.tbEmpresaGrupos, f => f.f.cdEmpresaGrupo, g => g.cdEmpresaGrupo, (f, g) => new { f, g })
                                          .Where(e => e.f.e.dsCertificadoDigital != null && e.f.e.dsCertificadoDigitalSenha != null && e.f.f.flAtivo == true && e.g.flTaxServices == true && e.g.flAtivo == true && e.f.e.dtValidade >= DateTime.Now && e.f.e.flSenhaValida != false)
                                          .GroupBy(e => new { e.f.e.cdEmpresaGrupo, e.f.e.dsCertificadoDigitalSenha, e.f.f.nrCNPJ, e.f.e.nrCNPJBase })
                                          .Select(e => new
                    {
                        cdEmpresaGrupo = e.Key.cdEmpresaGrupo,

                        dsCertificadoDigital = _db.tbEmpresas
                                               .Where(t => t.nrCNPJBase.Equals(e.Key.nrCNPJBase))
                                               .Select(s => new { s.dsCertificadoDigital }).FirstOrDefault().dsCertificadoDigital,

                        dsCertificadoDigitalSenha = e.Key.dsCertificadoDigitalSenha,
                        nrCNPJ = e.Key.nrCNPJ
                    })
                                          .AsQueryable().ToList <dynamic>();
                }
                else if (colecao == 0)
                {
                    CollectionTbEmpresa = query.Select(e => new
                    {
                        nrCNPJBase                = e.nrCNPJBase,
                        dsCertificadoDigital      = e.dsCertificadoDigital,
                        dsCertificadoDigitalSenha = e.dsCertificadoDigitalSenha,
                        cdEmpresaGrupo            = e.cdEmpresaGrupo,
                        dtCadastro                = e.dtCadastro,
                        dtValidade                = e.dtValidade,
                        flSenhaValida             = e.flSenhaValida,
                    }).ToList <dynamic>();
                }
                else if (colecao == 2) // Verificar WEBAPI
                {
                    CollectionTbEmpresa = query.Select(e => new
                    {
                        nrCNPJBase                = e.nrCNPJBase,
                        dsCertificadoDigital      = e.dsCertificadoDigital,
                        dsCertificadoDigitalSenha = e.dsCertificadoDigitalSenha,
                        cdEmpresaGrupo            = e.cdEmpresaGrupo,
                    }).Take(1).ToList <dynamic>();
                }
                else if (colecao == 3) // [PORTAL] Cadastro Certificado Digital
                {
                    CollectionTbEmpresa = query.Select(e => new
                    {
                        nrCNPJBase = e.nrCNPJBase,
                        certificadoDigitalPresente = e.dsCertificadoDigital != null,
                        senhaPresente  = e.dsCertificadoDigitalSenha != null && !e.dsCertificadoDigitalSenha.Equals(""),
                        tbempresagrupo = new { cdEmpresaGrupo = e.cdEmpresaGrupo,
                                               dsEmpresaGrupo = e.tbEmpresaGrupo.dsEmpresaGrupo },
                        dtCadastro    = e.dtCadastro,
                        dtValidade    = e.dtValidade,
                        flSenhaValida = e.flSenhaValida,
                    }).ToList <dynamic>();
                }


                transaction.Commit();

                retorno.TotalDeRegistros = CollectionTbEmpresa.Count;
                retorno.Registros        = CollectionTbEmpresa;

                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 TbEmpresa" : 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();
                }
            }
        }
Beispiel #8
0
        /// <summary>
        /// Retorna LoginOperadora/LoginOperadora
        /// </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
            {
                // Filtro de grupo empresa e filial
                string outValue = null;
                Int32  IdGrupo  = Permissoes.GetIdGrupo(token, _db);
                if (colecao != 3 ||
                    !queryString.TryGetValue("" + (int)CAMPOS.ESTABELECIMENTO, out outValue) || // se for a coleção 3, tem que ter filtro de estabelecimento
                    !Permissoes.isAtosRole(token))                                              // Como coleção 3 é para consultar estabelecimento, quem for de perfil atos
                {
                    if (IdGrupo != 0)
                    {
                        if (queryString.TryGetValue("" + (int)CAMPOS.IDGRUPO, out outValue))
                        {
                            queryString["" + (int)CAMPOS.IDGRUPO] = IdGrupo.ToString();
                        }
                        else
                        {
                            queryString.Add("" + (int)CAMPOS.IDGRUPO, 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);
                        }
                    }
                }


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

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

                // Perfil vendedor ?
                if (IdGrupo == 0 && Permissoes.isAtosRoleVendedor(token, _db))
                {
                    // Perfil Comercial tem uma carteira de clientes específica
                    List <Int32> listaIdsGruposEmpresas = Permissoes.GetIdsGruposEmpresasVendedor(token, _db);
                    query = query.Where(e => listaIdsGruposEmpresas.Contains(e.empresa.id_grupo)).AsQueryable <LoginOperadora>();
                }


                // PAGINAÇÃO
                if (colecao != 4) // senhas inválidas
                {
                    // TOTAL DE REGISTROS
                    retorno.TotalDeRegistros = query.Count();

                    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)
                {
                    CollectionLoginOperadora = query.Select(e => new
                    {
                        id                        = e.id,
                        login                     = e.login,
                        senha                     = e.senha,
                        data_alteracao            = e.data_alteracao,
                        status                    = e.status,
                        cnpj                      = e.cnpj,
                        idOperadora               = e.idOperadora,
                        idGrupo                   = e.idGrupo,
                        estabelecimento           = e.estabelecimento,
                        nrCNPJCentralizadora      = e.nrCNPJCentralizadora,
                        cdEstabelecimentoConsulta = e.cdEstabelecimentoConsulta,
                        dtBloqueio                = e.dtBloqueio,
                    }).ToList <dynamic>();
                }
                else if (colecao == 0)
                {
                    CollectionLoginOperadora = query.Select(e => new
                    {
                        id                        = e.id,
                        login                     = e.login,
                        senha                     = e.senha,
                        data_alteracao            = e.data_alteracao,
                        status                    = e.status,
                        cnpj                      = e.cnpj,
                        idOperadora               = e.idOperadora,
                        idGrupo                   = e.idGrupo,
                        estabelecimento           = e.estabelecimento,
                        nrCNPJCentralizadora      = e.nrCNPJCentralizadora,
                        cdEstabelecimentoConsulta = e.cdEstabelecimentoConsulta,
                        dtBloqueio                = e.dtBloqueio,
                    }).ToList <dynamic>();
                }
                else if (colecao == 2) // [mobile]
                {
                    CollectionLoginOperadora = query.Select(e => new
                    {
                        id                        = e.id,
                        login                     = e.login,
                        senha                     = e.senha,
                        status                    = e.status,
                        estabelecimento           = e.estabelecimento,
                        operadora                 = e.Operadora.nmOperadora,
                        idOperadora               = e.idOperadora,
                        nrCNPJCentralizadora      = e.nrCNPJCentralizadora,
                        cdEstabelecimentoConsulta = e.cdEstabelecimentoConsulta,
                        dtBloqueio                = e.dtBloqueio,
                    }).ToList <dynamic>();
                }
                else if (colecao == 3) // [web]/Dados de Acesso/Grid
                {
                    CollectionLoginOperadora = query.Select(e => new
                    {
                        id           = e.id,
                        login        = e.login,
                        senha        = e.senha,
                        status       = e.status,
                        empresa      = new { nu_cnpj = e.empresa.nu_cnpj, ds_fantasia = e.empresa.ds_fantasia, filial = e.empresa.filial },
                        grupoempresa = new { id_grupo = e.empresa.id_grupo, ds_nome = e.empresa.grupo_empresa.ds_nome },
                        //operadora = new { id = e.Operadora.id ,desOperadora = e.Operadora.nmOperadora },
                        operadora                 = new { id = e.Operadora.id, desOperadora = _db.Adquirentes.Where(a => a.nome.Equals(e.Operadora.nmOperadora)).Select(a => a.descricao).FirstOrDefault() },
                        estabelecimento           = e.estabelecimento,
                        empresaCentralizadora     = e.nrCNPJCentralizadora == null ? null : new { nu_cnpj = e.empresaCentralizadora.nu_cnpj, ds_fantasia = e.empresaCentralizadora.ds_fantasia, filial = e.empresaCentralizadora.filial },
                        cdEstabelecimentoConsulta = e.cdEstabelecimentoConsulta,
                        dtBloqueio                = e.dtBloqueio,
                    }).ToList <dynamic>();

                    CollectionLoginOperadora = CollectionLoginOperadora.OrderBy(l => l.operadora.desOperadora).ToList();
                }
                else if (colecao == 4) // [web]/Senhas Inválidas/Grid
                {
                    var subQuery = query
                                   .OrderBy(e => e.grupo_empresa.ds_nome).ThenBy(e => e.empresa.ds_fantasia).ThenBy(e => e.Operadora.nmOperadora)
                                   .Where(e => e.status == false)
                                   .Select(e => new
                    {
                        id           = e.id,
                        login        = e.login,
                        senha        = e.senha,
                        status       = e.status,
                        empresa      = e.empresa.ds_fantasia + (e.empresa.filial != null ? " " + e.empresa.filial : ""),
                        grupoempresa = e.grupo_empresa.ds_nome,
                        //operadora = e.Operadora.nmOperadora,
                        operadora                 = _db.Adquirentes.Where(a => a.nome.Equals(e.Operadora.nmOperadora)).Select(a => a.descricao).FirstOrDefault(),
                        estabelecimento           = e.estabelecimento,
                        empresaCentralizadora     = e.nrCNPJCentralizadora == null ? null : new { nu_cnpj = e.empresaCentralizadora.nu_cnpj, ds_fantasia = e.empresaCentralizadora.ds_fantasia, filial = e.empresaCentralizadora.filial },
                        cdEstabelecimentoConsulta = e.cdEstabelecimentoConsulta,
                        dtBloqueio                = e.dtBloqueio,
                    });

                    retorno.TotalDeRegistros = subQuery.Count();

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

                    CollectionLoginOperadora = subQuery.ToList <dynamic>();
                }

                transaction.Commit();

                retorno.Registros = CollectionLoginOperadora;

                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 login operadora" : 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();
                }
            }
        }
Beispiel #9
0
        /// <summary>
        /// Retorna PDV/PDV
        /// </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> CollectionPDV = new List <dynamic>();
                Retorno        retorno       = new Retorno();

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

                // GET QUERY
                var query = getQuery(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)
                {
                    CollectionPDV = query.Select(e => new
                    {
                        IdPDV               = e.IdPDV,
                        CNPJjFilial         = e.CNPJjFilial,
                        DecricaoPdv         = e.DecricaoPdv,
                        CodPdvERP           = e.CodPdvERP,
                        cdEmpresaTEF        = e.cdEmpresaTEF,
                        CodPdvHostPagamento = e.CodPdvHostPagamento,
                        cdGrupo             = e.cdGrupo,
                    }).ToList <dynamic>();
                }
                else if (colecao == 0)
                {
                    CollectionPDV = query.Select(e => new
                    {
                        IdPDV               = e.IdPDV,
                        CNPJjFilial         = e.CNPJjFilial,
                        DecricaoPdv         = e.DecricaoPdv,
                        CodPdvERP           = e.CodPdvERP,
                        cdEmpresaTEF        = e.cdEmpresaTEF,
                        CodPdvHostPagamento = e.CodPdvHostPagamento,
                        cdGrupo             = e.cdGrupo,
                    }).ToList <dynamic>();
                }
                else if (colecao == 2)
                {
                    CollectionPDV = query.GroupBy(e => e.CodPdvHostPagamento)
                                    .Select(e => new
                    {
                        CodPdvHostPagamento = e.Key,
                    }).ToList <dynamic>();
                }

                retorno.Registros = CollectionPDV;

                return(retorno);
            }
            catch (Exception e)
            {
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao consultar pdvs" : erro);
                }
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
            }
        }