Ejemplo n.º 1
0
    protected void Page_Load(object sender, EventArgs e)
    {
        LastPageThread = Convert.ToString(Session["LastPage"]);

        CatId   = Convert.ToString(Session["CatId"]);
        CatName = Convert.ToString(Session["CatName"]);
        QsId    = Convert.ToString(Session["ThreadId"]);


        //PostCounter();

        PostId = Request.QueryString["Id"];

        PostsRpt.DataSource = DataBaseQueries.GetThreadContent(QsId);
        PostsRpt.DataBind();

        TitleRpt.DataSource = DataBaseQueries.GetThreadTitle(QsId);
        TitleRpt.DataBind();

        TitleRpt2.DataSource = DataBaseQueries.GetThreadTitle(QsId);
        TitleRpt2.DataBind();

        if (!IsPostBack)
        {
            EditPostTextAreaRpt.DataSource = DataBaseQueries.GetPostContent(PostId);
            EditPostTextAreaRpt.DataBind();
        }
    }
Ejemplo n.º 2
0
    protected void EditCategoriesBtn_Click(object sender, EventArgs e)
    {
        //Makes it possible to read values from textboxes inside a repeater. Also calls Update method
        foreach (RepeaterItem item in EditCategoryRpt.Items)
        {
            //Creates empty string varibles which gets its value later
            //Category Name
            string Param1;

            //Category Description
            string Param2;

            //Fetches value from the textbox "EditCategoryNameTxt", and puts it inside a TEXTBOX VARIBLE called "EditCategoryNameTxt"
            TextBox EditCategoryNameTxt = (TextBox)item.FindControl("EditCategoryNameTxt");
            //Fetches value from the TEXTBOX VARIBLE "EditCategoryNameTxt", and puts it inside the empty STRING VARIABLE called "CatName"
            Param1 = EditCategoryNameTxt.Text;

            //Same principle as above
            TextBox EditCategoryDescriptionTxt = (TextBox)item.FindControl("EditCategoryDescriptionTxt");
            Param2 = EditCategoryDescriptionTxt.Text;

            //Calls Update method, which updates the table in the DB
            DataBaseQueries.UpdateEditDataInBD(QsModel, QsId, Param1, Param2);
        }

        Response.Redirect("Default.aspx");
    }
Ejemplo n.º 3
0
    protected void Page_Load(object sender, EventArgs e)
    {
        PostEditor.Visible        = Per.Allowed("CreatePost");
        PostEditorDivider.Visible = Per.Allowed("CreatePost");
        ShowEditor.Visible        = !Per.Allowed("CreatePost");

        Session["LastPage"] = Request.Url.PathAndQuery;

        CatId   = Convert.ToString(Session["CatId"]);
        CatName = Convert.ToString(Session["CatName"]);

        //Hvis bruger er logget ind skal ShpwEditor-knappen fjernes, og editoren skal vises.

        //PostCounter();

        QsId = Request.QueryString["Id"];
        Session["ThreadId"] = QsId;

        PostsRpt.DataSource = DataBaseQueries.GetThreadContent(QsId);
        PostsRpt.DataBind();

        TitleRpt.DataSource = DataBaseQueries.GetThreadTitle(QsId);
        TitleRpt.DataBind();

        TitleRpt2.DataSource = DataBaseQueries.GetThreadTitle(QsId);
        TitleRpt2.DataBind();

        //foreach (RepeaterItem item in PostsRpt.Items)
        //{
        //    FindControl("EditPostLink").Visible = false;
        //}
    }
Ejemplo n.º 4
0
    //int ThisUsersRoleId;

    protected void Page_Load(object sender, EventArgs e)
    {
        LastPage = Convert.ToString(Session["LastPage"]);

        UserId = Convert.ToInt32(Request.QueryString["Id"]);



        if (!IsPostBack)
        {
            EditUserInfoRpt.DataSource = DataBaseQueries.GetUserInfo(UserId);
            EditUserInfoRpt.DataBind();

            //UserRoleDdl.DataTextField = "RoleName";
            //UserRoleDdl.DataValueField = "RoleId";

            //Not yet used. Plan to use it for itemselector in dropdownlist
            //SelectorForRoleDropDownList(UserId);

            //ArrayList Roles = new ArrayList();
            //Roles = DataBaseQueries.GetRoles();

            //foreach (int item in Roles)
            //{

            //}


            //UserRoleDdl.SelectedValue =
            //UserRoleDdl.DataSource = Roles;
            //UserRoleDdl.DataBind();
        }
    }
Ejemplo n.º 5
0
    public static void CreatePrivilegeSession()
    {
        object RoleId = HttpContext.Current.Session["RoleId"];

        //Check user privileges Privileges (Arraylist)
        HttpContext.Current.Session["Privileges"] = DataBaseQueries.Privileges(RoleId);
    }
Ejemplo n.º 6
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Per.CreatePrivilegeSession();

        CreateCategoryLink.Visible          = Per.Allowed("CreateCategory");
        CreateCategoryLinkSeparator.Visible = Per.Allowed("CreateCategory");

        CategoriesRpt.DataSource = DataBaseQueries.GetCategoriesInfoForCategoryList();
        CategoriesRpt.DataBind();

        //SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
        //SqlCommand cmd = new SqlCommand();

        //cmd.CommandType = CommandType.StoredProcedure;
        //cmd.CommandText = "GetCategoriesInfo";

        //cmd.Connection = conn;

        //conn.Open();

        //SqlDataReader reader = cmd.ExecuteReader();

        //CategoriesRpt.DataSource = reader;
        //CategoriesRpt.DataBind();

        //conn.Close();
    }
Ejemplo n.º 7
0
 protected void CreateCategoriesBtn_Click(object sender, EventArgs e)
 {
     DataBaseQueries.CreateCategory(CreateCategoryNameTxt.Text, CreateCategoryDescriptionTxt.Text);
     CreateCategoryNameTxt.Text        = "";
     CreateCategoryDescriptionTxt.Text = "";
     Response.Redirect("Default.aspx");
 }
Ejemplo n.º 8
0
    protected void EditThreadBtn_Click(object sender, EventArgs e)
    {
        //Makes it possible to read values from textboxes inside a repeater. Also calls Update method
        foreach (RepeaterItem item in EditThreadRpt.Items)
        {
            //Creates empty string varibles
            //Thread Title
            string Param1;

            //Thread Content
            string Param2;

            //Fetches value from the textbox "EditThreadTitleTxt", and puts it inside a TEXTBOX VARIBLE called "EditThreadTitleTxt"
            TextBox EditThreadTitleTxt = (TextBox)item.FindControl("EditThreadTitleTxt");
            //Fetches value from the TEXTBOX VARIBLE "EditThreadTitleTxt", and puts it inside the empty STRING VARIABLE called "ThreadTitle"
            Param1 = EditThreadTitleTxt.Text;

            //Same principle as above
            TextBox EditThreadContentTxt = (TextBox)item.FindControl("EditThreadContentTxt");
            Param2 = EditThreadContentTxt.Text;

            //Calls Update method, which updates the table in the DB
            DataBaseQueries.UpdateEditDataInBD(QsModel, QsId, Param1, Param2);
        }

        //Link needs fixing.
        Response.Redirect(BackToCategory);
    }
