コード例 #1
0
        /// <summary>
        /// Get TbAdquirente/TbAdquirente
        /// </summary>
        /// <param name="colecao"></param>
        /// <param name="campo"></param>
        /// <param name="orderby"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageNumber"></param>
        /// <param name="queryString"></param>
        /// <returns></returns>
        private static IQueryable <tbLoginAdquirenteEmpresa> getQuery(painel_taxservices_dbContext _db, int colecao, int campo, int orderby, int pageSize, int pageNumber, Dictionary <string, string> queryString)
        {
            // DEFINE A QUERY PRINCIPAL
            var entity = _db.tbLoginAdquirenteEmpresas.AsQueryable <tbLoginAdquirenteEmpresa>();

            #region WHERE - ADICIONA OS FILTROS A QUERY

            // ADICIONA OS FILTROS A QUERY
            foreach (var item in queryString)
            {
                int    key        = Convert.ToInt16(item.Key);
                CAMPOS filtroEnum = (CAMPOS)key;
                switch (filtroEnum)
                {
                case CAMPOS.CDLOGINADQUIRENTEEMPRESA:
                    Int32 cdLoginAdquirenteEmpresa = Convert.ToInt32(item.Value);
                    entity = entity.Where(e => e.cdAdquirente == cdLoginAdquirenteEmpresa).AsQueryable <tbLoginAdquirenteEmpresa>();
                    break;

                case CAMPOS.CDADQUIRENTE:
                    Int32 cdAdquirente = Convert.ToInt32(item.Value);
                    entity = entity.Where(e => e.cdAdquirente == cdAdquirente).AsQueryable <tbLoginAdquirenteEmpresa>();
                    break;

                case CAMPOS.CDGRUPO:
                    Int32 cdGrupo = Convert.ToInt32(item.Value);
                    entity = entity.Where(e => e.cdGrupo == cdGrupo).AsQueryable <tbLoginAdquirenteEmpresa>();
                    break;

                case CAMPOS.NRCNPJ:
                    string nrCnpj = Convert.ToString(item.Value);
                    entity = entity.Where(e => e.nrCnpj.Equals(nrCnpj)).AsQueryable <tbLoginAdquirenteEmpresa>();
                    break;

                case CAMPOS.DSLOGIN:
                    string dsLogin = Convert.ToString(item.Value);
                    entity = entity.Where(e => e.dsLogin.Equals(dsLogin)).AsQueryable <tbLoginAdquirenteEmpresa>();
                    break;

                case CAMPOS.DSSENHA:
                    string dsSenha = Convert.ToString(item.Value);
                    entity = entity.Where(e => e.dsSenha.Equals(dsSenha)).AsQueryable <tbLoginAdquirenteEmpresa>();
                    break;

                case CAMPOS.CDESTABELECIMENTO:
                    string cdEstabelecimento = Convert.ToString(item.Value);
                    entity = entity.Where(e => e.cdEstabelecimento.Equals(cdEstabelecimento)).AsQueryable <tbLoginAdquirenteEmpresa>();
                    break;

                case CAMPOS.DTALTERACAO:
                    DateTime dtAlteracao = Convert.ToDateTime(item.Value);
                    entity = entity.Where(e => e.dtAlteracao.Equals(dtAlteracao)).AsQueryable <tbLoginAdquirenteEmpresa>();
                    break;

                case CAMPOS.STLOGINADQUIRENTE:
                    byte stLoginAdquirente = Convert.ToByte(item.Value);
                    entity = entity.Where(e => e.stLoginAdquirente.Equals(stLoginAdquirente)).AsQueryable <tbLoginAdquirenteEmpresa>();
                    break;

                case CAMPOS.STLOGINADQUIRENTEEMPRESA:
                    byte stLoginAdquirenteEmpresa = Convert.ToByte(item.Value);
                    entity = entity.Where(e => e.stLoginAdquirenteEmpresa.Equals(stLoginAdquirenteEmpresa)).AsQueryable <tbLoginAdquirenteEmpresa>();
                    break;

                case CAMPOS.NRCNPJCENTRALIZADORA:
                    string nrCNPJCentralizadora = Convert.ToString(item.Value);
                    entity = entity.Where(e => e.nrCNPJCentralizadora != null && e.nrCNPJCentralizadora.Equals(nrCNPJCentralizadora)).AsQueryable <tbLoginAdquirenteEmpresa>();
                    break;

                case CAMPOS.CDESTABELECIMENTOCONSULTA:
                    string cdEstabelecimentoConsulta = Convert.ToString(item.Value);
                    if (cdEstabelecimentoConsulta.Contains("%"))     // usa LIKE
                    {
                        string busca = cdEstabelecimentoConsulta.Replace("%", "").ToString();
                        // Remove os zeros a esquerda
                        while (busca.StartsWith("0"))
                        {
                            busca = busca.Substring(1);
                        }
                        // Consult
                        entity = entity.Where(e => e.cdEstabelecimentoConsulta != null && e.cdEstabelecimentoConsulta.Contains(busca)).AsQueryable <tbLoginAdquirenteEmpresa>();
                    }
                    else
                    {
                        entity = entity.Where(e => e.cdEstabelecimentoConsulta != null && e.cdEstabelecimentoConsulta.Equals(cdEstabelecimentoConsulta)).AsQueryable <tbLoginAdquirenteEmpresa>();
                    }
                    break;

                // PERSONALIZADO
                case CAMPOS.DSADQUIRENTE:
                    string dsAdquirente = Convert.ToString(item.Value);
                    entity = entity.Where(e => e.tbAdquirente.dsAdquirente.Equals(dsAdquirente)).AsQueryable <tbLoginAdquirenteEmpresa>();
                    break;

                case CAMPOS.DS_FANTASIA:
                    string ds_fantasia = Convert.ToString(item.Value);
                    if (ds_fantasia.Contains("%"))     // usa LIKE
                    {
                        string busca = ds_fantasia.Replace("%", "").ToString();
                        entity = entity.Where(e => e.empresa.ds_fantasia.Contains(busca)).AsQueryable <tbLoginAdquirenteEmpresa>();
                    }
                    else
                    {
                        entity = entity.Where(e => e.empresa.ds_fantasia.Equals(ds_fantasia)).AsQueryable <tbLoginAdquirenteEmpresa>();
                    }
                    break;
                }
            }
            #endregion

            #region ORDER BY - ADICIONA A ORDENAÇÃO A QUERY
            // ADICIONA A ORDENAÇÃO A QUERY
            CAMPOS filtro = (CAMPOS)campo;
            switch (filtro)
            {
            case CAMPOS.CDLOGINADQUIRENTEEMPRESA:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.cdLoginAdquirenteEmpresa).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.cdLoginAdquirenteEmpresa).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                break;

            case CAMPOS.CDADQUIRENTE:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.cdAdquirente).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.cdAdquirente).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                break;

            case CAMPOS.CDGRUPO:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.cdGrupo).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.cdGrupo).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                break;

            case CAMPOS.NRCNPJ:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.nrCnpj).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.nrCnpj).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                break;

            case CAMPOS.DSLOGIN:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.dsLogin).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.dsLogin).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                break;

            case CAMPOS.DSSENHA:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.dsSenha).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.dsSenha).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                break;

            case CAMPOS.CDESTABELECIMENTO:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.cdEstabelecimento).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.cdEstabelecimento).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                break;

            case CAMPOS.DTALTERACAO:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.dtAlteracao).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.dtAlteracao).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                break;

            case CAMPOS.STLOGINADQUIRENTE:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.stLoginAdquirente).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.stLoginAdquirente).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                break;

            case CAMPOS.STLOGINADQUIRENTEEMPRESA:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.stLoginAdquirenteEmpresa).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.stLoginAdquirenteEmpresa).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                break;

            // PERSONALIZADO
            case CAMPOS.DSADQUIRENTE:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.tbAdquirente.dsAdquirente).ThenBy(e => e.dsLogin).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.tbAdquirente.dsAdquirente).ThenByDescending(e => e.dsLogin).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                break;

            case CAMPOS.DS_FANTASIA:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.empresa.ds_fantasia).ThenBy(e => e.tbAdquirente.dsAdquirente).ThenBy(e => e.dsLogin).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.empresa.ds_fantasia).ThenByDescending(e => e.tbAdquirente.dsAdquirente).ThenByDescending(e => e.dsLogin).AsQueryable <tbLoginAdquirenteEmpresa>();
                }
                break;
            }
            #endregion

            return(entity);
        }