Ejemplo n.º 9
0
    protected void CreateUserBtn_Click(object sender, EventArgs e)
    {
        //Validate og opret i DB
        if (ValidateInput())
        {
            //Insert into DB
            string UserName = CreateUserNameTxt.Text;
            string PassWord = CreateUserPassWordTxt.Text;
            string Email    = CreateUserEmailTxt.Text;
            int    RoleId   = 2;
            DataBaseQueries.CreateNewUser(UserName, PassWord, Email, RoleId);
            //Succes message
            Session["FlashMsgSucces"] = "<strong>Succes!</strong><br /> Du er nu oprettet";
            //Gemmer brugernavn og password i session og sender brugeren videre til Login, hvor session bliver brugt til at udfylde tekstfelterne
            Session["UserName"] = UserName;
            Session["PassWord"] = PassWord;
            Response.Redirect("Login.aspx");
        }

        //Errormessage if not ok
        else
        {
            PanelMsgFejl.Visible = true;

            //Session metoden virker kun, hvis man refresher siden. Derfor er den deaktiveret.
            //Har ikke slettet den, hvis der skulle dukke en god metode op til at refreshe uden, at man mister inputtet
            //Session["FlashMsgDanger"] = "<strong>Fejl!</strong><br /> Tjek din indtastning";
        }
    }
Ejemplo n.º 10
0
    protected void Page_Load(object sender, EventArgs e)
    {
        CatId   = Convert.ToString(Session["CatId"]);
        QsModel = Request.QueryString["Model"];
        QsId    = Request.QueryString["Id"];

        //Her defineres variablen der kaldes ved bekræftelse af sletning. Den indeholder Navnet på det der slettes
        ModelTitleText = Convert.ToString(DataBaseQueries.GetModelTitle(QsModel, QsId));
    }
Ejemplo n.º 11
0
    protected void CheckBoxList1_DataBound(object sender, EventArgs e)
    {
        ArrayList NyList = DataBaseQueries.GetSelectedItemsForThisRole("3");

        foreach (ListItem item in CheckBoxList1.Items)
        {
            if (NyList.Contains(Convert.ToInt32(item.Value)))
            {
                item.Selected = true;
            }
        }
    }
Ejemplo n.º 12
0
    protected void CreateThreadBtn_Click(object sender, EventArgs e)
    {
        string CatId         = Request.QueryString["CatId"];
        int    UserId        = Convert.ToInt32(Session["UserId"]);
        string ThreadTitle   = CreateThreadTitleTxt.Text;
        string ThreadContent = CreateThreadContentTxt.Text;

        string ThreadId = DataBaseQueries.CreateThread(UserId, CatId, ThreadTitle, ThreadContent);

        CreateThreadTitleTxt.Text   = "";
        CreateThreadContentTxt.Text = "";
        Response.Redirect("Thread.aspx?Id=" + ThreadId);
    }
Ejemplo n.º 13
0
    //ArrayList AllPrivileges;

    protected void Page_Load(object sender, EventArgs e)
    {
        PrivilegesCbl.DataSource = DataBaseQueries.GetAllPrivileges();
        PrivilegesCbl.DataBind();

        Selected = DataBaseQueries.GetSelectedItemsForThisRole(RolesDdl.SelectedValue);
        foreach (ListItem item in PrivilegesCbl.Items)
        {
            if (Selected.Contains(Convert.ToInt32(item.Value)))
            {
                item.Selected = true;
            }
        }
    }
Ejemplo n.º 14
0
    protected void SubmitPostBtn_Click(object sender, EventArgs e)
    {
        int    UserId  = Convert.ToInt32(Session["UserId"]);
        string NewPost = SubmitPostTA.InnerText;

        DataBaseQueries.CreateNewPost(UserId, QsId, NewPost);

        SubmitPostTA.InnerText = "";

        //Refreshes page
        string RefreshThisPage = Convert.ToString(Session["LastPage"]);

        Response.Redirect(RefreshThisPage);
    }
 public RegistrationController(UserManager <IdentityUser> userManager,
                               SignInManager <IdentityUser> signInManager,
                               RoleManager <IdentityRole> roleManager,
                               ILogger <ApplicationUser> logger,
                               IEmailSender emailSender,
                               ApplicationDbContext context,
                               HostingEnvironment hostingEnvironment)
 {
     _userManager        = userManager;
     _signInManager      = signInManager;
     _roleManager        = roleManager;
     _logger             = logger;
     _emailSender        = emailSender;
     _context            = context;
     _dataBaseQueries    = new DataBaseQueries(context);
     _hostingEnvironment = hostingEnvironment;
 }
Ejemplo n.º 16
0
    protected void SubmitPostBtn_Click(object sender, EventArgs e)
    {
        //Makes it possible to read values from textboxes inside a repeater. Also calls Update method
        foreach (RepeaterItem item in EditPostTextAreaRpt.Items)
        {
            //Creates empty string varibles
            //Post Content
            string EditedPost;

            //Fetches value from the textbox "SubmitPostTA", and puts it inside a TEXTBOX VARIBLE called "SubmitPostTA"
            TextBox SubmitPostTA = (TextBox)item.FindControl("SubmitPostTA");
            EditedPost = SubmitPostTA.Text;

            DataBaseQueries.UpdatePostContent(PostId, EditedPost);
            Response.Redirect(LastPageThread);
        }
    }
Ejemplo n.º 17
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["UserId"] == null)
        {
            Response.Redirect("Default.aspx");
        }
        else
        {
            Session["LastPage"] = Request.Url.PathAndQuery;

            UserId = Convert.ToInt32(Session["UserId"]);


            MyInfoRpt.DataSource = DataBaseQueries.GetUserInfo(UserId);
            MyInfoRpt.DataBind();
        }
    }
Ejemplo n.º 18
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Per.Allowed("ShowUserList"))
        {
            Response.Redirect("Default.aspx");
        }
        else
        {
            Session["LastPage"] = Request.Url.PathAndQuery;

            if (!IsPostBack)
            {
                UserListRpt.DataSource = DataBaseQueries.GetUserListInfo();
                UserListRpt.DataBind();
            }
        }
    }