コード例 #2
0
        /// <summary>
        /// Retorna a lista de conciliação bancária
        /// </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> CollectionRelatorioVendas = new List <dynamic>();
                Retorno        retorno = new Retorno();


                // QUERIES DE FILTRO
                string outValue = null;
                Dictionary <string, string> queryStringAjustes            = new Dictionary <string, string>();
                Dictionary <string, string> queryStringRecebimentoParcela = new Dictionary <string, string>();
                Dictionary <string, string> queryStringTbLogCarga         = new Dictionary <string, string>();

                // DATA DA VENDA => OBRIGATÓRIO
                DateTime dataNow = Convert.ToDateTime(DateTime.Now.ToShortDateString());
                DateTime dataInicial, dataFinal;
                if (queryString.TryGetValue("" + (int)CAMPOS.DATA, out outValue))
                {
                    // Não permite que o período seja superior ou igual a data corrente
                    string data = queryString["" + (int)CAMPOS.DATA];
                    if (data.Contains("|"))
                    {
                        dataInicial = DateTime.ParseExact(data.Substring(0, data.IndexOf("|")) + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        //if (dataInicial >= dataNow)
                        //    throw new Exception("Data inicial do período de vendas deve ser inferior a data corrente (" + dataNow.ToShortDateString() + ")");
                        dataFinal = DateTime.ParseExact(data.Substring(data.IndexOf("|") + 1) + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        //if (dataFinal >= dataNow)
                        //    throw new Exception("Data final do período de vendas deve ser inferior a data corrente (" + dataNow.ToShortDateString() + ")");
                        if (dataInicial > dataFinal)
                        {
                            throw new Exception("Período de vendas informado é inválido!");
                        }
                    }
                    else if (data.Length == 6)
                    {
                        dataInicial = DateTime.ParseExact(data + "01" + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        dataFinal   = Convert.ToDateTime(DateTime.DaysInMonth(dataInicial.Year, dataInicial.Month) + "/" + dataInicial.Month + "/" + dataInicial.Year);
                    }
                    else
                    {
                        dataFinal = dataInicial = DateTime.ParseExact(data + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                    }
                    //else
                    //{
                    //    DateTime dataVenda = DateTime.ParseExact(data + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                    //    if (dataVenda >= dataNow)
                    //        throw new Exception("Data da venda informada deve ser inferior a data corrente (" + dataNow.ToShortDateString() + ")");
                    //}
                    queryStringAjustes.Add("" + (int)GatewayTbRecebimentoAjuste.CAMPOS.DTVENDA, data);
                    queryStringRecebimentoParcela.Add("" + (int)GatewayRecebimentoParcela.CAMPOS.DTAVENDA, data);
                    queryStringTbLogCarga.Add("" + (int)GatewayTbLogCarga.CAMPOS.DTCOMPETENCIA, data);
                }
                else
                {
                    throw new Exception("Data ou período de vendas deve ser informado!");
                }

                // 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)
                {
                    queryStringAjustes.Add("" + (int)GatewayTbRecebimentoAjuste.CAMPOS.ID_GRUPO, IdGrupo.ToString());
                    queryStringRecebimentoParcela.Add("" + (int)GatewayRecebimentoParcela.CAMPOS.ID_GRUPO, IdGrupo.ToString());
                    queryStringTbLogCarga.Add("" + (int)GatewayTbLogCarga.CAMPOS.ID_GRUPO, IdGrupo.ToString());
                }
                else
                {
                    throw new Exception("Um grupo deve ser selecionado como filtro de recebíveis futuros!");
                }
                // 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(""))
                {
                    queryStringAjustes.Add("" + (int)GatewayTbRecebimentoAjuste.CAMPOS.NRCNPJ, CnpjEmpresa);
                    queryStringRecebimentoParcela.Add("" + (int)GatewayRecebimentoParcela.CAMPOS.NU_CNPJ, CnpjEmpresa);
                    queryStringTbLogCarga.Add("" + (int)GatewayTbLogCarga.CAMPOS.NRCNPJ, CnpjEmpresa);
                }
                // ADQUIRENTE
                if (queryString.TryGetValue("" + (int)CAMPOS.CDADQUIRENTE, out outValue))
                {
                    string cdAdquirente = queryString["" + (int)CAMPOS.CDADQUIRENTE];
                    queryStringAjustes.Add("" + (int)GatewayTbRecebimentoAjuste.CAMPOS.CDADQUIRENTE, cdAdquirente);
                    queryStringRecebimentoParcela.Add("" + (int)GatewayRecebimentoParcela.CAMPOS.CDADQUIRENTE, cdAdquirente);
                    queryStringTbLogCarga.Add("" + (int)GatewayTbLogCarga.CAMPOS.CDADQUIRENTE, cdAdquirente);
                }


                // OBTÉM A QUERY
                //IQueryable<RecebimentoParcela> queryRecebimentoParcela = GatewayRecebimentoParcela.getQuery(_db, 0, (int)GatewayRecebimentoParcela.CAMPOS.DTAVENDA, 0, 0, 0, queryStringRecebimentoParcela);

                // 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");
                }

                List <RelatorioVendas>   vendas      = new List <RelatorioVendas>();
                List <LogCargaValorSite> valoresSite = new List <LogCargaValorSite>();

                try
                {
                    #region OBTÉM AS QUERIES
                    SimpleDataBaseQuery dataBaseQueryRP = GatewayRecebimentoParcela.getQuery((int)GatewayRecebimentoParcela.CAMPOS.DTARECEBIMENTOEFETIVO, 0, queryStringRecebimentoParcela);
                    SimpleDataBaseQuery dataBaseQueryAJ = GatewayTbRecebimentoAjuste.getQuery((int)GatewayTbRecebimentoAjuste.CAMPOS.DTVENDA, 0, queryStringAjustes);
                    SimpleDataBaseQuery dataBaseQueryLC = GatewayTbLogCarga.getQuery((int)GatewayTbLogCarga.CAMPOS.DTCOMPETENCIA, 0, queryStringTbLogCarga);

                    // RECEBIMENTO PARCELA
                    if (!dataBaseQueryRP.join.ContainsKey("INNER JOIN pos.Recebimento " + GatewayRecebimento.SIGLA_QUERY))
                    {
                        dataBaseQueryRP.join.Add("INNER JOIN pos.Recebimento " + GatewayRecebimento.SIGLA_QUERY, " ON " + GatewayRecebimento.SIGLA_QUERY + ".id = " + GatewayRecebimentoParcela.SIGLA_QUERY + ".idRecebimento");
                    }
                    if (!dataBaseQueryRP.join.ContainsKey("INNER JOIN card.tbBandeira " + GatewayTbBandeira.SIGLA_QUERY))
                    {
                        dataBaseQueryRP.join.Add("INNER JOIN card.tbBandeira " + GatewayTbBandeira.SIGLA_QUERY, " ON " + GatewayTbBandeira.SIGLA_QUERY + ".cdBandeira = " + GatewayRecebimento.SIGLA_QUERY + ".cdBandeira");
                    }
                    if (!dataBaseQueryRP.join.ContainsKey("INNER JOIN card.tbAdquirente " + GatewayTbAdquirente.SIGLA_QUERY))
                    {
                        dataBaseQueryRP.join.Add("INNER JOIN card.tbAdquirente " + GatewayTbAdquirente.SIGLA_QUERY, " ON " + GatewayTbAdquirente.SIGLA_QUERY + ".cdAdquirente = " + GatewayTbBandeira.SIGLA_QUERY + ".cdAdquirente");
                    }
                    //if (!dataBaseQueryRP.join.ContainsKey("INNER JOIN cliente.empresa " + GatewayEmpresa.SIGLA_QUERY))
                    //    dataBaseQueryRP.join.Add("INNER JOIN cliente.empresa " + GatewayEmpresa.SIGLA_QUERY, " ON " + GatewayRecebimento.SIGLA_QUERY + ".cnpj = " + GatewayEmpresa.SIGLA_QUERY + ".nu_cnpj");

                    // AJUSTES
                    if (!dataBaseQueryAJ.join.ContainsKey("INNER JOIN card.tbBandeira " + GatewayTbBandeira.SIGLA_QUERY))
                    {
                        dataBaseQueryAJ.join.Add("INNER JOIN card.tbBandeira " + GatewayTbBandeira.SIGLA_QUERY, " ON " + GatewayTbBandeira.SIGLA_QUERY + ".cdBandeira = " + GatewayTbRecebimentoAjuste.SIGLA_QUERY + ".cdBandeira");
                    }
                    if (!dataBaseQueryAJ.join.ContainsKey("INNER JOIN card.tbAdquirente " + GatewayTbAdquirente.SIGLA_QUERY))
                    {
                        dataBaseQueryAJ.join.Add("INNER JOIN card.tbAdquirente " + GatewayTbAdquirente.SIGLA_QUERY, " ON " + GatewayTbAdquirente.SIGLA_QUERY + ".cdAdquirente = " + GatewayTbBandeira.SIGLA_QUERY + ".cdAdquirente");
                    }

                    // TBLOGCARGA
                    if (!dataBaseQueryLC.join.ContainsKey("INNER JOIN card.tbAdquirente " + GatewayTbAdquirente.SIGLA_QUERY))
                    {
                        dataBaseQueryLC.join.Add("INNER JOIN card.tbAdquirente " + GatewayTbAdquirente.SIGLA_QUERY, " ON " + GatewayTbAdquirente.SIGLA_QUERY + ".cdAdquirente = " + GatewayTbLogCarga.SIGLA_QUERY + ".cdAdquirente");
                    }


                    // RECEBIMENTO PARCELA
                    dataBaseQueryRP.select = new string[] { GatewayRecebimentoParcela.SIGLA_QUERY + ".dtaRecebimento",
                                                            GatewayRecebimentoParcela.SIGLA_QUERY + ".dtaRecebimentoEfetivo",
                                                            GatewayRecebimento.SIGLA_QUERY + ".dtaVenda AS dataVenda",
                                                            "adquirente = UPPER(" + GatewayTbAdquirente.SIGLA_QUERY + ".nmAdquirente)",
                                                            GatewayTbBandeira.SIGLA_QUERY + ".dsBandeira AS bandeira",
                                                            "valorBruto = " + GatewayRecebimentoParcela.SIGLA_QUERY + ".valorParcelaBruta",
                                                            "valorDescontado = " + GatewayRecebimentoParcela.SIGLA_QUERY + ".valorDescontado",
                                                            "valorLiquido = ISNULL(" + GatewayRecebimentoParcela.SIGLA_QUERY + ".valorParcelaLiquida, 0)" };

                    // AJUSTE
                    dataBaseQueryAJ.select = new string[] { //GatewayTbRecebimentoAjuste.SIGLA_QUERY + ".idRecebimentoAjuste",
                        //GatewayTbRecebimentoAjuste.SIGLA_QUERY + ".dsMotivo",
                        GatewayTbRecebimentoAjuste.SIGLA_QUERY + ".vlAjuste",
                        GatewayTbRecebimentoAjuste.SIGLA_QUERY + ".dtAjuste",
                        GatewayTbRecebimentoAjuste.SIGLA_QUERY + ".dtVenda AS dataVenda",
                        GatewayTbRecebimentoAjuste.SIGLA_QUERY + ".vlBruto",
                        GatewayTbBandeira.SIGLA_QUERY + ".dsBandeira AS bandeira",
                        "adquirente = UPPER(" + GatewayTbAdquirente.SIGLA_QUERY + ".nmAdquirente)"
                    };


                    // TBLOGCARGA
                    dataBaseQueryLC.select = new string[] { GatewayTbLogCarga.SIGLA_QUERY + ".dtCompetencia",
                                                            "adquirente = UPPER(" + GatewayTbAdquirente.SIGLA_QUERY + ".nmAdquirente)",
                                                            "processouVendas = CASE WHEN SUM(CASE WHEN " + GatewayTbLogCarga.SIGLA_QUERY + ".flStatusVendasCredito = 0 OR " + GatewayTbLogCarga.SIGLA_QUERY + ".flStatusVendasDebito = 0 THEN 1 ELSE 0 END) > 0 THEN 0 ELSE 1 END",
                                                            "valorSite = SUM(" + GatewayTbLogCarga.SIGLA_QUERY + ".vlVendaCredito + " + GatewayTbLogCarga.SIGLA_QUERY + ".vlVendaDebito)" };

                    dataBaseQueryLC.groupby = new string[] { GatewayTbLogCarga.SIGLA_QUERY + ".dtCompetencia",
                                                             GatewayTbAdquirente.SIGLA_QUERY + ".nmAdquirente" };


                    dataBaseQueryRP.readUncommited = true;
                    dataBaseQueryAJ.readUncommited = true;
                    dataBaseQueryLC.readUncommited = true;
                    #endregion

                    string             script    = dataBaseQueryRP.Script();
                    List <IDataRecord> resultado = DataBaseQueries.SqlQuery(script, connection);

                    if (resultado != null && resultado.Count > 0)
                    {
                        vendas = resultado.Select(r => new RelatorioVendas
                        {
                            dataVenda       = Convert.ToDateTime(((DateTime)r["dataVenda"]).ToShortDateString()), // remove horário
                            dataRecebimento = r["dtaRecebimentoEfetivo"].Equals(DBNull.Value) ? (DateTime)r["dtaRecebimento"] : (DateTime)r["dtaRecebimentoEfetivo"],
                            recebeu         = r["dtaRecebimentoEfetivo"].Equals(DBNull.Value) ? (DateTime)r["dtaRecebimento"] < dataNow : (DateTime)r["dtaRecebimentoEfetivo"] < dataNow,
                            valorBruto      = Convert.ToDecimal(r["valorBruto"]),
                            valorLiquido    = Convert.ToDecimal(r["valorLiquido"]),
                            valorDescontado = Convert.ToDecimal(r["valorDescontado"]),
                            bandeira        = Convert.ToString(r["bandeira"]),
                            adquirente      = Convert.ToString(r["adquirente"]),
                        }).OrderBy(r => r.dataVenda).ToList <RelatorioVendas>();
                    }

                    // Ajustes de vendas
                    script    = dataBaseQueryAJ.Script();
                    resultado = DataBaseQueries.SqlQuery(script, connection);
                    if (resultado != null && resultado.Count > 0)
                    {
                        foreach (IDataRecord r in resultado)
                        {
                            vendas.Add(new RelatorioVendas
                            {
                                dataVenda       = Convert.ToDateTime(((DateTime)r["dataVenda"]).ToShortDateString()), // remove horário
                                dataRecebimento = (DateTime)r["dtAjuste"],
                                recebeu         = (DateTime)r["dtAjuste"] < dataNow,
                                valorBruto      = Convert.ToDecimal(r["vlBruto"]) != new decimal(0.0) ? Convert.ToDecimal(r["vlBruto"]) : Convert.ToDecimal(r["vlAjuste"]) > new decimal(0.0) ? Convert.ToDecimal(r["vlAjuste"]) : new decimal(0.0),
                                valorLiquido    = Convert.ToDecimal(r["vlAjuste"]),
                                valorDescontado = Convert.ToDecimal(r["vlAjuste"]) > new decimal(0.0) ? new decimal(0.0) : Math.Abs(Convert.ToDecimal(r["vlAjuste"])),
                                bandeira        = Convert.ToString(r["bandeira"]),
                                adquirente      = Convert.ToString(r["adquirente"]),
                            });
                        }
                    }

                    // Obtém os valores lidos do site
                    script    = dataBaseQueryLC.Script();
                    resultado = DataBaseQueries.SqlQuery(script, connection);
                    if (resultado != null && resultado.Count > 0)
                    {
                        valoresSite = resultado.Select(t => new LogCargaValorSite
                        {
                            //nrCNPJ = Convert.ToString(t["nrCNPJ"]),
                            adquirente          = Convert.ToString(t["adquirente"]),
                            dtCompetencia       = Convert.ToDateTime(((DateTime)t["dtCompetencia"]).ToShortDateString()),
                            processouModalidade = Convert.ToBoolean(t["processouVendas"]),
                            valorSite           = Convert.ToDecimal(t["valorSite"])
                        })
                                      .ToList <LogCargaValorSite>();
                    }

                    //List<RelatorioVendas> vendas = queryRecebimentoParcela.Select(r => new RelatorioVendas
                    //{
                    //    dataVenda = r.Recebimento.dtaVenda,
                    //    dataRecebimento = r.dtaRecebimentoEfetivo != null ? r.dtaRecebimentoEfetivo.Value : r.dtaRecebimento,
                    //    recebeu = (r.dtaRecebimentoEfetivo != null && r.dtaRecebimentoEfetivo.Value < dataNow) || (r.dtaRecebimentoEfetivo == null && r.dtaRecebimento < dataNow),
                    //    valorBruto = r.valorParcelaBruta,
                    //    valorLiquido = r.valorParcelaLiquida != null ? r.valorParcelaLiquida.Value : new decimal(0.0),
                    //    valorDescontado = r.valorDescontado,
                    //    bandeira = r.Recebimento.cdBandeira != null ? r.Recebimento.tbBandeira.dsBandeira : r.Recebimento.BandeiraPos.desBandeira,
                    //    adquirente = r.Recebimento.cdBandeira != null ? r.Recebimento.tbBandeira.tbAdquirente.nmAdquirente : r.Recebimento.BandeiraPos.Operadora.nmOperadora
                    //}).OrderBy(r => r.dataVenda).ToList<RelatorioVendas>();
                }
                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 { }
                }

                transaction.Commit();

                List <dynamic> vendasAgrupadas = vendas
                                                 .GroupBy(r => r.dataVenda)
                                                 .Select(r => new
                {
                    data      = r.Key,
                    valorSite = valoresSite.Where(t => t.dtCompetencia.Equals(r.Key))
                                .Where(t => r.GroupBy(f => f.adquirente).Select(f => f.Key).Contains(t.adquirente))
                                .Sum(t => t.valorSite),
                    processouVenda = valoresSite.Where(t => t.dtCompetencia.Equals(r.Key))
                                     .Where(t => r.GroupBy(f => f.adquirente).Select(f => f.Key).Contains(t.adquirente))
                                     .Count() > 0 &&
                                     valoresSite.Where(t => t.dtCompetencia.Equals(r.Key))
                                     .Where(t => r.GroupBy(f => f.adquirente).Select(f => f.Key).Contains(t.adquirente))
                                     .Where(t => !t.processouModalidade)
                                     .Count() == 0,
                    valorBruto      = r.Sum(f => f.valorBruto),
                    valorDescontado = r.Sum(f => f.valorDescontado),
                    valorLiquido    = r.Sum(f => f.valorLiquido),
                    valorRecebido   = r.Where(f => f.recebeu == true).Sum(f => f.valorLiquido),
                    valorAReceber   = r.Where(f => f.recebeu == false).Sum(f => f.valorLiquido),
                    adquirentes     = r.GroupBy(f => f.adquirente)
                                      .OrderBy(f => f.Key)
                                      .Select(f => new
                    {
                        adquirente = f.Key,
                        valorSite  = valoresSite.Where(t => t.dtCompetencia.Equals(r.Key))
                                     .Where(t => t.adquirente.Equals(f.Key))
                                     .Sum(t => t.valorSite),
                        processouVenda = valoresSite.Where(t => t.dtCompetencia.Equals(r.Key))
                                         .Where(t => t.adquirente.Equals(f.Key))
                                         .Count() > 0 &&
                                         valoresSite.Where(t => t.dtCompetencia.Equals(r.Key))
                                         .Where(t => t.adquirente.Equals(f.Key))
                                         .Where(t => !t.processouModalidade)
                                         .Count() == 0,
                        valorBruto      = f.Sum(x => x.valorBruto),
                        valorDescontado = f.Sum(x => x.valorDescontado),
                        valorLiquido    = f.Sum(x => x.valorLiquido),
                        valorRecebido   = f.Where(x => x.recebeu == true).Sum(x => x.valorLiquido),
                        valorAReceber   = f.Where(x => x.recebeu == false).Sum(x => x.valorLiquido),
                        bandeiras       = f.GroupBy(x => x.bandeira)
                                          .OrderBy(x => x.Key)
                                          .Select(x => new
                        {
                            bandeira        = x.Key,
                            valorSite       = new decimal(0.0),
                            valorBruto      = x.Sum(y => y.valorBruto),
                            valorDescontado = x.Sum(y => y.valorDescontado),
                            valorLiquido    = x.Sum(y => y.valorLiquido),
                            valorRecebido   = x.Where(y => y.recebeu == true).Sum(y => y.valorLiquido),
                            valorAReceber   = x.Where(y => y.recebeu == false).Sum(y => y.valorLiquido),
                        }).ToList <dynamic>(),
                    }).ToList <dynamic>(),
                }).ToList <dynamic>();

                for (DateTime dt = dataInicial; dt <= dataFinal; dt = dt.AddDays(1))
                {
                    var v = vendasAgrupadas.Where(t => t.data.Equals(dt)).FirstOrDefault();
                    var s = valoresSite.Where(t => t.dtCompetencia.Equals(dt)).FirstOrDefault();

                    if (v != null)
                    {
                        CollectionRelatorioVendas.Add(new
                        {
                            diaVenda        = dt.ToShortDateString(),
                            valorSite       = v.valorSite,
                            processouVenda  = v.processouVenda,
                            valorBruto      = v.valorBruto,
                            valorDescontado = v.valorDescontado,
                            valorLiquido    = v.valorLiquido,
                            valorRecebido   = v.valorRecebido,
                            valorAReceber   = v.valorAReceber,
                            adquirentes     = v.adquirentes
                        });
                    }
                    else if (s != null)
                    {
                        CollectionRelatorioVendas.Add(new
                        {
                            diaVenda  = dt.ToShortDateString(),
                            valorSite = valoresSite.Where(t => t.dtCompetencia.Equals(dt))
                                        .Sum(t => t.valorSite),
                            processouVenda = valoresSite.Where(t => t.dtCompetencia.Equals(dt))
                                             .Count() > 0 &&
                                             valoresSite.Where(t => t.dtCompetencia.Equals(dt))
                                             .Where(t => !t.processouModalidade)
                                             .Count() == 0,
                            valorBruto      = new decimal(0.0),
                            valorDescontado = new decimal(0.0),
                            valorLiquido    = new decimal(0.0),
                            valorRecebido   = new decimal(0.0),
                            valorAReceber   = new decimal(0.0),
                            adquirentes     = valoresSite.Where(f => f.dtCompetencia.Equals(dt))
                                              .GroupBy(f => f.adquirente)
                                              .Select(f => new
                            {
                                adquirente      = f.Key,
                                valorSite       = f.Sum(t => t.valorSite),
                                processouVenda  = f.Count() > 0 && f.Where(t => !t.processouModalidade).Count() == 0,
                                valorBruto      = new decimal(0.0),
                                valorDescontado = new decimal(0.0),
                                valorLiquido    = new decimal(0.0),
                                valorRecebido   = new decimal(0.0),
                                valorAReceber   = new decimal(0.0),
                                bandeiras       = new List <dynamic>()
                            })
                                              .ToList <dynamic>()
                        });
                    }
                }

                //CollectionRelatorioVendas = vendas//.GroupBy(r => new { r.dataVenda.Day, r.dataVenda.Month, r.dataVenda.Year })
                //                                .GroupBy(r => r.dataVenda)
                //                                .Select(r => new
                //                                {
                //                                    //diaVenda = (r.Key.Day < 10 ? "0" : "") + r.Key.Day + "/" + (r.Key.Month < 10 ? "0" : "") + r.Key.Month + "/" + r.Key.Year,
                //                                    diaVenda = r.Key.ToShortDateString(),
                //                                    valorSite = valoresSite.Where(t => t.dtCompetencia.Equals(r.Key))
                //                                                           .Where(t => r.GroupBy(f => f.adquirente).Select(f => f.Key).Contains(t.adquirente))
                //                                                           .Sum(t => t.valorSite),
                //                                    processouVenda = valoresSite.Where(t => t.dtCompetencia.Equals(r.Key))
                //                                                                .Where(t => r.GroupBy(f => f.adquirente).Select(f => f.Key).Contains(t.adquirente))
                //                                                                .Count() > 0 &&
                //                                                     valoresSite.Where(t => t.dtCompetencia.Equals(r.Key))
                //                                                                .Where(t => r.GroupBy(f => f.adquirente).Select(f => f.Key).Contains(t.adquirente))
                //                                                                .Where(t => !t.processouModalidade)
                //                                                                .Count() == 0,
                //                                    valorBruto = r.Sum(f => f.valorBruto),
                //                                    valorDescontado = r.Sum(f => f.valorDescontado),
                //                                    valorLiquido = r.Sum(f => f.valorLiquido),
                //                                    valorRecebido = r.Where(f => f.recebeu == true).Sum(f => f.valorLiquido),
                //                                    valorAReceber = r.Where(f => f.recebeu == false).Sum(f => f.valorLiquido),
                //                                    adquirentes = r.GroupBy(f => f.adquirente)
                //                                    .OrderBy(f => f.Key)
                //                                    .Select(f => new
                //                                    {
                //                                        adquirente = f.Key,
                //                                        valorSite = valoresSite.Where(t => t.dtCompetencia.Equals(r.Key))
                //                                                               .Where(t => t.adquirente.Equals(f.Key))
                //                                                               .Sum(t => t.valorSite),
                //                                        processouVenda = valoresSite.Where(t => t.dtCompetencia.Equals(r.Key))
                //                                                                    .Where(t => t.adquirente.Equals(f.Key))
                //                                                                    .Count() > 0 &&
                //                                                         valoresSite.Where(t => t.dtCompetencia.Equals(r.Key))
                //                                                                    .Where(t => t.adquirente.Equals(f.Key))
                //                                                                    .Where(t => !t.processouModalidade)
                //                                                                    .Count() == 0,
                //                                        valorBruto = f.Sum(x => x.valorBruto),
                //                                        valorDescontado = f.Sum(x => x.valorDescontado),
                //                                        valorLiquido = f.Sum(x => x.valorLiquido),
                //                                        valorRecebido = f.Where(x => x.recebeu == true).Sum(x => x.valorLiquido),
                //                                        valorAReceber = f.Where(x => x.recebeu == false).Sum(x => x.valorLiquido),
                //                                        bandeiras = f.GroupBy(x => x.bandeira)
                //                                        .OrderBy(x => x.Key)
                //                                        .Select(x => new
                //                                        {
                //                                            bandeira = x.Key,
                //                                            valorSite = new decimal(0.0),
                //                                            valorBruto = x.Sum(y => y.valorBruto),
                //                                            valorDescontado = x.Sum(y => y.valorDescontado),
                //                                            valorLiquido = x.Sum(y => y.valorLiquido),
                //                                            valorRecebido = x.Where(y => y.recebeu == true).Sum(y => y.valorLiquido),
                //                                            valorAReceber = x.Where(y => y.recebeu == false).Sum(y => y.valorLiquido),
                //                                        }).ToList<dynamic>(),
                //                                    }).ToList<dynamic>(),
                //                                }).ToList<dynamic>();

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

                // TOTAL
                retorno.Totais = new Dictionary <string, object>();
                retorno.Totais.Add("valorSite", CollectionRelatorioVendas.Select(r => r.valorSite).Cast <decimal>().Sum());
                retorno.Totais.Add("valorBruto", CollectionRelatorioVendas.Select(r => r.valorBruto).Cast <decimal>().Sum());
                retorno.Totais.Add("valorDescontado", CollectionRelatorioVendas.Select(r => r.valorDescontado).Cast <decimal>().Sum());
                retorno.Totais.Add("valorLiquido", CollectionRelatorioVendas.Select(r => r.valorLiquido).Cast <decimal>().Sum());
                retorno.Totais.Add("valorRecebido", CollectionRelatorioVendas.Select(r => r.valorRecebido).Cast <decimal>().Sum());
                retorno.Totais.Add("valorAReceber", CollectionRelatorioVendas.Select(r => r.valorAReceber).Cast <decimal>().Sum());

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

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

                retorno.Registros = CollectionRelatorioVendas;

                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" : 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();
                }
            }
        }
コード例 #3
0
        /// <summary>
        /// Altera webpages_Permissions
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static void Update(string token, Models.Object.RolesPermissions param, painel_taxservices_dbContext _dbContext = null)
        {
            painel_taxservices_dbContext _db;

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

            try
            {
                if ((param.Inserir != null) && (param.Inserir.Count > 0))
                {
                    foreach (var item in param.Inserir)
                    {
                        _db.webpages_Permissions.Add(new webpages_Permissions {
                            id_roles = param.Id_roles, id_method = (int)item
                        });
                    }
                }

                if ((param.Deletar != null) && (param.Deletar.Count > 0))
                {
                    foreach (var item in param.Deletar)
                    {
                        _db.webpages_Permissions.Remove(
                            _db.webpages_Permissions
                            .Where(e => e.id_roles == param.Id_roles)
                            .Where(e => e.id_method == item).First()
                            );
                    }
                }
                _db.SaveChanges();
                // set o controller principal
                if (param.Id_controller_principal != null)
                {
                    // procura por um possível controller principal
                    List <webpages_Permissions> permissoes = _db.webpages_Permissions
                                                             .Where(p => p.id_roles == param.Id_roles)
                                                             .Where(p => p.fl_principal == true).ToList <webpages_Permissions>();
                    foreach (var permissao in permissoes)
                    {
                        permissao.fl_principal = false;
                        Update(token, permissao);
                    }

                    // set os metodos do controller para ser o principal
                    permissoes = _db.webpages_Permissions
                                 .Where(p => p.id_roles == param.Id_roles)
                                 .Where(p => p.webpages_Methods.id_controller == param.Id_controller_principal).ToList <webpages_Permissions>();
                    foreach (var permissao in permissoes)
                    {
                        permissao.fl_principal = true;
                        Update(token, permissao);
                    }
                }


                // set o controller principal
                if (param.Id_controller_principal != null)
                {
                    // procura por um possível controller principal
                    List <webpages_Permissions> permissoes = _db.webpages_Permissions
                                                             .Where(p => p.id_roles == param.Id_roles)
                                                             .Where(p => p.fl_principal == true).ToList <webpages_Permissions>();
                    foreach (var permissao in permissoes)
                    {
                        permissao.fl_principal = false;
                        Update(token, permissao);
                    }

                    // set os metodos do controller para ser o principal
                    permissoes = _db.webpages_Permissions
                                 .Where(p => p.id_roles == param.Id_roles)
                                 .Where(p => p.webpages_Methods.id_controller == param.Id_controller_principal).ToList <webpages_Permissions>();
                    foreach (var permissao in permissoes)
                    {
                        permissao.fl_principal = true;
                        Update(token, permissao);
                    }
                }
            }
            catch (Exception e)
            {
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao alterar pessoa" : erro);
                }
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
            }
            finally
            {
                if (_dbContext == null)
                {
                    // Fecha conexão
                    _db.Database.Connection.Close();
                    _db.Dispose();
                }
            }
        }
コード例 #4
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();
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// Get TbRecebimentoTitulo/TbRecebimentoTitulo
        /// </summary>
        /// <param name="colecao"></param>
        /// <param name="campo"></param>
        /// <param name="orderby"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageNumber"></param>
        /// <param name="queryString"></param>
        /// <returns></returns>
        public static IQueryable <tbRecebimentoTitulo> getQuery(painel_taxservices_dbContext _db, int colecao, int campo, int orderby, int pageSize, int pageNumber, Dictionary <string, string> queryString)
        {
            // DEFINE A QUERY PRINCIPAL
            var entity = _db.tbRecebimentoTitulos.AsQueryable <tbRecebimentoTitulo>();

            #region WHERE - ADICIONA OS FILTROS A QUERY

            // ADICIONA OS FILTROS A QUERY
            foreach (var item in queryString)
            {
                int    key        = Convert.ToInt16(item.Key);
                CAMPOS filtroEnum = (CAMPOS)key;
                switch (filtroEnum)
                {
                case CAMPOS.IDRECEBIMENTOTITULO:
                    Int32 idRecebimentoTitulo = Convert.ToInt32(item.Value);
                    entity = entity.Where(e => e.idRecebimentoTitulo.Equals(idRecebimentoTitulo)).AsQueryable <tbRecebimentoTitulo>();
                    break;

                case CAMPOS.NRCNPJ:
                    string nrCNPJ = Convert.ToString(item.Value);
                    entity = entity.Where(e => e.nrCNPJ.Equals(nrCNPJ)).AsQueryable <tbRecebimentoTitulo>();
                    break;

                case CAMPOS.NRNSU:
                    string nrNSU = Convert.ToString(item.Value);
                    if (nrNSU.Contains("%"))     // usa LIKE => ENDS WITH
                    {
                        string busca = nrNSU.Replace("%", "").ToString();
                        entity = entity.Where(e => e.nrNSU.EndsWith(busca));
                    }
                    else
                    {
                        entity = entity.Where(e => e.nrNSU.Equals(nrNSU)).AsQueryable();
                    }
                    break;

                case CAMPOS.DTVENDA:
                    if (item.Value.Contains("|"))     // BETWEEN
                    {
                        string[] busca  = item.Value.Split('|');
                        DateTime dtaIni = DateTime.ParseExact(busca[0] + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        DateTime dtaFim = DateTime.ParseExact(busca[1] + " 23:59:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        entity = entity.Where(e => e.dtVenda != null && e.dtVenda.Value >= dtaIni && e.dtVenda.Value <= dtaFim).AsQueryable <tbRecebimentoTitulo>();
                    }
                    else     // IGUAL
                    {
                        string   busca  = item.Value;
                        DateTime dtaIni = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        entity = entity.Where(e => e.dtVenda != null && e.dtVenda.Value.Year == dtaIni.Year && e.dtVenda.Value.Month == dtaIni.Month && e.dtVenda.Value.Day == dtaIni.Day).AsQueryable <tbRecebimentoTitulo>();
                    }
                    break;

                case CAMPOS.CDADQUIRENTE:
                    Int32 cdAdquirente = Convert.ToInt32(item.Value);
                    entity = entity.Where(e => (e.cdAdquirente != null && e.cdAdquirente == cdAdquirente) ||
                                          (e.cdAdquirente == null && e.cdAdquirenteNew == cdAdquirente)).AsQueryable <tbRecebimentoTitulo>();
                    break;

                case CAMPOS.DSBANDEIRA:
                    string dsBandeira = Convert.ToString(item.Value);
                    entity = entity.Where(e => e.dsBandeira.Equals(dsBandeira)).AsQueryable <tbRecebimentoTitulo>();
                    break;

                case CAMPOS.VLVENDA:
                    decimal vlVenda = Convert.ToDecimal(item.Value);
                    entity = entity.Where(e => e.vlVenda.Equals(vlVenda)).AsQueryable <tbRecebimentoTitulo>();
                    break;

                case CAMPOS.QTPARCELAS:
                    byte qtParcelas = Convert.ToByte(item.Value);
                    entity = entity.Where(e => e.qtParcelas.Equals(qtParcelas)).AsQueryable <tbRecebimentoTitulo>();
                    break;

                case CAMPOS.DTTITULO:
                    if (item.Value.Contains("|"))     // BETWEEN
                    {
                        string[] busca  = item.Value.Split('|');
                        DateTime dtaIni = DateTime.ParseExact(busca[0] + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        DateTime dtaFim = DateTime.ParseExact(busca[1] + " 23:59:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        entity = entity.Where(e => e.dtTitulo >= dtaIni && e.dtTitulo <= dtaFim).AsQueryable <tbRecebimentoTitulo>();
                    }
                    else     // IGUAL
                    {
                        string   busca  = item.Value;
                        DateTime dtaIni = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        entity = entity.Where(e => e.dtTitulo.Year == dtaIni.Year && e.dtTitulo.Month == dtaIni.Month && e.dtTitulo.Day == dtaIni.Day).AsQueryable <tbRecebimentoTitulo>();
                    }
                    break;

                case CAMPOS.VLPARCELA:
                    decimal vlParcela = Convert.ToDecimal(item.Value);
                    entity = entity.Where(e => e.vlParcela.Equals(vlParcela)).AsQueryable <tbRecebimentoTitulo>();
                    break;

                case CAMPOS.NRPARCELA:
                    byte nrParcela = Convert.ToByte(item.Value);
                    entity = entity.Where(e => e.nrParcela.Equals(nrParcela)).AsQueryable <tbRecebimentoTitulo>();
                    break;

                case CAMPOS.CDERP:
                    string cdERP = Convert.ToString(item.Value);
                    entity = entity.Where(e => e.cdERP.Equals(cdERP)).AsQueryable <tbRecebimentoTitulo>();
                    break;

                case CAMPOS.DTBAIXAERP:
                    if (item.Value.Equals(""))
                    {
                        entity = entity.Where(e => e.dtBaixaERP == null).AsQueryable <tbRecebimentoTitulo>();
                    }
                    else if (item.Value.Equals("0"))
                    {
                        entity = entity.Where(e => e.dtBaixaERP != null).AsQueryable <tbRecebimentoTitulo>();
                    }
                    else if (item.Value.Contains("|"))     // BETWEEN
                    {
                        string[] busca  = item.Value.Split('|');
                        DateTime dtaIni = DateTime.ParseExact(busca[0] + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        DateTime dtaFim = DateTime.ParseExact(busca[1] + " 23:59:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        entity = entity.Where(e => e.dtBaixaERP != null && e.dtBaixaERP.Value >= dtaIni && e.dtBaixaERP.Value <= dtaFim).AsQueryable <tbRecebimentoTitulo>();
                    }
                    else     // IGUAL
                    {
                        string   busca  = item.Value;
                        DateTime dtaIni = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        entity = entity.Where(e => e.dtBaixaERP != null && e.dtBaixaERP.Value.Year == dtaIni.Year && e.dtBaixaERP.Value.Month == dtaIni.Month && e.dtBaixaERP.Value.Day == dtaIni.Day).AsQueryable <tbRecebimentoTitulo>();
                    }
                    break;

                case CAMPOS.CDSACADO:
                    string cdSacado = Convert.ToString(item.Value);
                    entity = entity.Where(e => e.cdSacado.Equals(cdSacado)).AsQueryable <tbRecebimentoTitulo>();
                    break;

                // RELACIONAMENTOS
                case CAMPOS.ID_GRUPO:
                    Int32 id_grupo = Convert.ToInt32(item.Value);
                    entity = entity.Where(e => e.empresa.id_grupo == id_grupo).AsQueryable <tbRecebimentoTitulo>();
                    break;

                case CAMPOS.ID_EXTRATO:
                    Int32 idExtrato = Convert.ToInt32(item.Value);
                    entity = entity.Where(e => e.RecebimentoParcelas.Where(r => r.idExtrato == idExtrato).Count() > 0).AsQueryable <tbRecebimentoTitulo>();
                    break;
                }
            }
            #endregion

            #region ORDER BY - ADICIONA A ORDENAÇÃO A QUERY
            // ADICIONA A ORDENAÇÃO A QUERY
            CAMPOS filtro = (CAMPOS)campo;
            switch (filtro)
            {
            case CAMPOS.IDRECEBIMENTOTITULO:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.idRecebimentoTitulo).AsQueryable <tbRecebimentoTitulo>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.idRecebimentoTitulo).AsQueryable <tbRecebimentoTitulo>();
                }
                break;

            case CAMPOS.NRCNPJ:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.nrCNPJ).AsQueryable <tbRecebimentoTitulo>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.nrCNPJ).AsQueryable <tbRecebimentoTitulo>();
                }
                break;

            case CAMPOS.NRNSU:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.nrNSU).AsQueryable <tbRecebimentoTitulo>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.nrNSU).AsQueryable <tbRecebimentoTitulo>();
                }
                break;

            case CAMPOS.DTVENDA:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.dtVenda).AsQueryable <tbRecebimentoTitulo>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.dtVenda).AsQueryable <tbRecebimentoTitulo>();
                }
                break;

            case CAMPOS.CDADQUIRENTE:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.cdAdquirente).AsQueryable <tbRecebimentoTitulo>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.cdAdquirente).AsQueryable <tbRecebimentoTitulo>();
                }
                break;

            case CAMPOS.DSBANDEIRA:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.dsBandeira).AsQueryable <tbRecebimentoTitulo>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.dsBandeira).AsQueryable <tbRecebimentoTitulo>();
                }
                break;

            case CAMPOS.VLVENDA:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.vlVenda).AsQueryable <tbRecebimentoTitulo>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.vlVenda).AsQueryable <tbRecebimentoTitulo>();
                }
                break;

            case CAMPOS.QTPARCELAS:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.qtParcelas).AsQueryable <tbRecebimentoTitulo>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.qtParcelas).AsQueryable <tbRecebimentoTitulo>();
                }
                break;

            case CAMPOS.DTTITULO:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.dtTitulo).AsQueryable <tbRecebimentoTitulo>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.dtTitulo).AsQueryable <tbRecebimentoTitulo>();
                }
                break;

            case CAMPOS.VLPARCELA:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.vlParcela).AsQueryable <tbRecebimentoTitulo>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.vlParcela).AsQueryable <tbRecebimentoTitulo>();
                }
                break;

            case CAMPOS.NRPARCELA:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.nrParcela).AsQueryable <tbRecebimentoTitulo>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.nrParcela).AsQueryable <tbRecebimentoTitulo>();
                }
                break;
            }
            #endregion

            return(entity);
        }
コード例 #6
0
        /// <summary>
        /// Get TbContaCorrente_tbLoginAdquirenteEmpresa/TbContaCorrente_tbLoginAdquirenteEmpresa
        /// </summary>
        /// <param name="colecao"></param>
        /// <param name="campo"></param>
        /// <param name="orderby"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageNumber"></param>
        /// <param name="queryString"></param>
        /// <returns></returns>
        private static IQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa> getQuery(painel_taxservices_dbContext _db, int colecao, int campo, int orderby, int pageSize, int pageNumber, Dictionary <string, string> queryString)
        {
            // DEFINE A QUERY PRINCIPAL
            var entity = _db.tbContaCorrente_tbLoginAdquirenteEmpresas.AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();

            #region WHERE - ADICIONA OS FILTROS A QUERY

            // ADICIONA OS FILTROS A QUERY
            foreach (var item in queryString)
            {
                int    key        = Convert.ToInt16(item.Key);
                CAMPOS filtroEnum = (CAMPOS)key;
                switch (filtroEnum)
                {
                case CAMPOS.CDCONTACORRENTE:
                    Int32 cdContaCorrente = Convert.ToInt32(item.Value);
                    entity = entity.Where(e => e.cdContaCorrente == cdContaCorrente).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                    break;

                case CAMPOS.CDLOGINADQUIRENTEEMPRESA:
                    Int32 cdLoginAdquirenteEmpresa = Convert.ToInt32(item.Value);
                    entity = entity.Where(e => e.cdLoginAdquirenteEmpresa == cdLoginAdquirenteEmpresa).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                    break;

                case CAMPOS.DTINICIO:
                    DateTime dtInicio = Convert.ToDateTime(item.Value);
                    entity = entity.Where(e => e.dtInicio.Equals(dtInicio)).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                    break;

                case CAMPOS.DTFIM:
                    DateTime dtFim = Convert.ToDateTime(item.Value);
                    entity = entity.Where(e => e.dtFim.Equals(dtFim)).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                    break;

                // PERSONALIZADO
                case CAMPOS.DS_FANTASIA:
                    string ds_fantasia = Convert.ToString(item.Value);
                    if (ds_fantasia.Contains("%"))     // usa LIKE
                    {
                        string busca = ds_fantasia.Replace("%", "").ToString();
                        entity = entity.Where(e => e.tbLoginAdquirenteEmpresa.empresa.ds_fantasia.Contains(busca)).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                    }
                    else
                    {
                        entity = entity.Where(e => e.tbLoginAdquirenteEmpresa.empresa.ds_fantasia.Equals(ds_fantasia)).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                    }
                    break;

                //case CAMPOS.NMADQUIRENTE:
                //    string nome = Convert.ToString(item.Value);
                //    if (nome.Contains("%")) // usa LIKE
                //    {
                //        string busca = nome.Replace("%", "").ToString();
                //        entity = entity.Where(e => e.tbLoginAdquirenteEmpresa.tbAdquirente.dsAdquirente.Contains(busca)).AsQueryable<tbContaCorrente_tbLoginAdquirenteEmpresa>();
                //    }
                //    else
                //        entity = entity.Where(e => e.tbLoginAdquirenteEmpresa.tbAdquirente.dsAdquirente.Equals(nome)).AsQueryable<tbContaCorrente_tbLoginAdquirenteEmpresa>();
                //    break;
                case CAMPOS.DTVIGENCIA:
                    if (item.Value.Contains("|"))     // BETWEEN
                    {
                        string[] busca  = item.Value.Split('|');
                        DateTime dtIni  = DateTime.ParseExact(busca[0] + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        DateTime dtaFim = DateTime.ParseExact(busca[1] + " 23:59:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        entity = entity.Where(v => (v.dtInicio.Year < dtIni.Year || (v.dtInicio.Year == dtIni.Year && v.dtInicio.Month < dtIni.Month) || (v.dtInicio.Year == dtIni.Year && v.dtInicio.Month == dtIni.Month && v.dtInicio.Day <= dtIni.Day)) &&
                                              (v.dtFim == null || (v.dtFim.Value.Year > dtIni.Year || (v.dtFim.Value.Year == dtIni.Year && v.dtFim.Value.Month > dtIni.Month) || (v.dtFim.Value.Year == dtIni.Year && v.dtFim.Value.Month == dtIni.Month && v.dtFim.Value.Day >= dtIni.Day))) &&
                                              (v.dtInicio.Year < dtaFim.Year || (v.dtInicio.Year == dtaFim.Year && v.dtInicio.Month < dtaFim.Month) || (v.dtInicio.Year == dtaFim.Year && v.dtInicio.Month == dtaFim.Month && v.dtInicio.Day <= dtaFim.Day)) &&
                                              (v.dtFim == null || (v.dtFim.Value.Year > dtaFim.Year || (v.dtFim.Value.Year == dtaFim.Year && v.dtFim.Value.Month > dtaFim.Month) || (v.dtFim.Value.Year == dtaFim.Year && v.dtFim.Value.Month == dtaFim.Month && v.dtFim.Value.Day >= dtaFim.Day)))
                                              ).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                    }
                    else     // ANO + MES + DIA
                    {
                        string   busca = item.Value;
                        DateTime data  = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        entity = entity.Where(v => (v.dtInicio.Year < data.Year || (v.dtInicio.Year == data.Year && v.dtInicio.Month < data.Month) || (v.dtInicio.Year == data.Year && v.dtInicio.Month == data.Month && v.dtInicio.Day <= data.Day)) &&
                                              (v.dtFim == null || (v.dtFim.Value.Year > data.Year || (v.dtFim.Value.Year == data.Year && v.dtFim.Value.Month > data.Month) || (v.dtFim.Value.Year == data.Year && v.dtFim.Value.Month == data.Month && v.dtFim.Value.Day >= data.Day))) &&
                                              (v.dtInicio.Year < data.Year || (v.dtInicio.Year == data.Year && v.dtInicio.Month < data.Month) || (v.dtInicio.Year == data.Year && v.dtInicio.Month == data.Month && v.dtInicio.Day <= data.Day)) &&
                                              (v.dtFim == null || (v.dtFim.Value.Year > data.Year || (v.dtFim.Value.Year == data.Year && v.dtFim.Value.Month > data.Month) || (v.dtFim.Value.Year == data.Year && v.dtFim.Value.Month == data.Month && v.dtFim.Value.Day >= data.Day)))
                                              ).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                    }
                    break;

                case CAMPOS.ID_GRUPO:
                    Int32 id_grupo = Convert.ToInt32(item.Value);
                    entity = entity.Where(e => e.tbLoginAdquirenteEmpresa.empresa.id_grupo == id_grupo).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                    break;

                case CAMPOS.NU_CNPJ:
                    string nu_cnpj = Convert.ToString(item.Value);
                    entity = entity.Where(e => e.tbLoginAdquirenteEmpresa.nrCnpj.Equals(nu_cnpj)).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                    break;

                case CAMPOS.STLOGINADQUIRENTE:
                    byte stLoginAdquirente = Convert.ToByte(item.Value);
                    entity = entity.Where(e => e.tbLoginAdquirenteEmpresa.stLoginAdquirente == stLoginAdquirente).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                    break;

                case CAMPOS.CDADQUIRENTE:
                    Int32 cdAdquirente = Convert.ToInt32(item.Value);
                    entity = entity.Where(e => e.tbLoginAdquirenteEmpresa.cdAdquirente == cdAdquirente).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                    break;
                }
            }
            #endregion

            #region ORDER BY - ADICIONA A ORDENAÇÃO A QUERY
            // ADICIONA A ORDENAÇÃO A QUERY
            CAMPOS filtro = (CAMPOS)campo;
            switch (filtro)
            {
            case CAMPOS.CDCONTACORRENTE:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.cdContaCorrente).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.cdContaCorrente).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                }
                break;

            case CAMPOS.CDLOGINADQUIRENTEEMPRESA:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.cdLoginAdquirenteEmpresa).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.cdLoginAdquirenteEmpresa).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                }
                break;

            case CAMPOS.DTINICIO:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.dtInicio).ThenBy(e => e.tbLoginAdquirenteEmpresa.empresa.ds_fantasia).ThenBy(e => e.tbLoginAdquirenteEmpresa.tbAdquirente.dsAdquirente).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.dtInicio).ThenBy(e => e.tbLoginAdquirenteEmpresa.empresa.ds_fantasia).ThenBy(e => e.tbLoginAdquirenteEmpresa.tbAdquirente.dsAdquirente).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                }
                break;

            case CAMPOS.DTFIM:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.dtFim).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.dtFim).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                }
                break;

            // PERSONALIZADO
            case CAMPOS.DS_FANTASIA:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.tbLoginAdquirenteEmpresa.empresa.ds_fantasia).ThenBy(e => e.tbLoginAdquirenteEmpresa.tbAdquirente.dsAdquirente).ThenByDescending(e => e.dtInicio).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.tbLoginAdquirenteEmpresa.empresa.ds_fantasia).ThenByDescending(e => e.tbLoginAdquirenteEmpresa.tbAdquirente.dsAdquirente).ThenByDescending(e => e.dtInicio).AsQueryable <tbContaCorrente_tbLoginAdquirenteEmpresa>();
                }
                break;
                //case CAMPOS.DSADQUIRENTE:
                //    if (orderby == 0) entity = entity.OrderBy(e => e.tbLoginAdquirenteEmpresa.tbAdquirente.dsAdquirente).ThenBy(e => e.tbLoginAdquirenteEmpresa.empresa.ds_fantasia).ThenByDescending(e => e.dtInicio).AsQueryable<tbContaCorrente_tbLoginAdquirenteEmpresa>();
                //    else entity = entity.OrderByDescending(e => e.tbLoginAdquirenteEmpresa.tbAdquirente.dsAdquirente).ThenByDescending(e => e.tbLoginAdquirenteEmpresa.empresa.ds_fantasia).ThenByDescending(e => e.dtInicio).AsQueryable<tbContaCorrente_tbLoginAdquirenteEmpresa>();
                //    break;
            }
            #endregion

            return(entity);
        }