Ejemplo n.º 19
0
    protected void Page_Load(object sender, EventArgs e)
    {
        LastPage = Convert.ToString(Session["LastPage"]).Trim();
        UserName = Convert.ToString(Session["UserName"]);
        PassWord = Convert.ToString(Session["PassWord"]);
        string RoleId;

        //Authenticate
        if (DataBaseQueries.AuthenticateUserCredentials(UserName, PassWord))
        {
            //Build Session:
            //UserId, RoleId
            RoleId = Convert.ToString(Session["RoleId"]);

            //Get privileges
            Per.CreatePrivilegeSession();

            //Return to last page or frontpage?___//
            if (LastPage != null && LastPage != "")
            {
                //Back to the last page
                Response.Redirect(LastPage);
            }
            else
            {
                //Til Forsiden
                Response.Redirect("Default.aspx");
            }

            //____________________________________//
        }
        else
        {
            //sæt brugerens rolle til gæst
            RoleId = "3";
            //Get privileges
            Per.CreatePrivilegeSession();

            //Fejl. Brugeren findes ikke
            Session["FlashMsgDanger"] = "Fejl i brugernavn eller password";

            //Tilbage til Login-siden
            Response.Redirect("Login.aspx");
        }
    }
Ejemplo n.º 20
0
    protected void SaveEditedUserBtn_Click(object sender, EventArgs e)
    {
        UserRole = Convert.ToInt32(UserRoleDdl.SelectedValue);

        //Makes it possible to read values from textboxes inside a repeater. Also calls Update method
        foreach (RepeaterItem item in EditUserInfoRpt.Items)
        {
            //Creates empty string varibles
            //Thread Title
            string UserName;

            //Thread Content
            string Email;

            //Thread Title
            string Password;

            //string UserRole;

            //Fetches value from the textbox "UserNameTxt", and puts it inside a TEXTBOX VARIBLE called "UserNameTxt"
            TextBox UserNameTxt = (TextBox)item.FindControl("UserNameTxt");
            //Fetches value from the TEXTBOX VARIBLE "UserNameTxt", and puts it inside the empty STRING VARIABLE called "UserName"
            UserName = UserNameTxt.Text;

            //Same principle as above
            TextBox EmailTxt = (TextBox)item.FindControl("EmailTxt");
            Email = EmailTxt.Text;

            //Same principle as above
            TextBox UserPasswordTxt = (TextBox)item.FindControl("UserPasswordTxt");
            Password = UserPasswordTxt.Text;

            //TextBox UserRoleTxt = (TextBox)item.FindControl("UserRoleTxt");
            //UserRole = UserRoleTxt.Text;

            //Calls Update method, which updates the table in the DB
            DataBaseQueries.UpdateEditedUserDataInDB(UserId, UserName, Email, Password, UserRole);
        }

        //DataBaseQueries.EditUserInfoRpt();


        Response.Redirect(LastPage);
    }
Ejemplo n.º 21
0
    protected void ContinueDeletetion_Click(object sender, EventArgs e)
    {
        switch (QsModel)
        {
        //case "Category": Response.Write(QsId);
        //    break;
        case "Category": DataBaseQueries.DeleteCategory(QsId);
            break;

        case "Thread": DataBaseQueries.DeleteThread(QsId);
            break;

        //case "Post": DataBaseQueries.DeletePost(QsId);
        //    break;
        case "User": DataBaseQueries.DeleteUser(QsId);
            break;
        }


        switch (QsModel)
        {
        case "Category": Response.Redirect("Default.aspx");
            break;

        case "Thread": Response.Redirect("Category.aspx?Id=" + CatId);
            break;
        //Not sure if allowing Post-deletion in a forum is a good idea.
        //Need to find a way to paste "Post deleted" and disabling deletion of first post in thread if it should be allowed
        //case "Post": Response.Redirect("Thread.aspx?Id=" + ThreadId);
        //    break;


        ///VIRKER IKKE ENDNU
        case "User": if (Convert.ToString(Session["UserId"]) == QsId)
            {
                Response.Redirect("logOut.aspx");
            }
            else
            {
                Response.Redirect("UserList.aspx");
            }
            break;
        }
    }
Ejemplo n.º 22
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //Adds value to BackToCategory variable
        BackToCategory = Convert.ToString(Session["LastPage"]);

        QsModel = Request.QueryString["Model"];
        QsId    = Request.QueryString["Id"];

        ////Til debugging
        //Response.Write(DataBaseQueries.GetEditDataFromDb(QsModel, QsId));


        BreadCrumbRpt.DataSource = DataBaseQueries.GetEditDataFromDb(QsModel, QsId);
        BreadCrumbRpt.DataBind();

        if (!IsPostBack)
        {
            InsertThreadToTextBoxes();
        }
    }
Ejemplo n.º 23
0
    protected void Page_Load(object sender, EventArgs e)
    {
        CreateThreadLink.Visible = Per.Allowed("CreateThread");

        Session["LastPage"] = Request.Url.PathAndQuery;

        QsModel = "Category";

        QsId             = Request.QueryString["Id"];
        Session["CatId"] = QsId;

        CatName = Convert.ToString(DataBaseQueries.GetModelTitle(QsModel, QsId));

        Session["CatName"] = CatName;
        Session["CatId"]   = QsId;



        ThreadRpt.DataSource = DataBaseQueries.GetThreadInfoData(QsId);
        ThreadRpt.DataBind();
    }
Ejemplo n.º 24
0
    public static bool IsThreadMine(string CodeName, object ThreadId)
    {
        int UserId = Convert.ToInt32(HttpContext.Current.Session["UserId"]);

        //Tjekke rettigheder
        if (Allowed(CodeName))
        {
            //PostOwner ejer ALLE indlæg. Bruges til fx. Admin eller moderator, som skal kunne slette alle indlæg
            if (CodeName == "IsThreadOwner")
            {
                return(true);
            }
            else
            {
                //Tjekke ejerskab
                return(DataBaseQueries.IsPostMine(UserId, ThreadId));
            }
        }
        else
        {
            return(false);
        }
    }