コード例 #7
0
        /// <summary>
        /// Altera tbContaCorrente_tbLoginAdquirenteEmpresa
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static void Update(string token, tbContaCorrente_tbLoginAdquirenteEmpresa param, 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();
            try
            {
                tbContaCorrente_tbLoginAdquirenteEmpresa value = _db.tbContaCorrente_tbLoginAdquirenteEmpresas
                                                                 .Where(e => e.cdContaCorrente == param.cdContaCorrente)
                                                                 .Where(e => e.cdLoginAdquirenteEmpresa == param.cdLoginAdquirenteEmpresa)
                                                                 .Where(e => e.dtInicio.Equals(param.dtInicio))
                                                                 .FirstOrDefault();
                if (value == null)
                {
                    throw new Exception("Vigência inválida!");
                }

                if (conflitoPeriodoVigencia(param) != null)
                {
                    throw new Exception("Conflito de período de vigência");
                }

                // Só altera a data fim => SEMPRE TEM QUE SER ENVIADO A DATA FIM, POIS ESTÁ PODE SER SETADA PARA NULL
                if (!param.dtFim.Equals(value.dtFim))
                {
                    value.dtFim = param.dtFim;
                    _db.SaveChanges();
                }
            }
            catch (Exception e)
            {
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao alterar 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();
                }
            }
        }
コード例 #8
0
        // GET api/contador
        public api.Models.Object.Contador Get(string token, int colecao = 0, int campo = 0, int orderBy = 0, int pageSize = 0, int pageNumber = 0)
        {
            try
            {
                using (var _db = new painel_taxservices_dbContext())
                {
                    _db.Configuration.ProxyCreationEnabled = false;



                    string script = @"
                                        
                                    SELECT

                                    (
                                    SELECT
	                                    COUNT(1)
                                    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
                                    WHERE
	                                    pos.LogExecution.statusExecution = 0
                                    ) AS execucao
                                    ,
                                    (
                                    SELECT
	                                    COUNT(1)
                                    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
                                    WHERE
	                                    pos.LogExecution.statusExecution = 3
	                                    AND MONTH(pos.LogExecution.dtaExecucaoProxima) = MONTH(GETDATE())
	                                    AND YEAR(pos.LogExecution.dtaExecucaoProxima) = YEAR(GETDATE())
                                    ) as erro
                                    ,
                                    (
                                    SELECT
                                    COUNT(1)
                                    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
                                    WHERE
                                    pos.LogExecution.statusExecution = 7
	                                    AND  pos.LogExecution.dtaExecucaoProxima  <= (CONVERT(VARCHAR(25), GETDATE(), 112) + ' 23:59:00')
                                    ) fila
                                    ,
                                    (SELECT
	                                        COUNT(1)
                                    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
                                    WHERE
	                                    pos.LogExecution.statusExecution = 1
	                                    AND MONTH(pos.LogExecution.dtaExecucaoProxima) = MONTH(GETDATE())
	                                    AND YEAR(pos.LogExecution.dtaExecucaoProxima) = YEAR(GETDATE())
                                    ) AS sucesso
                                    ";

                    api.Models.Object.Contador log = _db.Database.SqlQuery <api.Models.Object.Contador>(script).FirstOrDefault();

                    return(log);
                }
            }
            catch
            {
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }
        }
コード例 #9
0
        /// <summary>
        /// Retorna Webpages_Membership/Webpages_Membership
        /// </summary>
        /// <returns></returns>
        public static Retorno Get(string token, int colecao = 0, int campo = 0, int orderBy = 0, int pageSize = 0, int pageNumber = 0, Dictionary <string, string> queryString = null, painel_taxservices_dbContext _dbContext = null)
        {
            painel_taxservices_dbContext _db;

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

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

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

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


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

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

                // COLEÇÃO DE RETORNO
                if (colecao == 1)
                {
                    CollectionWebpages_Membership = query.Select(e => new
                    {
                        UserId                                  = e.UserId,
                        CreateDate                              = e.CreateDate,
                        ConfirmationToken                       = e.ConfirmationToken,
                        IsConfirmed                             = e.IsConfirmed,
                        LastPasswordFailureDate                 = e.LastPasswordFailureDate,
                        PasswordFailuresSinceLastSuccess        = e.PasswordFailuresSinceLastSuccess,
                        Password                                = e.Password,
                        PasswordChangedDate                     = e.PasswordChangedDate,
                        PasswordSalt                            = e.PasswordSalt,
                        PasswordVerificationToken               = e.PasswordVerificationToken,
                        PasswordVerificationTokenExpirationDate = e.PasswordVerificationTokenExpirationDate,
                    }).ToList <dynamic>();
                }
                else if (colecao == 0)
                {
                    CollectionWebpages_Membership = query.Select(e => new
                    {
                        UserId                                  = e.UserId,
                        CreateDate                              = e.CreateDate,
                        ConfirmationToken                       = e.ConfirmationToken,
                        IsConfirmed                             = e.IsConfirmed,
                        LastPasswordFailureDate                 = e.LastPasswordFailureDate,
                        PasswordFailuresSinceLastSuccess        = e.PasswordFailuresSinceLastSuccess,
                        Password                                = e.Password,
                        PasswordChangedDate                     = e.PasswordChangedDate,
                        PasswordSalt                            = e.PasswordSalt,
                        PasswordVerificationToken               = e.PasswordVerificationToken,
                        PasswordVerificationTokenExpirationDate = e.PasswordVerificationTokenExpirationDate,
                    }).ToList <dynamic>();
                }

                transaction.Commit();

                retorno.Registros = CollectionWebpages_Membership;

                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 membership" : 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();
                }
            }
        }
コード例 #10
0
        /// <summary>
        /// Altera tbLogCarga
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static void Update(string token, tbLogCarga param, 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();

            try
            {
                tbLogCarga value = _db.tbLogCargas
                                   .Where(e => e.idLogCarga.Equals(param.idLogCarga))
                                   .First <tbLogCarga>();
                if (param.idLogCarga != null && param.idLogCarga != value.idLogCarga)
                {
                    value.idLogCarga = param.idLogCarga;
                }
                if (param.dtCompetencia != null && param.dtCompetencia != value.dtCompetencia)
                {
                    value.dtCompetencia = param.dtCompetencia;
                }
                if (param.nrCNPJ != null && param.nrCNPJ != value.nrCNPJ)
                {
                    value.nrCNPJ = param.nrCNPJ;
                }
                if (param.cdAdquirente != null && param.cdAdquirente != value.cdAdquirente)
                {
                    value.cdAdquirente = param.cdAdquirente;
                }
                if (param.flStatusVendasCredito != null && param.flStatusVendasCredito != value.flStatusVendasCredito)
                {
                    value.flStatusVendasCredito = param.flStatusVendasCredito;
                }
                if (param.flStatusVendasDebito != null && param.flStatusVendasDebito != value.flStatusVendasDebito)
                {
                    value.flStatusVendasDebito = param.flStatusVendasDebito;
                }
                if (param.flStatusPagosCredito != null && param.flStatusPagosCredito != value.flStatusPagosCredito)
                {
                    value.flStatusPagosCredito = param.flStatusPagosCredito;
                }
                if (param.flStatusPagosDebito != null && param.flStatusPagosDebito != value.flStatusPagosDebito)
                {
                    value.flStatusPagosDebito = param.flStatusPagosDebito;
                }
                if (param.flStatusPagosAntecipacao != null && param.flStatusPagosAntecipacao != value.flStatusPagosAntecipacao)
                {
                    value.flStatusPagosAntecipacao = param.flStatusPagosAntecipacao;
                }
                if (param.flStatusReceber != null && param.flStatusReceber != value.flStatusReceber)
                {
                    value.flStatusReceber = param.flStatusReceber;
                }
                if (param.vlVendaCredito != null && param.vlVendaCredito != value.vlVendaCredito)
                {
                    value.vlVendaCredito = param.vlVendaCredito;
                }
                if (param.vlVendaDebito != null && param.vlVendaDebito != value.vlVendaDebito)
                {
                    value.vlVendaDebito = param.vlVendaDebito;
                }
                if (param.vlPagosCredito != null && param.vlPagosCredito != value.vlPagosCredito)
                {
                    value.vlPagosCredito = param.vlPagosCredito;
                }
                if (param.vlPagosDebito != null && param.vlPagosDebito != value.vlPagosDebito)
                {
                    value.vlPagosDebito = param.vlPagosDebito;
                }
                if (param.vlPagosAntecipacao != null && param.vlPagosAntecipacao != value.vlPagosAntecipacao)
                {
                    value.vlPagosAntecipacao = param.vlPagosAntecipacao;
                }
                _db.SaveChanges();
                transaction.Commit();
            }
            catch (Exception e)
            {
                transaction.Rollback();
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao realizar a baixa automática" : 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();
                }
            }
        }
コード例 #11
0
        public static tbLogAcessoUsuario New(string token, string dsJson, string dsMethod, painel_taxservices_dbContext _dbContext = null)
        {
            painel_taxservices_dbContext _db;

            if (_dbContext == null)
            {
                _db = new painel_taxservices_dbContext();
            }
            else
            {
                _db = _dbContext;
            }
            try
            {
                bool Mobile = Bibliotecas.Device.IsMobile();

                tbLogAcessoUsuario log = new tbLogAcessoUsuario();
                log.idUser = Bibliotecas.Permissoes.GetIdUser(token, _db);
                log.dsUrl  = HttpContext.Current.Request.Url.Segments[1] + HttpContext.Current.Request.Url.Segments[2];

                string afterUrl = HttpContext.Current.Request.RawUrl.Replace((HttpContext.Current.Request.Url.Segments[0] + HttpContext.Current.Request.Url.Segments[1] + HttpContext.Current.Request.Url.Segments[2]), "");

                int index = afterUrl.IndexOf('?');
                if (index > -1)
                {
                    // tem filtros
                    log.dsFiltros    = afterUrl.Substring(index);
                    log.dsParametros = afterUrl.Substring(0, index);
                }
                else
                {
                    // Não tem filtros
                    log.dsFiltros    = String.Empty;
                    log.dsParametros = afterUrl;
                }
                //log.dsFiltros = HttpContext.Current.Request.RawUrl.LastIndexOf('?') > 0 ? HttpContext.Current.Request.RawUrl.Remove(0, HttpContext.Current.Request.RawUrl.LastIndexOf('?')) : String.Empty;

                log.dtAcesso     = DateTime.Now;
                log.dsAplicacao  = Mobile ? "M" : "P";
                log.dsMethod     = dsMethod;
                log.idController = _db.LogAcesso1.Where(l => l.idUsers == log.idUser)
                                   .Where(l => l.flMobile == Mobile)
                                   .OrderByDescending(l => l.dtAcesso)
                                   .Select(l => l.idController)
                                   .FirstOrDefault();
                /* Campos alimentados no controller*/
                //log.codResposta = data.codResposta;
                //log.msgErro = data.msgErro;
                log.dsJson      = dsJson != null ? dsJson : String.Empty;
                log.dsUserAgent = HttpContext.Current.Request.UserAgent;
                return(log);
            }
            catch (Exception e)
            {
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao salvar log" : 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();
                }
            }
        }
コード例 #12
0
        /// <summary>
        /// Get TbLogCarga/TbLogCarga
        /// </summary>
        /// <param name="colecao"></param>
        /// <param name="campo"></param>
        /// <param name="orderby"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageNumber"></param>
        /// <param name="queryString"></param>
        /// <returns></returns>
        private static IQueryable <tbLogCarga> getQuery(painel_taxservices_dbContext _db, int colecao, int campo, int orderby, int pageSize, int pageNumber, Dictionary <string, string> queryString)
        {
            // DEFINE A QUERY PRINCIPAL
            var entity = _db.tbLogCargas.AsQueryable();

            #region WHERE - ADICIONA OS FILTROS A QUERY

            // ADICIONA OS FILTROS A QUERY
            foreach (var item in queryString)
            {
                int    key        = Convert.ToInt16(item.Key);
                CAMPOS filtroEnum = (CAMPOS)key;
                switch (filtroEnum)
                {
                case CAMPOS.IDLOGCARGA:
                    Int32 idLogCarga = Convert.ToInt32(item.Value);
                    entity = entity.Where(e => e.idLogCarga.Equals(idLogCarga)).AsQueryable <tbLogCarga>();
                    break;

                case CAMPOS.DTCOMPETENCIA:
                    if (item.Value.Contains("|"))     // BETWEEN
                    {
                        string[] busca  = item.Value.Split('|');
                        DateTime dtaIni = DateTime.ParseExact(busca[0] + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        DateTime dtaFim = DateTime.ParseExact(busca[1] + " 23:59:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        entity = entity.Where(e => e.dtCompetencia > dtaIni && e.dtCompetencia < dtaFim).AsQueryable <tbLogCarga>();
                    }
                    else if (item.Value.Length == 6)
                    {
                        string   busca  = item.Value + "01";
                        DateTime dtaIni = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        entity = entity.Where(e => e.dtCompetencia.Year == dtaIni.Year && e.dtCompetencia.Month == dtaIni.Month);
                    }
                    else
                    {
                        string   busca  = item.Value;
                        DateTime dtaIni = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        entity = entity.Where(e => e.dtCompetencia.Year == dtaIni.Year && e.dtCompetencia.Month == dtaIni.Month && e.dtCompetencia.Day == dtaIni.Day).AsQueryable <tbLogCarga>();
                    }
                    break;

                case CAMPOS.NRCNPJ:
                    string nrCNPJ = Convert.ToString(item.Value);
                    entity = entity.Where(e => e.nrCNPJ.Equals(nrCNPJ)).AsQueryable <tbLogCarga>();
                    break;

                case CAMPOS.CDADQUIRENTE:
                    Int32 cdAdquirente = Convert.ToInt32(item.Value);
                    entity = entity.Where(e => e.cdAdquirente.Equals(cdAdquirente)).AsQueryable <tbLogCarga>();
                    break;

                case CAMPOS.FLSTATUSVENDASCREDITO:
                    Boolean flStatusVendasCredito = Convert.ToBoolean(item.Value);
                    entity = entity.Where(e => e.flStatusVendasCredito.Equals(flStatusVendasCredito)).AsQueryable <tbLogCarga>();
                    break;

                case CAMPOS.FLSTATUSVENDASDEBITO:
                    Boolean flStatusVendasDebito = Convert.ToBoolean(item.Value);
                    entity = entity.Where(e => e.flStatusVendasDebito.Equals(flStatusVendasDebito)).AsQueryable <tbLogCarga>();
                    break;

                case CAMPOS.FLSTATUSPAGOSCREDITO:
                    Boolean flStatusPagosCredito = Convert.ToBoolean(item.Value);
                    entity = entity.Where(e => e.flStatusPagosCredito.Equals(flStatusPagosCredito)).AsQueryable <tbLogCarga>();
                    break;

                case CAMPOS.FLSTATUSPAGOSDEBITO:
                    Boolean flStatusPagosDebito = Convert.ToBoolean(item.Value);
                    entity = entity.Where(e => e.flStatusPagosDebito.Equals(flStatusPagosDebito)).AsQueryable <tbLogCarga>();
                    break;

                case CAMPOS.FLSTATUSPAGOSANTECIPACAO:
                    Boolean flStatusPagosAntecipacao = Convert.ToBoolean(item.Value);
                    entity = entity.Where(e => e.flStatusPagosAntecipacao.Equals(flStatusPagosAntecipacao)).AsQueryable <tbLogCarga>();
                    break;

                case CAMPOS.FLSTATUSRECEBER:
                    Boolean flStatusReceber = Convert.ToBoolean(item.Value);
                    entity = entity.Where(e => e.flStatusReceber.Equals(flStatusReceber)).AsQueryable <tbLogCarga>();
                    break;

                case CAMPOS.VLVENDACREDITO:
                    decimal vlVendaCredito = Convert.ToDecimal(item.Value);
                    entity = entity.Where(e => e.vlVendaCredito.Equals(vlVendaCredito)).AsQueryable <tbLogCarga>();
                    break;

                case CAMPOS.VLVENDADEBITO:
                    decimal vlVendaDebito = Convert.ToDecimal(item.Value);
                    entity = entity.Where(e => e.vlVendaDebito.Equals(vlVendaDebito)).AsQueryable <tbLogCarga>();
                    break;

                case CAMPOS.VLPAGOSCREDITO:
                    decimal vlPagosCredito = Convert.ToDecimal(item.Value);
                    entity = entity.Where(e => e.vlPagosCredito.Equals(vlPagosCredito)).AsQueryable <tbLogCarga>();
                    break;

                case CAMPOS.VLPAGOSDEBITO:
                    decimal vlPagosDebito = Convert.ToDecimal(item.Value);
                    entity = entity.Where(e => e.vlPagosDebito.Equals(vlPagosDebito)).AsQueryable <tbLogCarga>();
                    break;

                case CAMPOS.VLPAGOSANTECIPACAO:
                    decimal vlPagosAntecipacao = Convert.ToDecimal(item.Value);
                    entity = entity.Where(e => e.vlPagosAntecipacao.Equals(vlPagosAntecipacao)).AsQueryable <tbLogCarga>();
                    break;

                // PERSONALIZADO
                case CAMPOS.ID_GRUPO:
                    Int32 id_grupo = Convert.ToInt32(item.Value);
                    entity = entity.Where(e => e.empresa.id_grupo == id_grupo).AsQueryable <tbLogCarga>();
                    break;
                }
            }
            #endregion

            #region ORDER BY - ADICIONA A ORDENAÇÃO A QUERY
            // ADICIONA A ORDENAÇÃO A QUERY
            CAMPOS filtro = (CAMPOS)campo;
            switch (filtro)
            {
            case CAMPOS.IDLOGCARGA:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.idLogCarga).AsQueryable <tbLogCarga>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.idLogCarga).AsQueryable <tbLogCarga>();
                }
                break;

            case CAMPOS.DTCOMPETENCIA:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.dtCompetencia).AsQueryable <tbLogCarga>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.dtCompetencia).AsQueryable <tbLogCarga>();
                }
                break;

            case CAMPOS.NRCNPJ:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.nrCNPJ).AsQueryable <tbLogCarga>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.nrCNPJ).AsQueryable <tbLogCarga>();
                }
                break;

            case CAMPOS.CDADQUIRENTE:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.cdAdquirente).AsQueryable <tbLogCarga>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.cdAdquirente).AsQueryable <tbLogCarga>();
                }
                break;

            case CAMPOS.FLSTATUSVENDASCREDITO:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.flStatusVendasCredito).AsQueryable <tbLogCarga>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.flStatusVendasCredito).AsQueryable <tbLogCarga>();
                }
                break;

            case CAMPOS.FLSTATUSVENDASDEBITO:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.flStatusVendasDebito).AsQueryable <tbLogCarga>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.flStatusVendasDebito).AsQueryable <tbLogCarga>();
                }
                break;

            case CAMPOS.FLSTATUSPAGOSCREDITO:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.flStatusPagosCredito).AsQueryable <tbLogCarga>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.flStatusPagosCredito).AsQueryable <tbLogCarga>();
                }
                break;

            case CAMPOS.FLSTATUSPAGOSDEBITO:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.flStatusPagosDebito).AsQueryable <tbLogCarga>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.flStatusPagosDebito).AsQueryable <tbLogCarga>();
                }
                break;

            case CAMPOS.FLSTATUSPAGOSANTECIPACAO:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.flStatusPagosAntecipacao).AsQueryable <tbLogCarga>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.flStatusPagosAntecipacao).AsQueryable <tbLogCarga>();
                }
                break;

            case CAMPOS.FLSTATUSRECEBER:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.flStatusReceber).AsQueryable <tbLogCarga>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.flStatusReceber).AsQueryable <tbLogCarga>();
                }
                break;

            case CAMPOS.VLVENDACREDITO:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.vlVendaCredito).AsQueryable <tbLogCarga>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.vlVendaCredito).AsQueryable <tbLogCarga>();
                }
                break;

            case CAMPOS.VLVENDADEBITO:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.vlVendaDebito).AsQueryable <tbLogCarga>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.vlVendaDebito).AsQueryable <tbLogCarga>();
                }
                break;

            case CAMPOS.VLPAGOSCREDITO:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.vlPagosCredito).AsQueryable <tbLogCarga>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.vlPagosCredito).AsQueryable <tbLogCarga>();
                }
                break;

            case CAMPOS.VLPAGOSDEBITO:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.vlPagosDebito).AsQueryable <tbLogCarga>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.vlPagosDebito).AsQueryable <tbLogCarga>();
                }
                break;

            case CAMPOS.VLPAGOSANTECIPACAO:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.vlPagosAntecipacao).AsQueryable <tbLogCarga>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.vlPagosAntecipacao).AsQueryable <tbLogCarga>();
                }
                break;
            }
            #endregion

            return(entity);
        }
コード例 #13
0
        /// <summary>
        /// Retorna TbLogCarga/TbLogCarga
        /// </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> CollectionTbLogCarga = new List <dynamic>();
                Retorno        retorno = new Retorno();

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


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


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

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

                // COLEÇÃO DE RETORNO
                if (colecao == 1)
                {
                    CollectionTbLogCarga = query.Select(e => new
                    {
                        idLogCarga               = e.idLogCarga,
                        dtCompetencia            = e.dtCompetencia,
                        nrCNPJ                   = e.nrCNPJ,
                        cdAdquirente             = e.cdAdquirente,
                        flStatusVendasCredito    = e.flStatusVendasCredito,
                        flStatusVendasDebito     = e.flStatusVendasDebito,
                        flStatusPagosCredito     = e.flStatusPagosCredito,
                        flStatusPagosDebito      = e.flStatusPagosDebito,
                        flStatusPagosAntecipacao = e.flStatusPagosAntecipacao,
                        flStatusReceber          = e.flStatusReceber,
                        vlVendaCredito           = e.vlVendaCredito,
                        vlVendaDebito            = e.vlVendaDebito,
                        vlPagosCredito           = e.vlPagosCredito,
                        vlPagosDebito            = e.vlPagosDebito,
                        vlPagosAntecipacao       = e.vlPagosAntecipacao,
                    }).ToList <dynamic>();
                }
                else if (colecao == 0)
                {
                    CollectionTbLogCarga = query.Select(e => new
                    {
                        idLogCarga               = e.idLogCarga,
                        dtCompetencia            = e.dtCompetencia,
                        nrCNPJ                   = e.nrCNPJ,
                        cdAdquirente             = e.cdAdquirente,
                        flStatusVendasCredito    = e.flStatusVendasCredito,
                        flStatusVendasDebito     = e.flStatusVendasDebito,
                        flStatusPagosCredito     = e.flStatusPagosCredito,
                        flStatusPagosDebito      = e.flStatusPagosDebito,
                        flStatusPagosAntecipacao = e.flStatusPagosAntecipacao,
                        flStatusReceber          = e.flStatusReceber,
                        vlVendaCredito           = e.vlVendaCredito,
                        vlVendaDebito            = e.vlVendaDebito,
                        vlPagosCredito           = e.vlPagosCredito,
                        vlPagosDebito            = e.vlPagosDebito,
                        vlPagosAntecipacao       = e.vlPagosAntecipacao,
                    }).ToList <dynamic>();
                }

                transaction.Commit();

                retorno.Registros = CollectionTbLogCarga;

                return(retorno);
            }
            catch (Exception e)
            {
                transaction.Rollback();
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao realizar a baixa automática" : 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();
                }
            }
        }
コード例 #14
0
        // GET api/fila
        public List <api.Models.Object.LogExecucao> Get(string token, int colecao = 0, int campo = 0, int orderBy = 0, int pageSize = 0, int pageNumber = 0)
        {
            try
            {
                using (var _db = new painel_taxservices_dbContext())
                {
                    _db.Configuration.ProxyCreationEnabled = false;



                    string script = @"
                                        SELECT
	                                        TOP ("     + pageSize + @") *
                                        FROM
	                                        (
		                                        SELECT
			                                        pos.LogExecution.id AS idLogExecucao,
			                                        pos.LogExecution.qtdTransacoes AS quantodade,
			                                        pos.LogExecution.vlTotalTransacoes AS valor_total,
			                                        pos.LogExecution.statusExecution AS status,
			                                        CONVERT (
				                                        nvarchar (MAX),
				                                        pos.LogExecution.dtaFiltroTransacoes,
				                                        103
			                                        ) AS data_carga,
			                                        CONVERT (
				                                        nvarchar (MAX),
				                                        pos.LogExecution.dtaExecucaoInicio,
				                                        103
			                                        ) AS data_inicio,
			                                        cliente.empresa.ds_fantasia AS empresa,
			                                        pos.Operadora.nmOperadora AS adquirente,
			                                        pos.Operadora.id AS idAdquirente,
			                                        row_number () OVER (

				                                        ORDER BY
					                                        pos.LogExecution.dtaExecucaoProxima ASC
			                                        ) AS [row_number]
		                                        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
		                                        WHERE
			                                        pos.LogExecution.statusExecution = 7
		                                        AND pos.LogExecution.dtaExecucaoProxima <= (
			                                        CONVERT (VARCHAR(25), GETDATE(), 112) + ' 23:59:00'
		                                        )
	                                        ) AS [Extent1]
                                        WHERE
	                                        [Extent1].[row_number] > "     + (pageNumber * pageSize);

                    if (colecao == 0)
                    {
                        if (orderBy == 0)
                        {
                            script += " ORDER BY [Extent1].row_number ASC ";
                        }
                        else
                        {
                            script += " ORDER BY [Extent1].row_number DESC ";
                        }
                    }
                    else
                    {
                        if (orderBy == 0)
                        {
                            script += " ORDER BY [Extent1].idLogExecucao ASC ";
                        }
                        else
                        {
                            script += " ORDER BY [Extent1].idLogExecucao DESC ";
                        }
                    }


                    List <api.Models.Object.LogExecucao> log = _db.Database.SqlQuery <api.Models.Object.LogExecucao>(script).ToList();

                    return(log);
                }
            }
            catch
            {
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }
        }
コード例 #15
0
        /**
         * Procura por conflitos de período de vigência a partir do parâmetro
         * Retorna null se não houve conflito. Caso contrário, retorna o registro ao qual o período conflita
         */
        private static tbContaCorrente_tbLoginAdquirenteEmpresa conflitoPeriodoVigencia(tbContaCorrente_tbLoginAdquirenteEmpresa param, painel_taxservices_dbContext _dbContext = null)
        {
            painel_taxservices_dbContext _db;

            if (_dbContext == null)
            {
                _db = new painel_taxservices_dbContext();
            }
            else
            {
                _db = _dbContext;
            }
            try
            {
                // Avalia se, para o mesmo cdContaCorrente e cdLoginAdquirenteEmpresa
                // o período informado já consta
                List <tbContaCorrente_tbLoginAdquirenteEmpresa> values = _db.tbContaCorrente_tbLoginAdquirenteEmpresas
                                                                         .Where(e => e.cdContaCorrente == param.cdContaCorrente)
                                                                         .Where(e => e.cdLoginAdquirenteEmpresa == param.cdLoginAdquirenteEmpresa)
                                                                         .ToList <tbContaCorrente_tbLoginAdquirenteEmpresa>();

                foreach (var value in values)
                {
                    // Não avalia o período se o parâmetro for mesmo elemento "value" corrente
                    if (value.cdContaCorrente == param.cdContaCorrente &&
                        value.cdLoginAdquirenteEmpresa == param.cdLoginAdquirenteEmpresa &&
                        value.dtInicio.Equals(param.dtInicio))
                    {
                        continue;
                    }

                    if (value.dtFim != null)
                    {
                        // Não é o vigente de dtFim nulo

                        if (param.dtFim == null)
                        {
                            // Data início do parâmetro deve ser superior a dtFim do encontrado na base
                            if (param.dtInicio.Year < Convert.ToDateTime(value.dtFim).Year ||
                                (param.dtInicio.Year == Convert.ToDateTime(value.dtFim).Year&& param.dtInicio.Month < Convert.ToDateTime(value.dtFim).Month) ||
                                (param.dtInicio.Year == Convert.ToDateTime(value.dtFim).Year&& param.dtInicio.Month == Convert.ToDateTime(value.dtFim).Month&& param.dtInicio.Day <= Convert.ToDateTime(value.dtFim).Day))
                            {
                                return(value);
                            }
                        }
                        else
                        {
                            // Avalia intervalos por completo => compara desconsiderando os horários
                            DateTime paramInicio = new DateTime(param.dtInicio.Year, param.dtInicio.Month, param.dtInicio.Day);
                            DateTime paramFim    = new DateTime(Convert.ToDateTime(param.dtInicio).Year, Convert.ToDateTime(param.dtFim).Month, Convert.ToDateTime(param.dtFim).Day);
                            DateTime valueInicio = new DateTime(value.dtInicio.Year, value.dtInicio.Month, value.dtInicio.Day);
                            DateTime valueFim    = new DateTime(Convert.ToDateTime(value.dtInicio).Year, Convert.ToDateTime(value.dtFim).Month, Convert.ToDateTime(value.dtFim).Day);

                            // Início de um não pode estar dentro do intervalo do outro
                            if (paramInicio.Ticks >= valueInicio.Ticks && paramInicio.Ticks <= valueFim.Ticks)
                            {
                                return(value);
                            }
                            if (valueInicio.Ticks >= paramInicio.Ticks && valueInicio.Ticks <= paramFim.Ticks)
                            {
                                return(value);
                            }

                            // Fim de um não pode estar dentro do intervalo do outro
                            if (paramFim.Ticks >= valueInicio.Ticks && paramFim.Ticks <= valueFim.Ticks)
                            {
                                return(value);
                            }
                            if (valueFim.Ticks >= paramInicio.Ticks && valueFim.Ticks <= paramFim.Ticks)
                            {
                                return(value);
                            }
                        }
                    }
                    else
                    {
                        // Já existe um vigente com dtFim nulo => período de dtInicio até oo

                        if (param.dtFim == null)
                        {
                            return(value); // Só pode existir um com dtFim nulo
                        }
                        // Data início do parâmetro deve ser inferior a do encontrado na base
                        if (param.dtInicio.Year > value.dtInicio.Year ||
                            (param.dtInicio.Year == value.dtInicio.Year && param.dtInicio.Month > value.dtInicio.Month) ||
                            (param.dtInicio.Year == value.dtInicio.Year && param.dtInicio.Month == value.dtInicio.Month && param.dtInicio.Day >= value.dtInicio.Day) ||
                            // Data fim do parâmetro deve ser inferior a dtInício do encontrado na base
                            Convert.ToDateTime(param.dtFim).Year > value.dtInicio.Year ||
                            (Convert.ToDateTime(param.dtFim).Year == value.dtInicio.Year && Convert.ToDateTime(param.dtFim).Month > value.dtInicio.Month) ||
                            (Convert.ToDateTime(param.dtFim).Year == value.dtInicio.Year && Convert.ToDateTime(param.dtFim).Month == value.dtInicio.Month && Convert.ToDateTime(param.dtFim).Day >= value.dtInicio.Day))
                        {
                            return(value);
                        }
                    }
                }
                // Não teve conflito de período de vigência
                return(null);
            }
            catch (Exception e)
            {
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao verificar conflito em 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();
                }
            }
        }
コード例 #16
0
        /// <summary>
        /// Altera webpages_Membership
        /// Alterar senha do usuário logado
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static void Update(string token, Models.Object.AlterarSenha param, painel_taxservices_dbContext _dbContext = null)
        {
            painel_taxservices_dbContext _db;

            if (_dbContext == null)
            {
                _db = new painel_taxservices_dbContext();
            }
            else
            {
                _db = _dbContext;
            }
            try
            {
                Int32 idUser = 0;

                if (param.UserId == -1)
                {
                    idUser = Permissoes.GetIdUser(token);
                }
                else
                {
                    idUser = param.UserId;
                }

                var value = _db.webpages_Users
                            .Where(e => e.id_users.Equals(idUser))
                            .FirstOrDefault();

                if (value != null)
                {
                    string resetToken = WebSecurity.GeneratePasswordResetToken(value.ds_login, 2);
                    if (param.NovaSenha == "")
                    {
                        WebSecurity.ResetPassword(resetToken, "atos123");
                    }
                    else if (param.SenhaAtual != null)
                    {
                        if (WebSecurity.Login(value.ds_login, param.SenhaAtual, persistCookie: false))
                        {
                            WebSecurity.ResetPassword(resetToken, param.NovaSenha);
                        }
                        else
                        {
                            throw new Exception("Senha inválida!");
                        }
                    }
                    else
                    {
                        throw new Exception("Operação inválida!");
                    }
                }
                else
                {
                    throw new Exception("Usuário inválido!");
                }
            }
            catch (Exception e)
            {
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao alterar membership" : 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();
                }
            }
        }
コード例 #17
0
        /// <summary>
        /// Adiciona nova TbContaCorrente_tbLoginAdquirenteEmpresa
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static Int32 Add(string token, tbContaCorrente_tbLoginAdquirenteEmpresa param, 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();

            try
            {
                tbContaCorrente_tbLoginAdquirenteEmpresa value = _db.tbContaCorrente_tbLoginAdquirenteEmpresas
                                                                 .Where(e => e.cdContaCorrente == param.cdContaCorrente)
                                                                 .Where(e => e.cdLoginAdquirenteEmpresa == param.cdLoginAdquirenteEmpresa)
                                                                 .Where(e => e.dtInicio.Equals(param.dtInicio))
                                                                 .FirstOrDefault();
                if (value != null)
                {
                    throw new Exception("Vigência já existe!");
                }
                if (conflitoPeriodoVigencia(param) != null)
                {
                    throw new Exception("Conflito de período de vigência");
                }
                _db.tbContaCorrente_tbLoginAdquirenteEmpresas.Add(param);
                _db.SaveChanges();
                transaction.Commit();
                return(param.cdContaCorrente);
            }
            catch (Exception e)
            {
                transaction.Rollback();
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao salvar 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();
                }
            }
        }