Ejemplo n.º 25
0
 public ResultController(ApplicationDbContext context)
 {
     _context         = context;
     _dataBaseQueries = new DataBaseQueries(context);
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Get TbRecebimentoVenda/TbRecebimentoVenda
        /// </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 SimpleDataBaseQuery getQuery(int campo, int orderby, Dictionary <string, string> queryString)
        {
            Dictionary <string, string> join = new Dictionary <string, string>();

            List <string> where = new List <string>();
            List <string> order = new List <string>();

            #region WHERE - ADICIONA OS FILTROS A QUERY
            // ADICIONA OS FILTROS A QUERY
            foreach (KeyValuePair <string, string> item in queryString)
            {
                int    key        = Convert.ToInt16(item.Key);
                CAMPOS filtroEnum = (CAMPOS)key;
                switch (filtroEnum)
                {
                case CAMPOS.IDRECEBIMENTOVENDA:
                    Int32 idRecebimentoVenda = Convert.ToInt32(item.Value);
                    where.Add(SIGLA_QUERY + ".idRecebimentoVenda = " + idRecebimentoVenda);
                    break;

                case CAMPOS.NRCNPJ:
                    string nrCNPJ = Convert.ToString(item.Value);
                    where.Add(SIGLA_QUERY + ".nrCNPJ = '" + nrCNPJ + "'");
                    break;

                case CAMPOS.NRNSU:
                    string nrNSU = Convert.ToString(item.Value);
                    if (nrNSU.Contains("%"))     // usa LIKE => ENDS WITH
                    {
                        string busca = nrNSU.Replace("%", "").ToString();
                        where.Add(SIGLA_QUERY + ".nrNSU like '%" + busca + "'");
                    }
                    else
                    {
                        where.Add(SIGLA_QUERY + ".nrNSU = '" + nrNSU + "'");
                    }
                    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);
                        string   dtInicio = DataBaseQueries.GetDate(dtaIni);
                        string   dtFim    = DataBaseQueries.GetDate(dtaFim);
                        where.Add(SIGLA_QUERY + ".dtVenda BETWEEN '" + dtInicio + "' AND '" + dtFim + " 23:59:00'");
                    }
                    else     // IGUAL
                    {
                        string   busca = item.Value;
                        DateTime data  = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        string   dt    = DataBaseQueries.GetDate(data);
                        where.Add(SIGLA_QUERY + ".dtVenda BETWEEN '" + dt + "' AND '" + dt + " 23:59:00'");
                    }
                    break;

                case CAMPOS.CDADQUIRENTE:
                    Int32 cdAdquirente = Convert.ToInt32(item.Value);
                    where.Add(SIGLA_QUERY + ".cdAdquirente = " + cdAdquirente);
                    break;

                case CAMPOS.DSBANDEIRA:
                    string dsBandeira = Convert.ToString(item.Value);
                    where.Add(SIGLA_QUERY + ".dsBandeira = '" + dsBandeira + "'");
                    break;

                case CAMPOS.VLVENDA:
                    decimal vlVenda = Convert.ToDecimal(item.Value);
                    where.Add(SIGLA_QUERY + ".vlVenda = " + vlVenda.ToString(CultureInfo.GetCultureInfo("en-GB")));
                    break;

                case CAMPOS.QTPARCELAS:
                    byte qtParcelas = Convert.ToByte(item.Value);
                    where.Add(SIGLA_QUERY + ".qtParcelas = " + qtParcelas);
                    break;

                case CAMPOS.CDERP:
                    string cdERP = Convert.ToString(item.Value);
                    where.Add(SIGLA_QUERY + ".cdERP = '" + cdERP + "'");
                    break;

                case CAMPOS.CDSACADO:
                    string cdSacado = Convert.ToString(item.Value);
                    where.Add(SIGLA_QUERY + ".cdSacado = '" + cdSacado + "'");
                    break;

                case CAMPOS.DTAJUSTE:
                    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);
                        string   dtInicio = DataBaseQueries.GetDate(dtaIni);
                        string   dtFim    = DataBaseQueries.GetDate(dtaFim);
                        where.Add(SIGLA_QUERY + ".dtAjuste BETWEEN '" + dtInicio + "' AND '" + dtFim + " 23:59:00'");
                    }
                    else     // IGUAL
                    {
                        string   busca = item.Value;
                        DateTime data  = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        string   dt    = DataBaseQueries.GetDate(data);
                        where.Add(SIGLA_QUERY + ".dtAjuste BETWEEN '" + dt + "' AND '" + dt + " 23:59:00'");
                    }
                    break;

                case CAMPOS.DSMENSAGEM:
                    string dsMensagem = Convert.ToString(item.Value);
                    where.Add(SIGLA_QUERY + ".dsMensagem = '" + dsMensagem + "'");
                    break;

                case CAMPOS.DSDETALHE:
                    string dsDetalhe = Convert.ToString(item.Value);
                    where.Add(SIGLA_QUERY + ".dsDetalhe = '" + dsDetalhe + "'");
                    break;

                // RELACIONAMENTOS
                case CAMPOS.ID_GRUPO:
                    Int32 id_grupo = Convert.ToInt32(item.Value);
                    // JOIN
                    if (!join.ContainsKey("INNER JOIN cliente.empresa " + GatewayEmpresa.SIGLA_QUERY))
                    {
                        join.Add("INNER JOIN cliente.empresa " + GatewayEmpresa.SIGLA_QUERY, " ON " + SIGLA_QUERY + ".nrCNPJ = " + GatewayEmpresa.SIGLA_QUERY + ".nu_cnpj");
                    }
                    where.Add(GatewayEmpresa.SIGLA_QUERY + ".id_grupo = " + id_grupo);
                    break;
                }
            }
            #endregion

            string outValue = null;
            if (queryString.TryGetValue("" + (int)CAMPOS.TIPO, out outValue))
            {
                string      script = String.Empty;
                TIPO_FILTRO tipo   = (TIPO_FILTRO)Convert.ToInt32(queryString["" + (int)CAMPOS.TIPO]);
                switch (tipo)
                {
                case TIPO_FILTRO.CONCILIADO:
                    // Adiciona o join
                    if (!join.ContainsKey("LEFT JOIN pos.Recebimento " + GatewayRecebimento.SIGLA_QUERY))
                    {
                        join.Add("LEFT JOIN pos.Recebimento " + GatewayRecebimento.SIGLA_QUERY, " ON " + GatewayRecebimento.SIGLA_QUERY + ".idRecebimentoVenda = " + SIGLA_QUERY + ".idRecebimentoVenda");
                    }
                    where.Add(GatewayRecebimento.SIGLA_QUERY + ".idRecebimentoVenda IS NOT NULL");
                    break;

                case TIPO_FILTRO.NAO_CONCILIADO:
                    // Adiciona o join
                    if (!join.ContainsKey("LEFT JOIN pos.Recebimento " + GatewayRecebimento.SIGLA_QUERY))
                    {
                        join.Add("LEFT JOIN pos.Recebimento " + GatewayRecebimento.SIGLA_QUERY, " ON " + GatewayRecebimento.SIGLA_QUERY + ".idRecebimentoVenda = " + SIGLA_QUERY + ".idRecebimentoVenda");
                    }
                    where.Add(GatewayRecebimento.SIGLA_QUERY + ".idRecebimentoVenda IS NULL");
                    break;

                case TIPO_FILTRO.CORRIGIDO:
                    where.Add(SIGLA_QUERY + ".dtAjuste IS NOT NULL");
                    break;

                case TIPO_FILTRO.CORRECAO_MANUAL:
                    where.Add(SIGLA_QUERY + ".dtAjuste IS NOT NULL && " + SIGLA_QUERY + ".dsMensagem IS NOT NULL");
                    break;
                }
            }

            #region ORDER BY - ADICIONA A ORDENAÇÃO A QUERY
            // ADICIONA A ORDENAÇÃO A QUERY
            CAMPOS filtro = (CAMPOS)campo;
            switch (filtro)
            {
            case CAMPOS.IDRECEBIMENTOVENDA:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".idRecebimentoVenda ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".idRecebimentoVenda DESC");
                }
                break;

            case CAMPOS.NRCNPJ:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".nrCNPJ ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".nrCNPJ DESC");
                }
                break;

            case CAMPOS.NRNSU:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".nrNSU ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".nrNSU DESC");
                }
                break;

            case CAMPOS.DTVENDA:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".dtVenda ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".dtVenda DESC");
                }
                break;

            case CAMPOS.CDADQUIRENTE:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".cdAdquirente ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".cdAdquirente DESC");
                }
                break;

            case CAMPOS.DSBANDEIRA:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".dsBandeira ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".dsBandeira DESC");
                }
                break;

            case CAMPOS.VLVENDA:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".vlVenda ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".vlVenda DESC");
                }
                break;

            case CAMPOS.QTPARCELAS:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".qtParcelas ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".qtParcelas DESC");
                }
                break;

            case CAMPOS.CDERP:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".cdERP ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".cdERP DESC");
                }
                break;

            case CAMPOS.CDSACADO:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".cdSacado ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".cdSacado DESC");
                }
                break;

            case CAMPOS.DTAJUSTE:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".dtAjuste ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".dtAjuste DESC");
                }
                break;

            case CAMPOS.DSMENSAGEM:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".dsMensagem ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".dsMensagem DESC");
                }
                break;
            }
            #endregion

            return(new SimpleDataBaseQuery(null, "card.tbRecebimentoVenda " + SIGLA_QUERY,
                                           join, where.ToArray(), null, order.ToArray()));
        }