コード例 #18
0
        /// <summary>
        /// Get Webpages_Membership/Webpages_Membership
        /// </summary>
        /// <param name="colecao"></param>
        /// <param name="campo"></param>
        /// <param name="orderby"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageNumber"></param>
        /// <param name="queryString"></param>
        /// <returns></returns>
        private static IQueryable <webpages_Membership> getQuery(painel_taxservices_dbContext _db, int colecao, int campo, int orderby, int pageSize, int pageNumber, Dictionary <string, string> queryString)
        {
            // DEFINE A QUERY PRINCIPAL
            var entity = _db.webpages_Membership.AsQueryable <webpages_Membership>();

            #region WHERE - ADICIONA OS FILTROS A QUERY

            // ADICIONA OS FILTROS A QUERY
            foreach (var item in queryString)
            {
                int    key        = Convert.ToInt16(item.Key);
                CAMPOS filtroEnum = (CAMPOS)key;
                switch (filtroEnum)
                {
                case CAMPOS.USERID:
                    Int32 UserId = Convert.ToInt32(item.Value);
                    entity = entity.Where(e => e.UserId.Equals(UserId)).AsQueryable <webpages_Membership>();
                    break;

                case CAMPOS.CREATEDATE:
                    DateTime CreateDate = Convert.ToDateTime(item.Value);
                    entity = entity.Where(e => e.CreateDate.Equals(CreateDate)).AsQueryable <webpages_Membership>();
                    break;

                case CAMPOS.CONFIRMATIONTOKEN:
                    string ConfirmationToken = Convert.ToString(item.Value);
                    entity = entity.Where(e => e.ConfirmationToken.Equals(ConfirmationToken)).AsQueryable <webpages_Membership>();
                    break;

                case CAMPOS.ISCONFIRMED:
                    Boolean IsConfirmed = Convert.ToBoolean(item.Value);
                    entity = entity.Where(e => e.IsConfirmed.Equals(IsConfirmed)).AsQueryable <webpages_Membership>();
                    break;

                case CAMPOS.LASTPASSWORDFAILUREDATE:
                    DateTime LastPasswordFailureDate = Convert.ToDateTime(item.Value);
                    entity = entity.Where(e => e.LastPasswordFailureDate.Equals(LastPasswordFailureDate)).AsQueryable <webpages_Membership>();
                    break;

                case CAMPOS.PASSWORDFAILURESSINCELASTSUCCESS:
                    Int32 PasswordFailuresSinceLastSuccess = Convert.ToInt32(item.Value);
                    entity = entity.Where(e => e.PasswordFailuresSinceLastSuccess.Equals(PasswordFailuresSinceLastSuccess)).AsQueryable <webpages_Membership>();
                    break;

                case CAMPOS.PASSWORD:
                    string Password = Convert.ToString(item.Value);
                    entity = entity.Where(e => e.Password.Equals(Password)).AsQueryable <webpages_Membership>();
                    break;

                case CAMPOS.PASSWORDCHANGEDDATE:
                    DateTime PasswordChangedDate = Convert.ToDateTime(item.Value);
                    entity = entity.Where(e => e.PasswordChangedDate.Equals(PasswordChangedDate)).AsQueryable <webpages_Membership>();
                    break;

                case CAMPOS.PASSWORDSALT:
                    string PasswordSalt = Convert.ToString(item.Value);
                    entity = entity.Where(e => e.PasswordSalt.Equals(PasswordSalt)).AsQueryable <webpages_Membership>();
                    break;

                case CAMPOS.PASSWORDVERIFICATIONTOKEN:
                    string PasswordVerificationToken = Convert.ToString(item.Value);
                    entity = entity.Where(e => e.PasswordVerificationToken.Equals(PasswordVerificationToken)).AsQueryable <webpages_Membership>();
                    break;

                case CAMPOS.PASSWORDVERIFICATIONTOKENEXPIRATIONDATE:
                    DateTime PasswordVerificationTokenExpirationDate = Convert.ToDateTime(item.Value);
                    entity = entity.Where(e => e.PasswordVerificationTokenExpirationDate.Equals(PasswordVerificationTokenExpirationDate)).AsQueryable <webpages_Membership>();
                    break;
                }
            }
            #endregion

            #region ORDER BY - ADICIONA A ORDENAÇÃO A QUERY
            // ADICIONA A ORDENAÇÃO A QUERY
            CAMPOS filtro = (CAMPOS)campo;
            switch (filtro)
            {
            case CAMPOS.USERID:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.UserId).AsQueryable <webpages_Membership>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.UserId).AsQueryable <webpages_Membership>();
                }
                break;

            case CAMPOS.CREATEDATE:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.CreateDate).AsQueryable <webpages_Membership>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.CreateDate).AsQueryable <webpages_Membership>();
                }
                break;

            case CAMPOS.CONFIRMATIONTOKEN:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.ConfirmationToken).AsQueryable <webpages_Membership>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.ConfirmationToken).AsQueryable <webpages_Membership>();
                }
                break;

            case CAMPOS.ISCONFIRMED:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.IsConfirmed).AsQueryable <webpages_Membership>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.IsConfirmed).AsQueryable <webpages_Membership>();
                }
                break;

            case CAMPOS.LASTPASSWORDFAILUREDATE:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.LastPasswordFailureDate).AsQueryable <webpages_Membership>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.LastPasswordFailureDate).AsQueryable <webpages_Membership>();
                }
                break;

            case CAMPOS.PASSWORDFAILURESSINCELASTSUCCESS:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.PasswordFailuresSinceLastSuccess).AsQueryable <webpages_Membership>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.PasswordFailuresSinceLastSuccess).AsQueryable <webpages_Membership>();
                }
                break;

            case CAMPOS.PASSWORD:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.Password).AsQueryable <webpages_Membership>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.Password).AsQueryable <webpages_Membership>();
                }
                break;

            case CAMPOS.PASSWORDCHANGEDDATE:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.PasswordChangedDate).AsQueryable <webpages_Membership>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.PasswordChangedDate).AsQueryable <webpages_Membership>();
                }
                break;

            case CAMPOS.PASSWORDSALT:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.PasswordSalt).AsQueryable <webpages_Membership>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.PasswordSalt).AsQueryable <webpages_Membership>();
                }
                break;

            case CAMPOS.PASSWORDVERIFICATIONTOKEN:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.PasswordVerificationToken).AsQueryable <webpages_Membership>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.PasswordVerificationToken).AsQueryable <webpages_Membership>();
                }
                break;

            case CAMPOS.PASSWORDVERIFICATIONTOKENEXPIRATIONDATE:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.PasswordVerificationTokenExpirationDate).AsQueryable <webpages_Membership>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.PasswordVerificationTokenExpirationDate).AsQueryable <webpages_Membership>();
                }
                break;
            }
            #endregion

            return(entity);
        }
コード例 #19
0
        /// <summary>
        /// Apaga uma TbContaCorrente_tbLoginAdquirenteEmpresa
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static void Delete(string token, Int32 cdContaCorrente, Int32 cdLoginAdquirenteEmpresa, DateTime dtInicio, 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();

            try
            {
                tbContaCorrente_tbLoginAdquirenteEmpresa value = _db.tbContaCorrente_tbLoginAdquirenteEmpresas
                                                                 .Where(e => e.cdContaCorrente == cdContaCorrente)
                                                                 .Where(e => e.cdLoginAdquirenteEmpresa == cdLoginAdquirenteEmpresa)
                                                                 .Where(e => e.dtInicio.Equals(dtInicio))
                                                                 .FirstOrDefault();
                if (value == null)
                {
                    throw new Exception("Vigência inválida!");
                }
                _db.tbContaCorrente_tbLoginAdquirenteEmpresas.Remove(value);
                _db.SaveChanges();
                transaction.Commit();
            }
            catch (Exception e)
            {
                transaction.Rollback();
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao apagar 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();
                }
            }
        }
コード例 #20
0
        /// <summary>
        /// Retorna TbLogManifesto/TbLogManifesto
        /// </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> CollectionTbLogManifesto = new List <dynamic>();
                Retorno        retorno = new Retorno();

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

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

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


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

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

                // COLEÇÃO DE RETORNO
                if (colecao == 1)
                {
                    CollectionTbLogManifesto = query.Select(e => new
                    {
                        idLog        = e.idLog,
                        dtLogInicio  = e.dtLogInicio,
                        dsXmlEntrada = e.dsXmlEntrada,
                        cdRetorno    = e.cdRetorno,
                        dsRetorno    = e.dsRetorno,
                        dsMetodo     = e.dsMetodo,
                        dsXmlRetorno = e.dsXmlRetorno,
                        dtLogFim     = e.dtLogFim,
                    }).ToList <dynamic>();
                }
                else if (colecao == 0)
                {
                    CollectionTbLogManifesto = query.Select(e => new
                    {
                        idLog        = e.idLog,
                        dtLogInicio  = e.dtLogInicio,
                        dsXmlEntrada = e.dsXmlEntrada,
                        cdRetorno    = e.cdRetorno,
                        dsRetorno    = e.dsRetorno,
                        dsMetodo     = e.dsMetodo,
                        dsXmlRetorno = e.dsXmlRetorno,
                        dtLogFim     = e.dtLogFim,
                    }).ToList <dynamic>();
                }

                transaction.Commit();

                retorno.Registros = CollectionTbLogManifesto;

                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 TbLogManifesto" : 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();
                }
            }
        }
コード例 #21
0
        // GET "titulos/baixaautomatica"
        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
                Retorno retorno  = new Retorno();
                string  outValue = null;

                // ID EXTRATO
                Int32 idExtrato = -1;
                if (!queryString.TryGetValue("" + (int)CAMPOS.IDEXTRATO, out outValue))
                {
                    throw new Exception("O identificador da movimentação bancária deve ser informada para a baixa automática!");
                }

                idExtrato = Convert.ToInt32(queryString["" + (int)CAMPOS.IDEXTRATO]);
                int?cdGrupo = _db.Database.SqlQuery <int>("SELECT C.cdGrupo" +
                                                          " FROM card.tbExtrato E (NOLOCK)" +
                                                          " JOIN card.tbContaCorrente C (NOLOCK) ON C.cdContaCorrente = E.cdContaCorrente" +
                                                          " WHERE E.idExtrato = " + idExtrato)
                              .FirstOrDefault();
                if (cdGrupo == null)
                {
                    throw new Exception("Extrato inexistente!");
                }

                // 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)
                {
                    throw new Exception("Um grupo deve ser selecionado como para a baixa automática!");
                }

                if (cdGrupo.Value != IdGrupo)
                {
                    throw new Exception("Permissão negada! Movimentação bancária informada não se refere ao grupo associado ao usuário.");
                }

                grupo_empresa grupo_empresa = _db.Database.SqlQuery <grupo_empresa>("SELECT G.*" +
                                                                                    " FROM cliente.grupo_empresa G (NOLOCK)" +
                                                                                    " WHERE G.id_grupo = " + IdGrupo)
                                              .FirstOrDefault();

                if (grupo_empresa.dsAPI == null || grupo_empresa.dsAPI.Equals(""))
                {
                    throw new Exception("Permissão negada! Empresa não possui o serviço ativo");
                }


                #region AVALIA SE POSSUI ALGUM TÍTULO CONCILIADO COM MAIS DE UM RECEBÍVEL
                List <int> idsRecebimentoTitulo = _db.Database.SqlQuery <int>("SELECT P.idRecebimentoTitulo" +
                                                                              " FROM pos.RecebimentoParcela P (NOLOCK)" +
                                                                              " WHERE P.idRecebimentoTitulo IS NOT NULL" +
                                                                              " AND P.idRecebimentoTitulo IN" +
                                                                              " (SELECT P.idRecebimentoTitulo" +
                                                                              "  FROM pos.RecebimentoParcela P (NOLOCK)" +
                                                                              "  WHERE P.idExtrato = " + idExtrato +
                                                                              " )" +
                                                                              " GROUP BY P.idRecebimentoTitulo" +
                                                                              " HAVING COUNT(*) > 1")
                                                  .ToList();
                if (idsRecebimentoTitulo.Count > 0)
                {
                    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
                    {
                        string error = "Há " + idsRecebimentoTitulo.Count +
                                       (idsRecebimentoTitulo.Count == 1 ? " título que está conciliado" :
                                        " títulos que estão conciliados")
                                       + " com mais de um recebível! Essa relação deve ser de um para um."
                                       + Environment.NewLine
                                       + (idsRecebimentoTitulo.Count == 1 ? " Segue o título e as correspondentes parcelas conciliadas com ele:" :
                                          " Seguem os títulos e as correspondentes parcelas conciliadas com cada um deles")
                                       + Environment.NewLine;
                        // Reporta os títulos e as parcelas....
                        foreach (int idRecebimentoTitulo in idsRecebimentoTitulo)
                        {
                            // Obtém as informações da base
                            string script = "SELECT R.dtaVenda AS P_dtVenda" +
                                            ", R.nsu AS P_nsu" +
                                            ", R.valorVendaBruta AS P_vlVenda" +
                                            ", P_filial = UPPER(ER.ds_fantasia + CASE WHEN ER.filial IS NULL THEN '' ELSE ' ' + ER.filial END)" +
                                            ", B.dsBandeira AS P_dsBandeira" +
                                            ", AAR.nmAdquirente AS P_nmAdquirente" +
                                            ", R.numParcelaTotal AS P_qtParcelas" +
                                            ", P.numParcela AS P_nrParcela" +
                                            ", P.dtaRecebimento AS P_dtRecebimentoPrevisto" +
                                            ", P.dtaRecebimentoEfetivo AS P_dtRecebimentoEfetivo" +
                                            ", P.flAntecipado AS P_flAntecipado" +
                                            ", P.valorParcelaBruta AS P_vlParcela" +
                                            ", T.dtVenda AS T_dtVenda" +
                                            ", T.nrNSU AS T_nsu" +
                                            ", T.vlVenda AS T_vlVenda" +
                                            ", T_filial = UPPER(ET.ds_fantasia + CASE WHEN ET.filial IS NULL THEN '' ELSE ' ' + ET.filial END)" +
                                            ", T.dsBandeira AS T_dsBandeira" +
                                            //", AAT.nmAdquirente AS T_nmAdquirente" +
                                            ", T_nmAdquirente = (SELECT TOP 1 UPPER(nmAdquirente) FROM card.tbAdquirente (NOLOCK) WHERE cdAdquirente = CASE WHEN T.cdAdquirente IS NOT NULL THEN T.cdAdquirente ELSE T.cdAdquirenteNew END)" +
                                            ", T.qtParcelas AS T_qtParcelas" +
                                            ", T.nrParcela AS T_nrParcela" +
                                            ", T.dtTitulo AS T_dtRecebimentoPrevisto" +
                                            ", T.vlParcela AS T_vlParcela" +
                                            " FROM pos.RecebimentoParcela P (NOLOCK)" +
                                            " JOIN pos.Recebimento R (NOLOCK) ON R.id = P.idRecebimento" +
                                            " JOIN cliente.empresa ER (NOLOCK) ON ER.nu_cnpj = R.cnpj" +
                                            " JOIN card.tbBandeira B (NOLOCK) ON B.cdBandeira = R.cdBandeira" +
                                            " JOIN card.tbAdquirente AAR (NOLOCK) ON AAR.cdAdquirente = B.cdAdquirente" +
                                            " JOIN card.tbRecebimentoTitulo T (NOLOCK) ON T.idRecebimentoTitulo = P.idRecebimentoTitulo" +
                                            " JOIN cliente.empresa ET (NOLOCK) ON ET.nu_cnpj = T.nrCNPJ" +
                                            //" JOIN card.tbAdquirente AAT (NOLOCK) ON AAT.cdAdquirente = T.cdAdquirente" +
                                            " WHERE P.idRecebimentoTitulo = " + idRecebimentoTitulo;
                            List <IDataRecord> resultado = DataBaseQueries.SqlQuery(script, connection);

                            error += Environment.NewLine + "==========TÍTULO=========";
                            if (resultado == null || resultado.Count == 0)
                            {
                                error += Environment.NewLine + " " + idRecebimentoTitulo;
                            }
                            else
                            {
                                IDataRecord t = resultado[0];

                                DateTime?T_dtVenda    = t["T_dtVenda"].Equals(DBNull.Value) ? (DateTime?)null : (DateTime)t["T_dtVenda"];
                                string   T_nsu        = Convert.ToString(t["T_nsu"]);
                                decimal? T_vlVenda    = t["T_vlVenda"].Equals(DBNull.Value) ? (decimal?)null : Convert.ToDecimal(t["T_vlVenda"]);
                                string   T_filial     = Convert.ToString(t["T_filial"]);
                                string   T_bandeira   = Convert.ToString(t["T_dsBandeira"].Equals(DBNull.Value) ? "" : t["T_dsBandeira"]);
                                string   T_adquirente = Convert.ToString(t["T_nmAdquirente"].Equals(DBNull.Value) ? "" : t["T_nmAdquirente"]);
                                byte     T_qtParcelas = Convert.ToByte(t["T_qtParcelas"].Equals(DBNull.Value) ? 0 : t["T_qtParcelas"]);
                                byte     T_nrParcela  = Convert.ToByte(t["T_nrParcela"]);
                                DateTime T_dtTitulo   = (DateTime)t["T_dtRecebimentoPrevisto"];
                                Decimal  T_vlParcela  = Convert.ToDecimal(t["T_vlParcela"]);

                                error += Environment.NewLine + "Adquirente: " + T_adquirente;
                                error += Environment.NewLine + "Bandeira: " + T_bandeira;
                                error += Environment.NewLine + "Filial: " + T_filial;
                                if (T_dtVenda != null)
                                {
                                    error += Environment.NewLine + "Venda em " + T_dtVenda.Value.ToShortDateString();
                                    if (T_vlVenda != null)
                                    {
                                        error += Environment.NewLine + " no valor de " + T_vlVenda.Value.ToString("C");
                                    }
                                }
                                else if (T_vlVenda != null)
                                {
                                    error += Environment.NewLine + "Valor da venda: " + T_vlVenda.Value.ToString("C");
                                }
                                error += Environment.NewLine + "NSU: " + T_nsu;
                                error += Environment.NewLine + "Parcela " + T_nrParcela + (T_qtParcelas > 0 ? " de " + T_qtParcelas : "");
                                error += Environment.NewLine + "Dt Prevista Recebimento: " + T_dtTitulo;
                                error += Environment.NewLine + "Valor Bruto: " + T_vlParcela.ToString("C");

                                error += Environment.NewLine;


                                foreach (IDataRecord r in resultado)
                                {
                                    DateTime P_dtVenda               = (DateTime)r["P_dtVenda"];
                                    string   P_nsu                   = Convert.ToString(r["P_nsu"]);
                                    decimal  P_vlVenda               = Convert.ToDecimal(r["P_vlVenda"]);
                                    string   P_filial                = Convert.ToString(r["P_filial"]);
                                    string   P_bandeira              = Convert.ToString(r["P_dsBandeira"]);
                                    string   P_adquirente            = Convert.ToString(r["P_nmAdquirente"]);
                                    int      P_qtParcelas            = Convert.ToInt32(r["P_qtParcelas"].Equals(DBNull.Value) ? 0 : r["P_qtParcelas"]);
                                    int      P_nrParcela             = Convert.ToInt32(r["P_nrParcela"]);
                                    DateTime P_dtRecebimentoPrevisto = (DateTime)r["P_dtRecebimentoPrevisto"];
                                    DateTime?P_dtRecebimentoEfetivo  = r["P_dtRecebimentoEfetivo"].Equals(DBNull.Value) ? (DateTime?)null : (DateTime)r["P_dtRecebimentoEfetivo"];
                                    bool     P_flAntecipado          = Convert.ToBoolean(r["P_flAntecipado"]);
                                    Decimal  P_vlParcela             = Convert.ToDecimal(r["P_vlParcela"]);

                                    error += Environment.NewLine + "=> RECEBÍVEL";
                                    error += Environment.NewLine + "   Adquirente: " + P_adquirente;
                                    error += Environment.NewLine + "   Bandeira: " + P_bandeira;
                                    error += Environment.NewLine + "   Filial: " + P_filial;
                                    error += Environment.NewLine + "   Venda em " + P_dtVenda.ToShortDateString() + " no valor de " + P_vlVenda.ToString("C");
                                    error += Environment.NewLine + "   NSU: " + P_nsu;
                                    error += Environment.NewLine + "   Parcela " + (P_nrParcela == 0 ? 1 : P_nrParcela) + (P_qtParcelas > 0 ? " de " + P_qtParcelas : "");
                                    error += Environment.NewLine + "   Dt Prevista Recebimento: " + P_dtRecebimentoPrevisto;
                                    if (P_dtRecebimentoEfetivo != null && !P_dtRecebimentoEfetivo.Value.Equals(P_dtRecebimentoPrevisto))
                                    {
                                        error += Environment.NewLine + " Dt Efetiva Recebimento: " + P_dtRecebimentoEfetivo.Value.ToShortDateString() + (P_flAntecipado ? " (ANTECIPAÇÃO)" : "");
                                    }
                                    error += Environment.NewLine + "   Valor Bruto: " + P_vlParcela.ToString("C");

                                    error += Environment.NewLine;
                                }
                            }
                        }

                        throw new Exception(error);
                    }
                    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 { }
                    }
                }
                #endregion


                string url = "http://" + grupo_empresa.dsAPI + DOMINIO;
                //string url = "http://localhost:60049/";
                string complemento = "titulos/baixaautomatica/" + token + "?" + ("" + (int)CAMPOS.IDEXTRATO) + "=" + idExtrato;


                HttpClient client = new System.Net.Http.HttpClient();
                client.BaseAddress = new Uri(url);
                client.Timeout     = TimeSpan.FromMinutes(30); // 30 minutos de timeout
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
                System.Net.Http.HttpResponseMessage response = client.GetAsync(complemento).Result;

                //se retornar com sucesso busca os dados
                if (response.IsSuccessStatusCode)
                {
                    //Pegando os dados do Rest e armazenando na variável retorno
                    retorno = response.Content.ReadAsAsync <Retorno>().Result;
                }
                else
                {
                    string resp = String.Empty;
                    try
                    {
                        resp = response.Content.ReadAsAsync <string>().Result;
                    }
                    catch
                    {
                        throw new Exception("Serviço indisponível no momento");
                    }
                    if (resp != null && !resp.Trim().Equals(""))
                    {
                        throw new Exception(((int)response.StatusCode) + " - " + resp);
                    }
                    throw new Exception(((int)response.StatusCode) + "");
                }


                return(retorno);
            }
            catch (Exception e)
            {
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao realizar a baixa automática" : erro);
                }
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
            }
        }
コード例 #22
0
        /// <summary>
        /// Altera tbLogManifesto
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static void Update(string token, tbLogManifesto param, painel_taxservices_dbContext _dbContext = null)
        {
            painel_taxservices_dbContext _db;

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

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

                tbLogManifesto value = _db.tbLogManifestos
                                       .Where(e => e.idLog.Equals(param.idLog))
                                       .First <tbLogManifesto>();

                // OBSERVAÇÂO: VERIFICAR SE EXISTE ALTERAÇÃO NO PARAMETROS


                if (param.idLog != null && param.idLog != value.idLog)
                {
                    value.idLog = param.idLog;
                }
                if (param.dtLogInicio != null && param.dtLogInicio != value.dtLogInicio)
                {
                    value.dtLogInicio = param.dtLogInicio;
                }
                if (param.dsXmlEntrada != null && param.dsXmlEntrada != value.dsXmlEntrada)
                {
                    value.dsXmlEntrada = param.dsXmlEntrada;
                }
                if (param.cdRetorno != null && param.cdRetorno != value.cdRetorno)
                {
                    value.cdRetorno = param.cdRetorno;
                }
                if (param.dsRetorno != null && param.dsRetorno != value.dsRetorno)
                {
                    value.dsRetorno = param.dsRetorno;
                }
                if (param.dsMetodo != null && param.dsMetodo != value.dsMetodo)
                {
                    value.dsMetodo = param.dsMetodo;
                }
                if (param.dsXmlRetorno != null && param.dsXmlRetorno != value.dsXmlRetorno)
                {
                    value.dsXmlRetorno = param.dsXmlRetorno;
                }
                if (param.dtLogFim != null && param.dtLogFim != value.dtLogFim)
                {
                    value.dtLogFim = param.dtLogFim;
                }
                _db.SaveChanges();
            }
            catch (Exception e)
            {
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao alterar TbLogManifesto" : 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();
                }
            }
        }
コード例 #23
0
        /// <summary>
        /// Altera tbRecebimentoTitulo
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static void Update(string token, tbRecebimentoTitulo param, 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();
            try
            {
                tbRecebimentoTitulo value = _db.tbRecebimentoTitulos
                                            .Where(e => e.idRecebimentoTitulo == param.idRecebimentoTitulo)
                                            .First <tbRecebimentoTitulo>();

                if (param.dtVenda != null && param.dtVenda != value.dtVenda)
                {
                    value.dtVenda = param.dtVenda;
                }
                if (param.cdAdquirente != 0 && param.cdAdquirente != value.cdAdquirente)
                {
                    value.cdAdquirente = param.cdAdquirente;
                }
                if (param.dsBandeira != null && param.dsBandeira != value.dsBandeira)
                {
                    value.dsBandeira = param.dsBandeira;
                }
                if (param.vlVenda != null && param.vlVenda != value.vlVenda)
                {
                    value.vlVenda = param.vlVenda;
                }
                if (param.qtParcelas != null && param.qtParcelas != value.qtParcelas)
                {
                    value.qtParcelas = param.qtParcelas;
                }
                if (param.vlParcela != new decimal(0.0) && param.vlParcela != value.vlParcela)
                {
                    value.vlParcela = param.vlParcela;
                }
                if (param.cdERP != null && param.cdERP != value.cdERP)
                {
                    value.cdERP = param.cdERP;
                }
                if (/*param.dtBaixaERP != null && param.dtBaixaERP != value.dtBaixaERP*/
                    (param.dtBaixaERP == null && value.dtBaixaERP != null) ||
                    (param.dtBaixaERP != null && value.dtBaixaERP == null) ||
                    (param.dtBaixaERP != null && value.dtBaixaERP != null && !param.dtBaixaERP.Value.Equals(value.dtBaixaERP.Value)))
                {
                    value.dtBaixaERP = param.dtBaixaERP;
                }
                _db.SaveChanges();
                //transaction.Commit();
            }
            catch (Exception e)
            {
                //transaction.Rollback();
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao atualizar título" : 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();
                }
            }
        }
コード例 #24
0
        /// <summary>
        /// Get TbLogManifesto/TbLogManifesto
        /// </summary>
        /// <param name="colecao"></param>
        /// <param name="campo"></param>
        /// <param name="orderby"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageNumber"></param>
        /// <param name="queryString"></param>
        /// <returns></returns>
        private static IQueryable <tbLogManifesto> getQuery(painel_taxservices_dbContext _db, int colecao, int campo, int orderby, int pageSize, int pageNumber, Dictionary <string, string> queryString)
        {
            // DEFINE A QUERY PRINCIPAL
            var entity = _db.tbLogManifestos.AsQueryable <tbLogManifesto>();

            #region WHERE - ADICIONA OS FILTROS A QUERY

            // ADICIONA OS FILTROS A QUERY
            foreach (var item in queryString)
            {
                int    key        = Convert.ToInt16(item.Key);
                CAMPOS filtroEnum = (CAMPOS)key;
                switch (filtroEnum)
                {
                case CAMPOS.IDLOG:
                    Int32 idLog = Convert.ToInt32(item.Value);
                    entity = entity.Where(e => e.idLog.Equals(idLog)).AsQueryable <tbLogManifesto>();
                    break;

                case CAMPOS.DTLOGINICIO:
                    DateTime dtLogInicio = Convert.ToDateTime(item.Value);
                    entity = entity.Where(e => e.dtLogInicio.Equals(dtLogInicio)).AsQueryable <tbLogManifesto>();
                    break;

                case CAMPOS.DSXMLENTRADA:
                    string dsXmlEntrada = Convert.ToString(item.Value);
                    entity = entity.Where(e => e.dsXmlEntrada.Equals(dsXmlEntrada)).AsQueryable <tbLogManifesto>();
                    break;

                case CAMPOS.CDRETORNO:
                    short cdRetorno = short.Parse(item.Value);
                    entity = entity.Where(e => e.cdRetorno.Equals(cdRetorno)).AsQueryable <tbLogManifesto>();
                    break;

                case CAMPOS.DSRETORNO:
                    string dsRetorno = Convert.ToString(item.Value);
                    entity = entity.Where(e => e.dsRetorno.Equals(dsRetorno)).AsQueryable <tbLogManifesto>();
                    break;

                case CAMPOS.DSMETODO:
                    string dsMetodo = Convert.ToString(item.Value);
                    entity = entity.Where(e => e.dsMetodo.Equals(dsMetodo)).AsQueryable <tbLogManifesto>();
                    break;

                case CAMPOS.DSXMLRETORNO:
                    string dsXmlRetorno = Convert.ToString(item.Value);
                    entity = entity.Where(e => e.dsXmlRetorno.Equals(dsXmlRetorno)).AsQueryable <tbLogManifesto>();
                    break;

                case CAMPOS.DTLOGFIM:
                    DateTime dtLogFim = Convert.ToDateTime(item.Value);
                    entity = entity.Where(e => e.dtLogFim.Equals(dtLogFim)).AsQueryable <tbLogManifesto>();
                    break;
                }
            }
            #endregion

            #region ORDER BY - ADICIONA A ORDENAÇÃO A QUERY
            // ADICIONA A ORDENAÇÃO A QUERY
            CAMPOS filtro = (CAMPOS)campo;
            switch (filtro)
            {
            case CAMPOS.IDLOG:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.idLog).AsQueryable <tbLogManifesto>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.idLog).AsQueryable <tbLogManifesto>();
                }
                break;

            case CAMPOS.DTLOGINICIO:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.dtLogInicio).AsQueryable <tbLogManifesto>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.dtLogInicio).AsQueryable <tbLogManifesto>();
                }
                break;

            case CAMPOS.DSXMLENTRADA:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.dsXmlEntrada).AsQueryable <tbLogManifesto>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.dsXmlEntrada).AsQueryable <tbLogManifesto>();
                }
                break;

            case CAMPOS.CDRETORNO:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.cdRetorno).AsQueryable <tbLogManifesto>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.cdRetorno).AsQueryable <tbLogManifesto>();
                }
                break;

            case CAMPOS.DSRETORNO:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.dsRetorno).AsQueryable <tbLogManifesto>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.dsRetorno).AsQueryable <tbLogManifesto>();
                }
                break;

            case CAMPOS.DSMETODO:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.dsMetodo).AsQueryable <tbLogManifesto>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.dsMetodo).AsQueryable <tbLogManifesto>();
                }
                break;

            case CAMPOS.DSXMLRETORNO:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.dsXmlRetorno).AsQueryable <tbLogManifesto>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.dsXmlRetorno).AsQueryable <tbLogManifesto>();
                }
                break;

            case CAMPOS.DTLOGFIM:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.dtLogFim).AsQueryable <tbLogManifesto>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.dtLogFim).AsQueryable <tbLogManifesto>();
                }
                break;
            }
            #endregion

            return(entity);
        }
コード例 #25
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();
                }
            }
        }