Ejemplo n.º 27
0
 public ExistingResultController(ApplicationDbContext context)
 {
     _dataBaseQueries = new DataBaseQueries(context);
 }
Ejemplo n.º 28
0
        /// <summary>
        /// Get TbRecebimentoAjuste/TbRecebimentoAjuste
        /// </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 SimpleDataBaseQuery getQuery(int campo, int orderby, Dictionary <string, string> queryString)
        {
            Dictionary <string, string> join = new Dictionary <string, string>();

            List <string> where = new List <string>();
            List <string> order = new List <string>();

            #region WHERE - ADICIONA OS FILTROS A QUERY
            // ADICIONA OS FILTROS A QUERY
            foreach (KeyValuePair <string, string> item in queryString)
            {
                int    key        = Convert.ToInt16(item.Key);
                CAMPOS filtroEnum = (CAMPOS)key;
                switch (filtroEnum)
                {
                case CAMPOS.IDRECEBIMENTOAJUSTE:
                    Int32 idRecebimentoAjuste = Convert.ToInt32(item.Value);
                    where.Add(SIGLA_QUERY + ".idRecebimentoAjuste = " + idRecebimentoAjuste);
                    break;

                case CAMPOS.DTAJUSTE:
                    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);
                        string   dtInicio = DataBaseQueries.GetDate(dtaIni);
                        string   dtFim    = DataBaseQueries.GetDate(dtaFim);
                        where.Add(SIGLA_QUERY + ".dtAjuste BETWEEN '" + dtInicio + "' AND '" + dtFim + " 23:59:00'");
                    }
                    else if (item.Value.Contains(">"))     // MAIOR IGUAL
                    {
                        string busca = item.Value.Replace(">", "");
                        if (busca.Contains("@"))
                        {
                            // Inclui registros de saldo de antecipação bancária
                            busca = busca.Replace("@", "");
                            DateTime dta = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                            string   dt  = DataBaseQueries.GetDate(dta);
                            where.Add(SIGLA_QUERY + ".dtAjuste >= '" + dt + "' OR (" +
                                      SIGLA_QUERY + ".dsMotivo LIKE 'SALDO ANTECIPAÇÃO BANCÁRIA%' AND " +
                                      "CONVERT(smalldatetime, SUBSTRING(" + SIGLA_QUERY + ".dsMotivo, CHARINDEX('VENCIMENTO', " + SIGLA_QUERY + ".dsMotivo) + 11, 10), 103) >= '" + dt + "')");
                        }
                        else
                        {
                            DateTime dta = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                            string   dt  = DataBaseQueries.GetDate(dta);
                            where.Add(SIGLA_QUERY + ".dtAjuste >= '" + dt + "'");
                        }
                    }
                    else if (item.Value.Contains("<"))     // MENOR IGUAL
                    {
                        string   busca = item.Value.Replace("<", "");
                        DateTime dta   = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        string   dt    = DataBaseQueries.GetDate(dta);
                        where.Add(SIGLA_QUERY + ".dtAjuste <= '" + dt + " 23:59:00'");
                    }
                    //else if (item.Value.Length == 4)
                    //{
                    //    string busca = item.Value + "0101";
                    //    DateTime data = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                    //    where.Add("DATEPART(YEAR, " + SIGLA_QUERY + ".dtAjuste) = " + data.Year);
                    //}
                    else if (item.Value.Length == 6)
                    {
                        string   busca = item.Value + "01";
                        DateTime data  = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        where.Add("DATEPART(YEAR, " + SIGLA_QUERY + ".dtAjuste) = " + data.Year + " AND DATEPART(MONTH, " + SIGLA_QUERY + ".dtAjuste) = " + data.Month);
                    }
                    else     // IGUAL
                    {
                        string   busca = item.Value;
                        DateTime data  = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        string   dt    = DataBaseQueries.GetDate(data);
                        where.Add(SIGLA_QUERY + ".dtAjuste BETWEEN '" + dt + "' AND '" + dt + " 23:59:00'");
                    }
                    break;

                case CAMPOS.NRCNPJ:
                    string nrCNPJ = Convert.ToString(item.Value);
                    where.Add(SIGLA_QUERY + ".nrCNPJ = '" + nrCNPJ + "'");
                    break;

                case CAMPOS.CDBANDEIRA:
                    Int32 cdBandeira = Convert.ToInt32(item.Value);
                    where.Add(SIGLA_QUERY + ".cdBandeira = " + cdBandeira);
                    break;

                case CAMPOS.DSMOTIVO:
                    string dsMotivo = Convert.ToString(item.Value);
                    where.Add(SIGLA_QUERY + ".dsMotivo = '" + dsMotivo + "'");
                    break;

                case CAMPOS.VLAJUSTE:
                    decimal vlAjuste = Convert.ToDecimal(item.Value);
                    where.Add(SIGLA_QUERY + ".vlAjuste = " + vlAjuste.ToString(CultureInfo.GetCultureInfo("en-GB")));
                    break;

                case CAMPOS.IDEXTRATO:
                    Int32 idExtrato = Convert.ToInt32(item.Value);
                    where.Add(SIGLA_QUERY + ".idExtrato = " + idExtrato);
                    break;

                case CAMPOS.IDRESUMOVENDA:
                    Int32 idResumoVenda = Convert.ToInt32(item.Value);
                    where.Add(SIGLA_QUERY + ".idResumoVenda = " + idResumoVenda);
                    break;

                case CAMPOS.FLANTECIPACAO:
                    Boolean flAntecipacao = Convert.ToBoolean(item.Value);
                    where.Add(SIGLA_QUERY + ".flAntecipacao = " + DataBaseQueries.GetBoolean(flAntecipacao));
                    break;

                case CAMPOS.IDANTECIPACAOBANCARIADETALHE:
                    Int32 idAntecipacaoBancariaDetalhe = Convert.ToInt32(item.Value);
                    where.Add(SIGLA_QUERY + ".idAntecipacaoBancariaDetalhe = " + idAntecipacaoBancariaDetalhe);
                    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);
                        string   dtInicio = DataBaseQueries.GetDate(dtaIni);
                        string   dtFim    = DataBaseQueries.GetDate(dtaFim);
                        where.Add(SIGLA_QUERY + ".dtVenda BETWEEN '" + dtInicio + "' AND '" + dtFim + " 23:59:00'");
                    }
                    else if (item.Value.Contains(">"))     // MAIOR IGUAL
                    {
                        string   busca = item.Value.Replace(">", "");
                        DateTime dta   = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        string   dt    = DataBaseQueries.GetDate(dta);
                        where.Add(SIGLA_QUERY + ".dtVenda >= '" + dt + "'");
                    }
                    else if (item.Value.Contains("<"))     // MENOR IGUAL
                    {
                        string   busca = item.Value.Replace("<", "");
                        DateTime dta   = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        string   dt    = DataBaseQueries.GetDate(dta);
                        where.Add(SIGLA_QUERY + ".dtVenda <= '" + dt + " 23:59:00'");
                    }
                    //else if (item.Value.Length == 4)
                    //{
                    //    string busca = item.Value + "0101";
                    //    DateTime data = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                    //    where.Add("DATEPART(YEAR, " + SIGLA_QUERY + ".dtVenda) = " + data.Year);
                    //}
                    else if (item.Value.Length == 6)
                    {
                        string   busca = item.Value + "01";
                        DateTime data  = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        where.Add("DATEPART(YEAR, " + SIGLA_QUERY + ".dtVenda) = " + data.Year + " AND DATEPART(MONTH, " + SIGLA_QUERY + ".dtVenda) = " + data.Month);
                    }
                    else     // IGUAL
                    {
                        string   busca = item.Value;
                        DateTime data  = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        string   dt    = DataBaseQueries.GetDate(data);
                        where.Add(SIGLA_QUERY + ".dtVenda BETWEEN '" + dt + "' AND '" + dt + " 23:59:00'");
                    }
                    break;

                // RELACIONAMENTOS
                case CAMPOS.ID_GRUPO:
                    // Adiciona os joins
                    if (!join.ContainsKey("INNER JOIN cliente.empresa " + GatewayEmpresa.SIGLA_QUERY))
                    {
                        join.Add("INNER JOIN cliente.empresa " + GatewayEmpresa.SIGLA_QUERY, " ON " + GatewayEmpresa.SIGLA_QUERY + ".nu_cnpj = " + SIGLA_QUERY + ".nrCNPJ");
                    }
                    Int32 id_grupo = Convert.ToInt32(item.Value);
                    where.Add(GatewayEmpresa.SIGLA_QUERY + ".id_grupo = " + id_grupo);
                    break;

                case CAMPOS.CDADQUIRENTE:
                    // Adiciona os joins
                    if (!join.ContainsKey("INNER JOIN card.tbBandeira " + GatewayTbBandeira.SIGLA_QUERY))
                    {
                        join.Add("INNER JOIN card.tbBandeira " + GatewayTbBandeira.SIGLA_QUERY, " ON " + GatewayTbBandeira.SIGLA_QUERY + ".cdBandeira = " + SIGLA_QUERY + ".cdBandeira");
                    }
                    Int32 cdAdquirente = Convert.ToInt32(item.Value);
                    where.Add(GatewayTbBandeira.SIGLA_QUERY + ".cdAdquirente = " + cdAdquirente);
                    break;

                case CAMPOS.DSTIPO:
                    // Adiciona os joins
                    if (!join.ContainsKey("INNER JOIN card.tbBandeira " + GatewayTbBandeira.SIGLA_QUERY))
                    {
                        join.Add("INNER JOIN card.tbBandeira " + GatewayTbBandeira.SIGLA_QUERY, " ON " + GatewayTbBandeira.SIGLA_QUERY + ".cdBandeira = " + SIGLA_QUERY + ".cdBandeira");
                    }
                    string dsTipo = Convert.ToString(item.Value).TrimEnd();
                    where.Add(GatewayTbBandeira.SIGLA_QUERY + ".dsTipo like '" + dsTipo + "%'");
                    break;

                case CAMPOS.SEM_AJUSTES_ANTECIPACAO:
                    bool   excludeBanese = false;
                    string v             = item.Value;
                    if (v.Contains("~7"))
                    {
                        // sem banese
                        excludeBanese = true;
                        v             = v.Substring(0, v.IndexOf("~"));
                    }

                    if (Convert.ToBoolean(v))
                    {
                        string ajustesCielo = "'" + string.Join("', '", AJUSTES_ANTECIPACAO_CIELO) + "'";
                        // Adiciona os joins
                        if (!join.ContainsKey("INNER JOIN card.tbBandeira " + GatewayTbBandeira.SIGLA_QUERY))
                        {
                            join.Add("INNER JOIN card.tbBandeira " + GatewayTbBandeira.SIGLA_QUERY, " ON " + GatewayTbBandeira.SIGLA_QUERY + ".cdBandeira = " + SIGLA_QUERY + ".cdBandeira");
                        }

                        if (excludeBanese)
                        {
                            // Sem Banese => Por enquanto, só trata Cielo
                            where.Add(GatewayTbBandeira.SIGLA_QUERY + ".cdAdquirente != 2" + " OR " + SIGLA_QUERY + ".dsMotivo NOT IN (" + ajustesCielo + ")");
                        }
                        else
                        {
                            // Por enquanto, só trata da Cielo e Banese
                            string ajustesBanese = "'" + string.Join("', '", AJUSTES_ANTECIPACAO_BANESE) + "'";
                            where.Add("(" + GatewayTbBandeira.SIGLA_QUERY + ".cdAdquirente NOT IN (2, 7))" +
                                      " OR (" + GatewayTbBandeira.SIGLA_QUERY + ".cdAdquirente = 2 AND " + SIGLA_QUERY + ".dsMotivo NOT IN (" + ajustesCielo + "))" +
                                      " OR (" + GatewayTbBandeira.SIGLA_QUERY + ".cdAdquirente = 7 AND " + SIGLA_QUERY + ".dsMotivo NOT IN (" + ajustesBanese + "))");
                        }
                    }
                    break;

                //case CAMPOS.AJUSTES_VENDA:
                //    if (Convert.ToBoolean(item.Value))
                //    {
                //        string ajustes = string.Join("', '", AJUSTES_VENDA_BANESE);
                //        if (!ajustes.Equals(""))
                //        {
                //            // Por enquanto, só trata do Banese
                //            ajustes = "'" + ajustes + "'";
                //            // Adiciona os joins
                //            if (!join.ContainsKey("INNER JOIN card.tbBandeira " + GatewayTbBandeira.SIGLA_QUERY))
                //                join.Add("INNER JOIN card.tbBandeira " + GatewayTbBandeira.SIGLA_QUERY, " ON " + GatewayTbBandeira.SIGLA_QUERY + ".cdBandeira = " + SIGLA_QUERY + ".cdBandeira");
                //            where.Add(GatewayTbBandeira.SIGLA_QUERY + ".cdAdquirente = 7 AND " + SIGLA_QUERY + ".dsMotivo IN (" + ajustes + ")");
                //        }
                //    }
                //    break;
                case CAMPOS.CDCONTACORRENTE:
                    Int32 cdContaCorrente = Convert.ToInt32(item.Value);
                    if (cdContaCorrente > 0)
                    {
                        // Obtém as filiais da conta
                        string filiaisDaConta     = "'" + string.Join("', '", Permissoes.GetFiliaisDaConta(cdContaCorrente, (painel_taxservices_dbContext)null)) + "'";
                        string adquirentesDaConta = string.Join(", ", Permissoes.GetAdquirentesDaConta(cdContaCorrente, (painel_taxservices_dbContext)null));
                        // Adiciona os joins
                        if (!join.ContainsKey("INNER JOIN card.tbBandeira " + GatewayTbBandeira.SIGLA_QUERY))
                        {
                            join.Add("INNER JOIN card.tbBandeira " + GatewayTbBandeira.SIGLA_QUERY, " ON " + GatewayTbBandeira.SIGLA_QUERY + ".cdBandeira = " + SIGLA_QUERY + ".cdBandeira");
                        }
                        where.Add(GatewayTbBandeira.SIGLA_QUERY + ".cdAdquirente in (" + adquirentesDaConta + ")");
                        where.Add(SIGLA_QUERY + ".nrCNPJ in (" + filiaisDaConta + ")");
                    }
                    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.IDRECEBIMENTOAJUSTE:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".idRecebimentoAjuste ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".idRecebimentoAjuste DESC");
                }
                break;

            case CAMPOS.DTAJUSTE:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".dtAjuste ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".dtAjuste DESC");
                }
                break;

            case CAMPOS.NRCNPJ:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".nrCNPJ ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".nrCNPJ DESC");
                }
                break;

            case CAMPOS.CDBANDEIRA:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".cdBandeira ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".cdBandeira DESC");
                }
                break;

            case CAMPOS.DSMOTIVO:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".dsMotivo ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".dsMotivo DESC");
                }
                break;

            case CAMPOS.VLAJUSTE:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".vlAjuste ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".vlAjuste DESC");
                }
                break;

            case CAMPOS.IDEXTRATO:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".idExtrato ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".idExtrato DESC");
                }
                break;

            case CAMPOS.IDRESUMOVENDA:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".idResumoVenda ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".idResumoVenda DESC");
                }
                break;

            case CAMPOS.FLANTECIPACAO:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".flAntecipacao ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".flAntecipacao DESC");
                }
                break;

            case CAMPOS.IDANTECIPACAOBANCARIADETALHE:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".idAntecipacaoBancariaDetalhe ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".idAntecipacaoBancariaDetalhe DESC");
                }
                break;

            case CAMPOS.DTVENDA:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".dtVenda ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".dtVenda DESC");
                }
                break;
            }
            #endregion

            return(new SimpleDataBaseQuery(null, "card.tbRecebimentoAjuste " + SIGLA_QUERY,
                                           join, where.ToArray(), null, order.ToArray()));
        }