コード例 #26
0
        // PUT  "vendas/corrigevendaserp"
        // JSON : { idsRecebimento [int] }
        public static void CorrigeVenda(string token, CorrigeVendasErp param, painel_taxservices_dbContext _dbContext = null)
        {
            painel_taxservices_dbContext _db;

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


            try
            {
                if (param == null)
                {
                    throw new Exception("Nenhum recebimento foi informado!");
                }

                //string outValue = null;

                string script = String.Empty;

                if (param.idsRecebimento == null || param.idsRecebimento.Count == 0)
                {
                    if (param.data == null)
                    {
                        throw new Exception("O período deve ser informado!");
                    }

                    // Obtém os recebíveis conciliados baseadas no filtro
                    DateTime dtIni, dtFim;

                    // Usa outros dados
                    if (param.data.Contains("|"))
                    {
                        string[] dts = param.data.Split('|');
                        dtIni = DateTime.ParseExact(dts[0] + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        dtFim = DateTime.ParseExact(dts[1] + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        dtIni = dtFim = DateTime.ParseExact(param.data + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                    }


                    script = "SELECT R.id" +
                             " FROM pos.Recebimento R (NOLOCK)" +
                             " JOIN card.tbBandeira B (NOLOCK) ON B.cdBandeira = R.cdBandeira" +
                             " JOIN cliente.empresa ER (NOLOCK) ON ER.nu_cnpj = R.cnpj" +
                             " JOIN card.tbRecebimentoVenda V (NOLOCK) ON V.idRecebimentoVenda = R.idRecebimentoVenda" +
                             //" LEFT JOIN card.tbBandeiraSacado BS on	BS.cdGrupo = ER.id_grupo and BS.cdBandeira = R.cdBandeira" +
                             " WHERE R.dtaVenda BETWEEN '" + DataBaseQueries.GetDate(dtIni) + "' AND '" + DataBaseQueries.GetDate(dtFim) + " 23:59:00'" +
                             (param.nrCNPJ != null ? " AND R.cnpj = '" + param.nrCNPJ + "'" : "") +
                             " AND V.dtAjuste IS NULL AND (" +
                             " CONVERT(VARCHAR(10), R.dtaVenda, 120) <> V.dtVenda" +
                             " OR (V.cdAdquirente IS NOT NULL AND R.cdSacado IS NOT NULL AND V.cdSacado IS NOT NULL AND V.cdSacado <> R.cdSacado)" +
                             " OR (R.numParcelaTotal IS NOT NULL AND V.qtParcelas <> R.numParcelaTotal)" +
                             " OR V.vlVenda <> R.valorVendaBruta" +
                             " OR (B.cdAdquirente NOT IN (5, 6, 11, 14) AND SUBSTRING('000000000000' + CONVERT(VARCHAR(12), R.nsu), LEN(R.nsu) + 1, 12) <> SUBSTRING('000000000000' + CONVERT(VARCHAR(12), V.nrNSU), LEN(V.nrNSU) + 1, 12))" +
                             ")";

                    // Obtém os recebíveis conciliados com divergência que respeitam o filtro
                    param.idsRecebimento = _db.Database.SqlQuery <int>(script).ToList();

                    if (param.idsRecebimento == null || param.idsRecebimento.Count == 0)
                    {
                        throw new Exception("Não há vendas a serem corrigadas " + (dtIni.Equals(dtFim) ? " em " + dtIni.ToShortDateString() : " no período de " + dtIni.ToShortDateString() + " a " + dtFim.ToShortDateString()) +
                                            (param.nrCNPJ != null ? " para a empresa " + param.nrCNPJ : "") + ".");
                    }
                }
                else
                {
                    #region DESCOBRE AS VENDAS QUE PRECISAM SER CORRIGIDAS
                    script = "SELECT R.id" +
                             " FROM pos.Recebimento R (NOLOCK)" +
                             " JOIN card.tbBandeira B (NOLOCK) ON B.cdBandeira = R.cdBandeira" +
                             " JOIN cliente.empresa ER (NOLOCK) ON ER.nu_cnpj = R.cnpj" +
                             " JOIN card.tbRecebimentoVenda V (NOLOCK) ON V.idRecebimentoVenda = R.idRecebimentoVenda" +
                             //" LEFT JOIN card.tbBandeiraSacado BS on	BS.cdGrupo = ER.id_grupo and BS.cdBandeira = R.cdBandeira" +
                             " WHERE R.id IN (" + string.Join(", ", param.idsRecebimento) + ")" +
                             " AND V.dtAjuste IS NULL AND (" +
                             " CONVERT(VARCHAR(10), R.dtaVenda, 120) <> V.dtVenda" +
                             " OR (V.cdAdquirente IS NOT NULL AND R.cdSacado IS NOT NULL AND V.cdSacado IS NOT NULL AND V.cdSacado <> R.cdSacado)" +
                             " OR (R.numParcelaTotal IS NOT NULL AND V.qtParcelas <> R.numParcelaTotal)" +
                             " OR V.vlVenda <> R.valorVendaBruta" +
                             // POLICARD, GETNET, SODEXO e VALECARD não trazem NSU do sitef
                             " OR (B.cdAdquirente NOT IN (5, 6, 11, 14) AND SUBSTRING('000000000000' + CONVERT(VARCHAR(12), R.nsu), LEN(R.nsu) + 1, 12) <> SUBSTRING('000000000000' + CONVERT(VARCHAR(12), V.nrNSU), LEN(V.nrNSU) + 1, 12))" +
                             ")";
                    param.idsRecebimento = _db.Database.SqlQuery <int>(script).ToList();
                    #endregion

                    if (param.idsRecebimento == null || param.idsRecebimento.Count == 0)
                    {
                        throw new Exception("Não há vendas a serem corrigadas!");
                    }
                }



                string idsRecebimento = string.Join(", ", param.idsRecebimento);

                int[] gruposRecebimentos = _db.Database.SqlQuery <int>("SELECT DISTINCT E.id_grupo" +
                                                                       " FROM pos.Recebimento R (NOLOCK)" +
                                                                       " JOIN cliente.empresa E (NOLOCK) ON E.nu_cnpj = R.cnpj" +
                                                                       " WHERE R.id IN (" + idsRecebimento + ")")
                                           .ToArray();

                if (gruposRecebimentos == null || gruposRecebimentos.Length == 0)
                {
                    throw new Exception(param.idsRecebimento.Count == 1 ? "Identificador de recebível inexistente!" : "Identificadores de recebíveis inexistentes!");
                }

                //if (gruposRecebimentos.Length < param.idsRecebimento.Count)
                //    throw new Exception("Há " + (param.idsRecebimento.Count - gruposRecebimentos.Length) + ((param.idsRecebimento.Count - gruposRecebimentos.Length) == 1 ? " identificador de recebível inexistente!" : " identificadores de recebíveis inexistentes!"));


                // GRUPO EMPRESA => OBRIGATÓRIO!
                Int32 IdGrupo = Permissoes.GetIdGrupo(token, _db);
                if (IdGrupo == 0)
                {
                    throw new Exception("Um grupo deve ser selecionado como para a correção das vendas no ERP!");
                }

                if (gruposRecebimentos.Any(t => t != IdGrupo))
                {
                    throw new Exception("Permissão negada! " + (gruposRecebimentos.Length == 1 ? "Recebível informado não se refere" : "Recebíveis informados não se referem") + " ao grupo associado ao usuário.");
                }

                grupo_empresa grupo_empresa = _db.Database.SqlQuery <grupo_empresa>("SELECT G.*" +
                                                                                    " FROM cliente.grupo_empresa G (NOLOCK)" +
                                                                                    " WHERE G.id_grupo = " + IdGrupo)
                                              .FirstOrDefault();

                if (grupo_empresa.dsAPI == null || grupo_empresa.dsAPI.Equals(""))
                {
                    throw new Exception("Permissão negada! Empresa não possui o serviço ativo");
                }


                SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["painel_taxservices_dbContext"].ConnectionString);

                List <IDataRecord> resultado;
                //List<int> idsReceb = new List<int>();
                try
                {
                    connection.Open();
                }
                catch
                {
                    throw new Exception("Não foi possível estabelecer conexão com a base de dados");
                }

                try
                {
                    #region AVALIA SE POSSUI ALGUM VENDA CONCILIADO COM MAIS DE UM RECEBÍVEL
                    List <int> idsRecebimentoVenda = _db.Database.SqlQuery <int>("SELECT R.idRecebimentoVenda" +
                                                                                 " FROM pos.Recebimento R (NOLOCK)" +
                                                                                 " WHERE R.idRecebimentoVenda IS NOT NULL" +
                                                                                 " AND R.idRecebimentoVenda IN" +
                                                                                 " (SELECT R.idRecebimentoVenda" +
                                                                                 "  FROM pos.Recebimento R (NOLOCK)" +
                                                                                 "  WHERE R.id IN (" + idsRecebimento + ")" +
                                                                                 " )" +
                                                                                 " GROUP BY R.idRecebimentoVenda" +
                                                                                 " HAVING COUNT(*) > 1")
                                                     .ToList();
                    if (idsRecebimentoVenda.Count > 0)
                    {
                        string error = "Há " + idsRecebimentoVenda.Count +
                                       (idsRecebimentoVenda.Count == 1 ? " venda que está conciliada" :
                                        " vendas que estão conciliadas")
                                       + " com mais de um recebível! Essa relação deve ser de um para um."
                                       + Environment.NewLine
                                       + (idsRecebimentoVenda.Count == 1 ? " Segue a venda e os correspondentes recebíveis conciliados com ele:" :
                                          " Seguem as vendas e os correspondentes recebíveis conciliados com cada uma delas")
                                       + Environment.NewLine;
                        // Reporta os vendas e as parcelas....
                        foreach (int idRecebimentoVenda in idsRecebimentoVenda)
                        {
                            // Obtém as informações da base
                            script = "SELECT R.dtaVenda AS R_dtVenda" +
                                     ", R.nsu AS R_nsu" +
                                     ", R.valorVendaBruta AS R_vlVenda" +
                                     ", R_filial = UPPER(ER.ds_fantasia + CASE WHEN ER.filial IS NULL THEN '' ELSE ' ' + ER.filial END)" +
                                     ", B.dsBandeira AS R_dsBandeira" +
                                     ", AAR.nmAdquirente AS R_nmAdquirente" +
                                     ", R.numParcelaTotal AS R_qtParcelas" +
                                     ", V.dtVenda AS V_dtVenda" +
                                     ", V.nrNSU AS V_nsu" +
                                     ", V.vlVenda AS V_vlVenda" +
                                     ", V_filial = UPPER(EV.ds_fantasia + CASE WHEN EV.filial IS NULL THEN '' ELSE ' ' + EV.filial END)" +
                                     ", V.dsBandeira AS V_dsBandeira" +
                                     ", AAV.nmAdquirente AS V_nmAdquirente" +
                                     ", V.qtParcelas AS V_qtParcelas" +
                                     " FROM pos.Recebimento R (NOLOCK)" +
                                     " JOIN cliente.empresa ER (NOLOCK) ON ER.nu_cnpj = R.cnpj" +
                                     " JOIN card.tbBandeira B (NOLOCK) ON B.cdBandeira = R.cdBandeira" +
                                     " JOIN card.tbAdquirente AAR (NOLOCK) ON AAR.cdAdquirente = B.cdAdquirente" +
                                     " JOIN card.tbRecebimentoVenda V (NOLOCK) ON V.idRecebimentoVenda = R.idRecebimentoVenda" +
                                     " JOIN cliente.empresa EV (NOLOCK) ON EV.nu_cnpj = V.nrCNPJ" +
                                     //" JOIN card.tbAdquirente AAV (NOLOCK) ON AAV.cdAdquirente = V.cdAdquirente" +
                                     " LEFT JOIN card.tbBandeiraSacado BS ON BS.cdSacado = V.cdSacado AND EV.id_grupo = BS.cdGrupo" +
                                     " JOIN card.tbBandeira BV ON BV.cdBandeira = BS.cdBandeira" +
                                     " JOIN card.tbAdquirente AAV ON AAV.cdAdquirente = BV.cdAdquirente" +
                                     " WHERE R.idRecebimentoVenda = " + idRecebimentoVenda;
                            resultado = DataBaseQueries.SqlQuery(script, connection);

                            error += Environment.NewLine + "==========VENDA=========";
                            if (resultado == null || resultado.Count == 0)
                            {
                                error += Environment.NewLine + " " + idRecebimentoVenda;
                            }
                            else
                            {
                                IDataRecord v = resultado[0];

                                DateTime V_dtVenda    = (DateTime)v["V_dtVenda"];
                                string   V_nsu        = Convert.ToString(v["V_nsu"]);
                                decimal  V_vlVenda    = Convert.ToDecimal(v["V_vlVenda"]);
                                string   V_filial     = Convert.ToString(v["V_filial"]);
                                string   V_bandeira   = Convert.ToString(v["V_dsBandeira"].Equals(DBNull.Value) ? "" : v["V_dsBandeira"]);
                                string   V_adquirente = Convert.ToString(v["V_nmAdquirente"]);
                                byte     V_qtParcelas = Convert.ToByte(v["V_qtParcelas"].Equals(DBNull.Value) ? 0 : v["V_qtParcelas"]);

                                error += Environment.NewLine + "Adquirente: " + V_adquirente;
                                error += Environment.NewLine + "Bandeira: " + V_bandeira;
                                error += Environment.NewLine + "Filial: " + V_filial;
                                error += Environment.NewLine + "Venda em " + V_dtVenda.ToShortDateString() + " no valor de " + V_vlVenda.ToString("C");
                                error += Environment.NewLine + "NSU: " + V_nsu;
                                error += Environment.NewLine + "Parcelas: " + V_qtParcelas;

                                error += Environment.NewLine;


                                foreach (IDataRecord r in resultado)
                                {
                                    DateTime R_dtVenda    = (DateTime)r["R_dtVenda"];
                                    string   R_nsu        = Convert.ToString(r["R_nsu"]);
                                    decimal  R_vlVenda    = Convert.ToDecimal(r["R_vlVenda"]);
                                    string   R_filial     = Convert.ToString(r["R_filial"]);
                                    string   R_bandeira   = Convert.ToString(r["R_dsBandeira"]);
                                    string   R_adquirente = Convert.ToString(r["R_nmAdquirente"]);
                                    int      R_qtParcelas = Convert.ToInt32(r["R_qtParcelas"].Equals(DBNull.Value) ? 1 : r["R_qtParcelas"]);

                                    error += Environment.NewLine + "=> RECEBÍVEL";
                                    error += Environment.NewLine + "   Adquirente: " + R_adquirente;
                                    error += Environment.NewLine + "   Bandeira: " + R_bandeira;
                                    error += Environment.NewLine + "   Filial: " + R_filial;
                                    error += Environment.NewLine + "   Venda em " + R_dtVenda.ToShortDateString() + " no valor de " + R_vlVenda.ToString("C");
                                    error += Environment.NewLine + "   NSU: " + R_nsu;
                                    error += Environment.NewLine + "   Parcelas: " + R_qtParcelas;

                                    error += Environment.NewLine;
                                }
                            }
                        }

                        throw new Exception(error);
                    }
                    #endregion
                }
                catch (Exception e)
                {
                    if (e is DbEntityValidationException)
                    {
                        string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                        throw new Exception(erro.Equals("") ? "Falha ao listar realizar a correção das vendas" : 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 { }
                }

                if (param.idsRecebimento == null || param.idsRecebimento.Count == 0)
                {
                    //if (idsReceb.Count == 0)
                    throw new Exception("Não há nenhuma venda para ser corrigida!");
                }


                string url = "http://" + grupo_empresa.dsAPI + DOMINIO;
                //string url = "http://localhost:50939";
                string complemento = "vendas/corrigevendas/" + token;

                CorrigeVendaERP o = new CorrigeVendaERP(param.idsRecebimento);//idsReceb);

                HttpContent json   = new StringContent(JsonConvert.SerializeObject(o), Encoding.UTF8, "application/json");
                HttpClient  client = new System.Net.Http.HttpClient();
                client.BaseAddress = new Uri(url);
                client.Timeout     = TimeSpan.FromMinutes(5); // 5 minutos de timeout
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
                System.Net.Http.HttpResponseMessage response = client.PutAsync(complemento, json).Result;

                //se não retornar com sucesso busca os dados
                if (!response.IsSuccessStatusCode)
                {
                    string resp = String.Empty;
                    try
                    {
                        resp = response.Content.ReadAsAsync <string>().Result;
                    }
                    catch
                    {
                        throw new Exception("Serviço indisponível no momento");
                    }
                    if (resp != null && !resp.Trim().Equals(""))
                    {
                        throw new Exception(((int)response.StatusCode) + " - " + resp);
                    }
                    throw new Exception(((int)response.StatusCode) + "");
                }

                // Avalia se alguma venda teve que inserir dados
                script = "SELECT V.*" +
                         " FROM pos.Recebimento R (NOLOCK)" +
                         " JOIN card.tbRecebimentoVenda V ON R.idRecebimentoVenda = V.idRecebimentoVenda" +
                         " WHERE R.id IN (" + idsRecebimento + ")" +
                         " AND V.dsMensagem IS NOT NULL";
                try
                {
                    tbRecebimentoVenda[] vendas = _db.Database.SqlQuery <tbRecebimentoVenda>(script).ToArray();
                    if (vendas.Length > 0)
                    {
                        string result = String.Empty;
                        //foreach (tbRecebimentoVenda venda in vendas)
                        //{
                        //    result += "NSU: " + venda.nrNSU + Environment.NewLine +
                        //              (venda.cdSacado != null ? "Sacado : " + venda.cdSacado + Environment.NewLine : "") +
                        //              "Valor: " + venda.vlVenda.ToString("C") + Environment.NewLine +
                        //              "Parcelas: " + venda.qtParcelas + Environment.NewLine +
                        //              "Mensagem: '" + venda.dsMensagem + "'" +
                        //              Environment.NewLine + Environment.NewLine;
                        //}
                        //throw new Exception("Vendas corrigidas que precisam ser corrigidas manualmente no sistema do cliente: " +
                        //                    Environment.NewLine + Environment.NewLine + result);

                        if (vendas.Length == 1)
                        {
                            result = "Há 1 venda que precisa ser corrigida manualmente no sistema do cliente.";
                        }
                        else
                        {
                            result = "Há " + vendas.Length + " vendas que precisam ser corrigidas manualmente no sistema do cliente.";
                        }

                        result += Environment.NewLine + "Por favor, acesse a tela ADMINISTRATIVO > INTEGRAÇÃO ERP > VENDAS" +
                                  " e seleciono como filtro de TIPO a opção CORREÇÃO MANUAL " +
                                  " usando como filtro de data o mesmo período selecionado aqui na Conciliação de Vendas.";

                        throw new Exception(result);
                    }
                }
                catch (Exception e)
                {
                    if (e.Message.StartsWith("Há") && e.Message.Contains("Por favor, acesse a tela ADMINISTRATIVO > INTEGRAÇÃO ERP > VENDAS"))
                    {
                        throw new Exception(e.Message);
                    }
                    throw new Exception("Falha de comunicação com o servidor");
                }
            }
            catch (Exception e)
            {
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao realizar a correção das vendas" : erro);
                }
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.InnerException == null ? e.InnerException.Message : e.InnerException.InnerException.Message);
            }
        }
コード例 #27
0
        /// <summary>
        /// Retorna Webpages_Permissions/Webpages_Permissions
        /// </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> CollectionWebpages_Permissions = new List <dynamic>();
                Retorno        retorno = new Retorno();

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

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


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

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

                // COLEÇÃO DE RETORNO
                if (colecao == 1)
                {
                    CollectionWebpages_Permissions = query.Select(e => new
                    {
                        id_roles     = e.id_roles,
                        id_method    = e.id_method,
                        fl_principal = e.fl_principal,
                    }).ToList <dynamic>();
                }
                else if (colecao == 0)
                {
                    CollectionWebpages_Permissions = query.Select(e => new
                    {
                        id_roles     = e.id_roles,
                        id_method    = e.id_method,
                        fl_principal = e.fl_principal,
                    }).ToList <dynamic>();
                }
                else if (colecao == 2)
                {
                    // Retorna os métodos permitidos para o usuário logado em relação ao controller informado
                    Int32 userId       = Permissoes.GetIdUser(token);
                    Int32 controllerId = Convert.ToInt32(queryString[((int)CAMPOS.ID_CONTROLLER).ToString()]);


                    var permissoes = _db.webpages_UsersInRoles
                                     .Where(r => r.UserId == userId)
                                     .Where(r => r.RoleId > 50)
                                     .Select(r => new
                    {
                        metodos = _db.webpages_Permissions
                                  .Where(p => p.id_roles == r.RoleId)
                                  .Where(p => p.webpages_Methods.webpages_Controllers.id_controller == controllerId)
                                  .Select(p => new
                        {
                            id_method     = p.webpages_Methods.id_method,
                            ds_method     = p.webpages_Methods.ds_method,
                            nm_method     = p.webpages_Methods.nm_method,
                            id_controller = p.webpages_Methods.id_controller
                        }
                                          ).ToList <dynamic>(),
                    }
                                             ).FirstOrDefault();

                    if (permissoes != null)
                    {
                        CollectionWebpages_Permissions = permissoes.metodos;
                    }

                    retorno.TotalDeRegistros = CollectionWebpages_Permissions.Count;
                }

                transaction.Commit();

                retorno.Registros = CollectionWebpages_Permissions;

                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 permissões" : 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();
                }
            }
        }
コード例 #28
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();
                }
            }
        }
コード例 #29
0
        /// <summary>
        /// Get Webpages_Permissions/Webpages_Permissions
        /// </summary>
        /// <param name="colecao"></param>
        /// <param name="campo"></param>
        /// <param name="orderby"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageNumber"></param>
        /// <param name="queryString"></param>
        /// <returns></returns>
        private static IQueryable <webpages_Permissions> getQuery(painel_taxservices_dbContext _db, int colecao, int campo, int orderby, int pageSize, int pageNumber, Dictionary <string, string> queryString)
        {
            // DEFINE A QUERY PRINCIPAL
            var entity = _db.webpages_Permissions.AsQueryable <webpages_Permissions>();

            #region WHERE - ADICIONA OS FILTROS A QUERY

            // ADICIONA OS FILTROS A QUERY
            foreach (var item in queryString)
            {
                int    key        = Convert.ToInt16(item.Key);
                CAMPOS filtroEnum = (CAMPOS)key;
                switch (filtroEnum)
                {
                case CAMPOS.ID_ROLES:
                    Int32 id_roles = Convert.ToInt32(item.Value);
                    entity = entity.Where(e => e.id_roles.Equals(id_roles)).AsQueryable <webpages_Permissions>();
                    break;

                case CAMPOS.ID_METHOD:
                    Int32 id_method = Convert.ToInt32(item.Value);
                    entity = entity.Where(e => e.id_method.Equals(id_method)).AsQueryable <webpages_Permissions>();
                    break;

                case CAMPOS.FL_PRINCIPAL:
                    Boolean fl_principal = Convert.ToBoolean(item.Value);
                    entity = entity.Where(e => e.fl_principal.Equals(fl_principal)).AsQueryable <webpages_Permissions>();
                    break;
                }
            }
            #endregion

            #region ORDER BY - ADICIONA A ORDENAÇÃO A QUERY
            // ADICIONA A ORDENAÇÃO A QUERY
            CAMPOS filtro = (CAMPOS)campo;
            switch (filtro)
            {
            case CAMPOS.ID_ROLES:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.id_roles).AsQueryable <webpages_Permissions>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.id_roles).AsQueryable <webpages_Permissions>();
                }
                break;

            case CAMPOS.ID_METHOD:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.id_method).AsQueryable <webpages_Permissions>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.id_method).AsQueryable <webpages_Permissions>();
                }
                break;

            case CAMPOS.FL_PRINCIPAL:
                if (orderby == 0)
                {
                    entity = entity.OrderBy(e => e.fl_principal).AsQueryable <webpages_Permissions>();
                }
                else
                {
                    entity = entity.OrderByDescending(e => e.fl_principal).AsQueryable <webpages_Permissions>();
                }
                break;
            }
            #endregion

            return(entity);
        }
コード例 #30
0
        /// <summary>
        /// Altera TbLoginAdquirenteEmpresa
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static void Update(string token, tbLoginAdquirenteEmpresa param, painel_taxservices_dbContext _dbContext = null)
        {
            painel_taxservices_dbContext _db;

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

            try
            {
                tbLoginAdquirenteEmpresa value = _db.tbLoginAdquirenteEmpresas
                                                 .Where(e => e.cdLoginAdquirenteEmpresa == param.cdLoginAdquirenteEmpresa)
                                                 .FirstOrDefault();

                if (value == null)
                {
                    throw new Exception("Registro inexistente");
                }

                // OBSERVAÇÂO: NÃO ALTERA GRUPO, CNPJ E ADQUIRENTE

                if (param.dsLogin != null && param.dsLogin != value.dsLogin)
                {
                    value.dsLogin = param.dsLogin;
                }
                if (param.dsSenha != null && param.dsSenha != value.dsSenha)
                {
                    value.dsSenha = param.dsSenha;
                }
                if (param.cdEstabelecimento != null && param.cdEstabelecimento != value.cdEstabelecimento)
                {
                    value.cdEstabelecimento = param.cdEstabelecimento;
                }
                if (param.stLoginAdquirente != value.stLoginAdquirente)
                {
                    value.stLoginAdquirente = param.stLoginAdquirente;
                }
                if (param.stLoginAdquirenteEmpresa != value.stLoginAdquirenteEmpresa)
                {
                    value.stLoginAdquirenteEmpresa = param.stLoginAdquirenteEmpresa;
                }
                if (param.nrCNPJCentralizadora != null && param.nrCNPJCentralizadora != value.nrCNPJCentralizadora)
                {
                    value.nrCNPJCentralizadora = param.nrCNPJCentralizadora;
                }
                if (param.cdEstabelecimentoConsulta != null && param.cdEstabelecimentoConsulta != value.cdEstabelecimentoConsulta)
                {
                    value.cdEstabelecimentoConsulta = param.cdEstabelecimentoConsulta;
                }
                value.dtAlteracao = DateTime.Now;
                _db.SaveChanges();
            }
            catch (Exception e)
            {
                if (e is DbEntityValidationException)
                {
                    string erro = MensagemErro.getMensagemErro((DbEntityValidationException)e);
                    throw new Exception(erro.Equals("") ? "Falha ao alterar login aquirente 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();
                }
            }
        }