Ejemplo n.º 29
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();
                }
            }
        }
Ejemplo n.º 30
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 SimpleDataBaseQuery getQuery(int campo, int orderby, Dictionary <string, string> queryString)
        {
            Dictionary <string, string> join = new Dictionary <string, string>();

            List <string> where = new List <string>();
            List <string> order = new List <string>();

            #region WHERE - ADICIONA OS FILTROS A QUERY
            // ADICIONA OS FILTROS A QUERY
            foreach (KeyValuePair <string, string> item in queryString)
            {
                int    key        = Convert.ToInt16(item.Key);
                CAMPOS filtroEnum = (CAMPOS)key;
                switch (filtroEnum)
                {
                case CAMPOS.IDRECEBIMENTOTITULO:
                    Int32 idRecebimentoTitulo = Convert.ToInt32(item.Value);
                    where.Add(SIGLA_QUERY + ".idRecebimentoTitulo = " + idRecebimentoTitulo);
                    break;

                case CAMPOS.NRCNPJ:
                    string nrCNPJ = Convert.ToString(item.Value);
                    where.Add(SIGLA_QUERY + ".nrCNPJ = '" + nrCNPJ + "'");
                    break;

                case CAMPOS.NRNSU:
                    string nrNSU = Convert.ToString(item.Value);
                    if (nrNSU.Contains("%"))     // usa LIKE => ENDS WITH
                    {
                        string busca = nrNSU.Replace("%", "").ToString();
                        where.Add(SIGLA_QUERY + ".nrNSU like '%" + busca + "'");
                    }
                    else
                    {
                        where.Add(SIGLA_QUERY + ".nrNSU = '" + nrNSU + "'");
                    }
                    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);
                        string   dtInicio = DataBaseQueries.GetDate(dtaIni);
                        string   dtFim    = DataBaseQueries.GetDate(dtaFim);
                        where.Add(SIGLA_QUERY + ".dtVenda BETWEEN '" + dtInicio + "' AND '" + dtFim + " 23:59:00'");
                    }
                    else     // IGUAL
                    {
                        string   busca = item.Value;
                        DateTime data  = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        string   dt    = DataBaseQueries.GetDate(data);
                        where.Add(SIGLA_QUERY + ".dtVenda BETWEEN '" + dt + "' AND '" + dt + " 23:59:00'");
                    }
                    break;

                case CAMPOS.CDADQUIRENTE:
                    Int32 cdAdquirente = Convert.ToInt32(item.Value);
                    where.Add("(" + SIGLA_QUERY + ".cdAdquirente IS NOT NULL AND " + SIGLA_QUERY + ".cdAdquirente = " + cdAdquirente + ") OR " +
                              "(" + SIGLA_QUERY + ".cdAdquirente IS NULL AND ISNULL(" + SIGLA_QUERY + ".cdAdquirenteNew, 0) = " + cdAdquirente + ")");
                    break;

                case CAMPOS.DSBANDEIRA:
                    string dsBandeira = Convert.ToString(item.Value);
                    where.Add(SIGLA_QUERY + ".dsBandeira = '" + dsBandeira + "'");
                    break;

                case CAMPOS.VLVENDA:
                    decimal vlVenda = Convert.ToDecimal(item.Value);
                    where.Add(SIGLA_QUERY + ".vlVenda = " + vlVenda.ToString(CultureInfo.GetCultureInfo("en-GB")));
                    break;

                case CAMPOS.QTPARCELAS:
                    byte qtParcelas = Convert.ToByte(item.Value);
                    where.Add(SIGLA_QUERY + ".qtParcelas = " + qtParcelas);
                    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);
                        string   dtInicio = DataBaseQueries.GetDate(dtaIni);
                        string   dtFim    = DataBaseQueries.GetDate(dtaFim);
                        where.Add(SIGLA_QUERY + ".dtTitulo BETWEEN '" + dtInicio + "' AND '" + dtFim + " 23:59:00'");
                    }
                    else     // IGUAL
                    {
                        string   busca = item.Value;
                        DateTime data  = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        string   dt    = DataBaseQueries.GetDate(data);
                        where.Add(SIGLA_QUERY + ".dtTitulo BETWEEN '" + dt + "' AND '" + dt + " 23:59:00'");
                    }
                    break;

                case CAMPOS.VLPARCELA:
                    decimal vlParcela = Convert.ToDecimal(item.Value);
                    where.Add(SIGLA_QUERY + ".vlParcela = " + vlParcela.ToString(CultureInfo.GetCultureInfo("en-GB")));
                    break;

                case CAMPOS.NRPARCELA:
                    byte nrParcela = Convert.ToByte(item.Value);
                    where.Add(SIGLA_QUERY + ".nrParcela = " + nrParcela);
                    break;

                case CAMPOS.CDERP:
                    string cdERP = Convert.ToString(item.Value);
                    where.Add(SIGLA_QUERY + ".cdERP = '" + cdERP + "'");
                    break;

                case CAMPOS.DTBAIXAERP:
                    if (item.Value.Equals(""))
                    {
                        where.Add(SIGLA_QUERY + ".dtBaixaERP IS NULL");
                    }
                    else if (item.Value.Equals("0"))
                    {
                        where.Add(SIGLA_QUERY + ".dtBaixaERP IS NOT NULL");
                    }
                    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);
                        string   dtInicio = DataBaseQueries.GetDate(dtaIni);
                        string   dtFim    = DataBaseQueries.GetDate(dtaFim);
                        where.Add(SIGLA_QUERY + ".dtBaixaERP IS NOT NULL AND " + SIGLA_QUERY + ".dtBaixaERP BETWEEN '" + dtInicio + "' AND '" + dtFim + " 23:59:00'");
                    }
                    else     // IGUAL
                    {
                        string   busca = item.Value;
                        DateTime dta   = DateTime.ParseExact(busca + " 00:00:00.000", "yyyyMMdd HH:mm:ss.fff", CultureInfo.InvariantCulture);
                        string   dt    = DataBaseQueries.GetDate(dta);
                        where.Add(SIGLA_QUERY + ".dtBaixaERP IS NOT NULL AND " + SIGLA_QUERY + ".dtBaixaERP BETWEEN '" + dt + "' AND '" + dt + " 23:59:00'");
                    }
                    break;

                case CAMPOS.CDSACADO:
                    string cdSacado = Convert.ToString(item.Value);
                    where.Add(SIGLA_QUERY + ".cdSacado = '" + cdSacado + "'");
                    break;

                // RELACIONAMENTOS
                case CAMPOS.ID_GRUPO:
                    Int32 id_grupo = Convert.ToInt32(item.Value);
                    // JOIN
                    if (!join.ContainsKey("INNER JOIN cliente.empresa " + GatewayEmpresa.SIGLA_QUERY))
                    {
                        join.Add("INNER JOIN cliente.empresa " + GatewayEmpresa.SIGLA_QUERY, " ON " + SIGLA_QUERY + ".nrCNPJ = " + GatewayEmpresa.SIGLA_QUERY + ".nu_cnpj");
                    }
                    where.Add(GatewayEmpresa.SIGLA_QUERY + ".id_grupo = " + id_grupo);
                    break;

                case CAMPOS.ID_EXTRATO:
                    Int32 idExtrato = Convert.ToInt32(item.Value);
                    // JOIN
                    if (!join.ContainsKey("INNER JOIN pos.RecebimentoParcela " + GatewayRecebimentoParcela.SIGLA_QUERY))
                    {
                        join.Add("INNER JOIN pos.RecebimentoParcela " + GatewayRecebimentoParcela.SIGLA_QUERY, " ON " + SIGLA_QUERY + ".idRecebimentoTitulo = " + GatewayRecebimentoParcela.SIGLA_QUERY + ".idRecebimentoTitulo");
                    }
                    where.Add(GatewayRecebimentoParcela.SIGLA_QUERY + ".idExtrato = " + idExtrato);
                    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)
                {
                    order.Add(SIGLA_QUERY + ".idRecebimentoTitulo ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".idRecebimentoTitulo DESC");
                }
                break;

            case CAMPOS.NRCNPJ:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".nrCNPJ ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".nrCNPJ DESC");
                }
                break;

            case CAMPOS.NRNSU:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".nrNSU ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".nrNSU DESC");
                }
                break;

            case CAMPOS.DTVENDA:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".dtVenda ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".dtVenda DESC");
                }
                break;

            case CAMPOS.CDADQUIRENTE:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".cdAdquirente ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".cdAdquirente DESC");
                }
                break;

            case CAMPOS.DSBANDEIRA:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".dsBandeira ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".dsBandeira DESC");
                }
                break;

            case CAMPOS.VLVENDA:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".vlVenda ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".vlVenda DESC");
                }
                break;

            case CAMPOS.QTPARCELAS:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".qtParcelas ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".qtParcelas DESC");
                }
                break;

            case CAMPOS.DTTITULO:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".dtTitulo ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".dtTitulo DESC");
                }
                break;

            case CAMPOS.VLPARCELA:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".vlParcela ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".vlParcela DESC");
                }
                break;

            case CAMPOS.NRPARCELA:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".nrParcela ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".nrParcela DESC");
                }
                break;

            case CAMPOS.CDERP:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".cdERP ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".cdERP DESC");
                }
                break;

            case CAMPOS.DTBAIXAERP:
                if (orderby == 0)
                {
                    order.Add(SIGLA_QUERY + ".dtBaixaERP ASC");
                }
                else
                {
                    order.Add(SIGLA_QUERY + ".dtBaixaERP DESC");
                }
                break;
            }
            #endregion

            return(new SimpleDataBaseQuery(null, "card.tbRecebimentoTitulo " + SIGLA_QUERY,
                                           join, where.ToArray(), null, order.ToArray()));
        }