Esempio n. 1
0
    private static void ReadTable(IWebDriver driver, string conta, ref List <Extrato> extratos)
    {
        try
        {
            var cultureBR = new CultureInfo("pt-BR");
            IList <IWebElement> tabelas = driver.FindElements(By.XPath("//*[@id='TRNcontainer01']/table"));

            foreach (var tabela in tabelas)
            {
                foreach (var tr in tabela.FindElements(By.TagName("tr")))
                {
                    IList <IWebElement> tds = tr.FindElements(By.TagName("td"));

                    if (tds.Count > 0 && tr.FindElement(By.TagName("td")).Text.Contains("/"))
                    {
                        var extrato = new Extrato();
                        extrato.conta = conta;

                        // Bug virada do ano
                        var ano = DateTime.Now.Year;

                        int  n;
                        bool isNumeric = int.TryParse(tds[0].Text.Substring(3), out n);

                        if (isNumeric)
                        {
                            var mes = Convert.ToInt32(tds[0].Text.Substring(3));

                            if (mes > DateTime.Now.Month) // virou o ano
                            {
                                ano -= 1;
                            }

                            extrato.data      = DateTime.ParseExact(tds[0].Text + "/" + ano.ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                            extrato.descricao = ExtratoHelper.GetDescricao(tds[1].Text);

                            if (extrato.descricao != null)
                            {
                                if (tds[2].Text.Contains("-"))
                                {
                                    extrato.credito = (decimal?)decimal.Parse(tds[2].Text.Replace("-", ""), NumberStyles.Currency, cultureBR);
                                }
                                else
                                {
                                    extrato.debito = -1 * (decimal?)decimal.Parse(tds[2].Text.Replace("-", ""), NumberStyles.Currency, cultureBR);
                                }

                                ExtratoHelper.AddExtrato(ref extratos, extrato);
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
Esempio n. 2
0
    public static List <Extrato> Sync(List <Conta> contas)
    {
        var extratos  = new List <Extrato>();
        var cultureBR = new CultureInfo("pt-BR");

        foreach (var conta in (from a in contas where a.classe.ToUpper(CultureInfo.InvariantCulture) == "NUBANK" select a).ToList())
        {
            IWebDriver driver = null;

            try
            {
                UI.StartChrome(ref driver, 4);

                driver.Url = "https://app.nubank.com.br/#/login";
                UI.WaitPageLoad(driver);


                // ------------------------------------------------------------------------------------------------------------------------------
                // Tela: Home
                // ------------------------------------------------------------------------------------------------------------------------------
                UI.SetTextBoxValue(driver, By.Id("username"), conta.conta);
                UI.SetTextBoxValue(driver, By.Id("input_001"), conta.senha);
                UI.Wait(1.5);
                UI.Click(driver, By.XPath("/html/body/navigation-base/div[1]/div/main/div[1]/div/div[1]/form/button"));
                //UI.WaitPageLoad(driver);
                UI.Wait(10);

                bool ToBreak = false;

                UI.Click(driver, By.ClassName("bills"));

                UI.Wait(10);

                IList <IWebElement> chargesList = new List <IWebElement>();

                chargesList = driver.FindElements(By.ClassName("charges-list"));

                foreach (var charge in chargesList)
                {
                    if (ToBreak)
                    {
                        break;
                    }
                    var tbodys = charge.FindElements(By.TagName("div"));

                    foreach (var tbody in tbodys)
                    {
                        try
                        {
                            #region DATA
                            IWebElement elementTime = tbody.FindElement(By.ClassName("time"));
                            IWebElement elementCell = elementTime.FindElement(By.ClassName("cell"));
                            IWebElement elementSpan = elementCell.FindElement(By.TagName("span"));

                            DateTime data = DateTime.Now;

                            var textoData = elementSpan.Text.Split(' ');
                            switch (textoData[1].ToUpper())
                            {
                            case "JAN":
                                data = new DateTime(DateTime.Now.Year, 1, Convert.ToInt32(textoData[0]));
                                break;

                            case "FEV":
                                data = new DateTime(DateTime.Now.Year, 2, Convert.ToInt32(textoData[0]));
                                break;

                            case "MAR":
                                data = new DateTime(DateTime.Now.Year, 3, Convert.ToInt32(textoData[0]));
                                break;

                            case "ABR":
                                data = new DateTime(DateTime.Now.Year, 4, Convert.ToInt32(textoData[0]));
                                break;

                            case "MAI":
                                data = new DateTime(DateTime.Now.Year, 5, Convert.ToInt32(textoData[0]));
                                break;

                            case "JUN":
                                data = new DateTime(DateTime.Now.Year, 6, Convert.ToInt32(textoData[0]));
                                break;

                            case "JUL":
                                data = new DateTime(DateTime.Now.Year, 7, Convert.ToInt32(textoData[0]));
                                break;

                            case "AGO":
                                data = new DateTime(DateTime.Now.Year, 8, Convert.ToInt32(textoData[0]));
                                break;

                            case "SET":
                                data = new DateTime(DateTime.Now.Year, 9, Convert.ToInt32(textoData[0]));
                                break;

                            case "OUT":
                                data = new DateTime(DateTime.Now.Year, 10, Convert.ToInt32(textoData[0]));
                                break;

                            case "NOV":
                                data = new DateTime(DateTime.Now.Year, 11, Convert.ToInt32(textoData[0]));
                                break;

                            case "DEZ":
                                data = new DateTime(DateTime.Now.Year, 12, Convert.ToInt32(textoData[0]));
                                break;
                            }
                            #endregion

                            IWebElement elementChargeData  = tbody.FindElement(By.ClassName("charge-data"));
                            IWebElement elementdescription = elementChargeData.FindElement(By.ClassName("description"));

                            IWebElement elementamount = tbody.FindElement(By.ClassName("amount"));

                            var extrato = new Extrato();
                            extrato.conta     = conta.nome;
                            extrato.data      = data;
                            extrato.descricao = ExtratoHelper.GetDescricao(elementdescription.Text);

                            if (!string.IsNullOrEmpty(extrato.descricao))
                            {
                                var valor = decimal.Parse(elementamount.Text.Replace("R$", ""), NumberStyles.Currency, cultureBR);

                                if (valor > 0)
                                {
                                    extrato.debito = Math.Abs(valor) * -1;
                                    ExtratoHelper.AddExtrato(ref extratos, extrato);
                                }
                            }
                        }
                        catch { }
                    }
                }

                UI.Click(driver, By.XPath("/html/body/navigation-base/navigation-menu/div/nav/section/ul[1]/li[3]/a")); // Sair
                UI.WaitPageLoad(driver);
                UI.Wait(2);

                UI.Click(driver, By.ClassName("logout")); // Confirmar
                UI.WaitPageLoad(driver);
            }
            catch (Exception ex)
            {
                UI.SaveHtmlAndPrint(driver, "Nubank", ex);
                throw ex;
            }
            finally
            {
                if (driver != null)
                {
                    try { driver.Close(); } catch { }
                    driver.Quit();
                    driver.Dispose();
                    driver = null;
                }
            }
        }

        // Retorna os registros
        return(extratos);
    }
Esempio n. 3
0
    public static List <Extrato> Sync(List <Conta> contas)
    {
        var extratos  = new List <Extrato>();
        var cultureBR = new CultureInfo("pt-BR");

        foreach (var conta in (from a in contas where a.classe.ToUpper(CultureInfo.InvariantCulture) == "PERSONALITE_MASTERCARD" select a).ToList())
        {
            IWebDriver driver = null;

            try
            {
                UI.StartChrome(ref driver, 4);

                driver.Url = "https://www.itau.com.br/";
                UI.WaitPageLoad(driver);


                // ------------------------------------------------------------------------------------------------------------------------------
                // Tela: Home
                // ------------------------------------------------------------------------------------------------------------------------------

                UI.SetTextBoxValue(driver, By.XPath("//*[@id=\"agencia\"]"), conta.agencia);
                UI.SetTextBoxValue(driver, By.XPath("//*[@id=\"conta\"]"), conta.conta);
                UI.Wait(1.5);
                UI.Click(driver, By.Id("btnLoginSubmit"));
                UI.WaitPageLoad(driver);
                UI.Wait(2);

                // ------------------------------------------------------------------------------------------------------------------------------
                // Tela: Login
                // ------------------------------------------------------------------------------------------------------------------------------

                var teclado = UI.WaitForDisplayed(driver, By.XPath(".//div[@class='teclas clearfix']"), 20);

                IList <IWebElement> teclas = teclado.FindElements(By.TagName("a"));
                var digitos = new List <KeyValuePair <string, IWebElement> >();
                IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;

                foreach (char c in conta.senha)
                {
                    foreach (var tecla in teclas)
                    {
                        if (tecla.Text.Contains(" ou ") && tecla.Text.Contains(c.ToString()))
                        {
                            UI.ClickWithJavascript(driver, executor, tecla);
                        }
                    }
                }

                UI.ClickWithJavascript(driver, executor, By.Id("acessar"));
                UI.WaitPageLoad(driver);


                UI.Wait(10);

                // ------------------------------------------------------------------------------------------------------------------------------
                // Recupera o JSON dos lançamentos
                // ------------------------------------------------------------------------------------------------------------------------------

                var url        = driver.Url.Replace("#30horas", "");
                var cookies    = UI.GetCookies(executor);
                var xauthtoken = cookies.First(x => x.Key == "X-AUTH-TOKEN").Value;
                var op         = driver.FindElement(By.XPath("/html/body/header/div[3]/nav/ul/li/div/div/div[2]/ul[2]/li[2]/a")).GetAttribute("data-op");
                //clicar na fatura
                UI.ClickWithJavascript(driver, executor, By.XPath("/html/body/header/div[3]/nav/ul/li/div/div/div[2]/ul[2]/li[2]/a"));

                UI.Wait(10);

                var element = driver.FindElement(By.Id("exp_elem_list"));
                var eleme   = element.FindElements(By.ClassName("selecao__opcao"));

                string html = UI.GetRequestHtml(HttpMethod.Post, url, xauthtoken, op);
                html = html.Substring(html.IndexOf("self.buscarDadosCompletos =", StringComparison.InvariantCulture));
                html = html.Substring(html.IndexOf("url: \"", StringComparison.InvariantCulture));
                var op2 = html.Substring(0, html.IndexOf("\n", StringComparison.InvariantCulture));
                op2 = op2.Substring(0, op2.LastIndexOf(";", StringComparison.InvariantCulture)).Replace("\"", "").Replace("url: ", ""); // 15 dias, não vai usar

                for (int i = 0; i < (eleme.Count() - 1); i++)
                {
                    var codigoCartao = eleme[i].GetAttribute("id");

                    var json  = UI.GetRequestJson(HttpMethod.Post, url, xauthtoken, op2, body: codigoCartao);
                    var dados = json["object"]["faturas"];

                    foreach (var faturaFechada in dados)
                    {
                        if (!UI.JsonNullOrEmpty(faturaFechada["status"]))
                        {
                            if (faturaFechada["status"].ToString().Equals("fechada", StringComparison.InvariantCulture) ||
                                faturaFechada["status"].ToString().Equals("aberta", StringComparison.InvariantCulture))
                            {
                                var dataFechamentoFatura = DateTime.ParseExact(faturaFechada["dataFechamentoFatura"].ToString(), "yyyy-MM-dd", CultureInfo.InvariantCulture);
                                var dataVencimentoFatura = DateTime.ParseExact(faturaFechada["dataVencimento"].ToString(), "yyyy-MM-dd", CultureInfo.InvariantCulture);

                                var titularidades = faturaFechada["lancamentosNacionais"]["titularidades"];

                                foreach (var titularidade in titularidades)
                                {
                                    var lancamentos = titularidade["lancamentos"];

                                    foreach (var lancamento in lancamentos)
                                    {
                                        var data = DateTime.ParseExact(lancamento["data"].ToString(), "yyyy-MM-dd", CultureInfo.InvariantCulture);

                                        var extrato = new Extrato();
                                        extrato.conta     = conta.nome;
                                        extrato.data      = data;
                                        extrato.descricao = ExtratoHelper.GetDescricao(lancamento["descricao"].ToString());

                                        if (!string.IsNullOrEmpty(extrato.descricao))
                                        {
                                            var valor = decimal.Parse(lancamento["valor"].ToString(), NumberStyles.Currency, cultureBR);

                                            if (lancamento["sinalValor"].ToString().ToUpper(CultureInfo.InvariantCulture) == "+")
                                            {
                                                extrato.debito = Math.Abs(valor) * -1;
                                            }
                                            else
                                            {
                                                extrato.credito = valor;
                                            }

                                            ExtratoHelper.AddExtrato(ref extratos, extrato);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                try
                {
                    UI.ClickWithJavascript(driver, executor, By.ClassName("mfp-close"));
                }
                catch { }
            }
            catch (Exception ex)
            {
                UI.SaveHtmlAndPrint(driver, "Itau", ex);
                throw ex;
            }
            finally
            {
                if (driver != null)
                {
                    try
                    {
                        UI.Click(driver, By.Id("linkSairHeader")); // Sair
                        UI.WaitPageLoad(driver);
                        UI.Wait(2);

                        UI.Click(driver, By.XPath("//*[@id=\"telaSair\"]/div/div/div[1]/section/div/div[2]/a")); // Confirmar
                        UI.WaitPageLoad(driver);

                        driver.Close();
                    }
                    catch { }

                    driver.Quit();
                    driver.Dispose();
                    driver = null;
                }
            }
        }

        // Retorna os registros
        return(extratos);
    }
Esempio n. 4
0
    public static List <Extrato> ReadExtrato(IWebDriver driver, List <Conta> contas, CultureInfo cultureBR, TipoConta tipoConta, TipoLink tipoLink)
    {
        List <Extrato> extratos = new List <Extrato>();

        // Clica no menu "Saldos e Extratos"
        UI.Wait(1);
        driver.SwitchTo().DefaultContent();
        UI.Wait(1);
        UI.ClickWithPerform(driver, UI.WaitForClickable(driver, By.Id("topmenu_S")));
        UI.Wait(1);
        UI.WaitPageLoad(driver);

        // Clica no link da conta corrente ou ponpança, depende do parâmetro linkTitle
        UI.Wait(1);
        UI.WaitIFrameLoad(driver, "paginaCentral");
        UI.Wait(3);

        // Clica no link do extrato
        var lnkText = tipoLink == TipoLink.Ultimos_Lancamentos ? "Extrato (Últimos Lançamentos)" : "Extrato Mensal / Por Período";
        //UI.WaitForClickable(driver, By.LinkText(lnkText));

        var    lnkExtratos = driver.FindElements(By.LinkText(lnkText));
        string conta       = null;

        if (tipoConta == TipoConta.Conta_Corrente)
        {
            conta = (from a in contas where a.nome.ToUpper().EndsWith("CC") select a.nome).First(); // "Bradesco Lu CC";
            lnkExtratos[0].Click();
        }
        else if (tipoConta == TipoConta.Poupanca)
        {
            conta = (from a in contas where a.nome.ToUpper().EndsWith("POUP") select a.nome).First();
            lnkExtratos[1].Click();
        }

        if (tipoLink == TipoLink.Por_Periodo)
        {
            // Tela do extrato: clica no radio button 'A partir de:'
            UI.ClickWhenDisplayed(driver, By.Id("formFiltroMensal:opcaoData1"));
            UI.Wait(1);

            //Seta as datas iniciais
            UI.ClickWhenDisplayed(driver, By.Id("formFiltroMensal:dataInicialDia"));
            UI.Wait(1);

            // Blur para fechar o calendário de data inicial
            IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;
            UI.Blur(driver, executor, driver.FindElement(By.Id("formFiltroMensal:dataInicialDia")));
            UI.Wait(1);

            // Clica na data final - dia
            UI.WaitForClickable(driver, By.Id("formFiltroMensal:dataFinalDia"));
            UI.Wait(1);

            // Seleciona o último dia possível
            var divCalendar             = UI.WaitForClickable(driver, By.Id("dp-popup"));
            IList <IWebElement> trsData = divCalendar.FindElement(By.ClassName("dp-calendar")).FindElement(By.ClassName("jCalendar")).FindElement(By.TagName("tbody")).FindElements(By.TagName("tr"));
            int diaFim = 0;

            foreach (IWebElement tr in trsData)
            {
                IList <IWebElement> tds = tr.FindElements(By.TagName("td"));
                {
                    foreach (IWebElement td in tds)
                    {
                        if (td.GetAttribute("class").Contains("disabled"))
                        {
                            break;
                        }
                        diaFim = Convert.ToInt32(td.Text);
                    }
                }
            }

            var dataFim = DateTime.Today.AddDays(-1); // new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day - 1);
            //dataFim = dataFim.AddDays(-1);
            //dataFim = new DateTime(2019, 11, 10); // XXXXXXX

            if (diaFim > DateTime.Today.Day)
            {
                dataFim = dataFim.AddMonths(-1);                              // caso hoje for 01/12 e o filtro máximo for 30/11. Corrige ficar como 30/12
            }
            // Blur para fechar o calendário de data inicial
            UI.Blur(driver, executor, driver.FindElement(By.Id("formFiltroMensal:dataFinalDia")));
            UI.Wait(1);

            // Seta a data inicial
            var ultima_atulizacao = contas[0].ultima_atulizacao;
            var dataInicio        = new DateTime(ultima_atulizacao.Year, ultima_atulizacao.Month, ultima_atulizacao.Day);
            if (dataInicio > dataFim)
            {
                dataInicio = dataFim;
            }

            //dataInicio = new DateTime(2019, 7, 1);
            //dataFim = new DateTime(2019, 7, 31);

            // Seta as datas
            UI.SetTextBoxValue(driver, By.Id("formFiltroMensal:dataInicialDia"), dataInicio.Day.ToString("00"));
            UI.SetTextBoxValue(driver, By.Id("formFiltroMensal:dataInicialMes"), dataInicio.Month.ToString("00"));
            UI.SetTextBoxValue(driver, By.Id("formFiltroMensal:dataInicialAno"), dataInicio.Year.ToString());

            UI.SetTextBoxValue(driver, By.Id("formFiltroMensal:dataFinalDia"), dataFim.Day.ToString("00"));
            UI.SetTextBoxValue(driver, By.Id("formFiltroMensal:dataFinalMes"), dataFim.Month.ToString("00"));
            UI.SetTextBoxValue(driver, By.Id("formFiltroMensal:dataFinalAno"), dataFim.Year.ToString());

            UI.Click(driver, By.Id("formFiltroMensal:dataInicialAno"));
            UI.Wait(1);
            UI.Blur(driver, executor, driver.FindElement(By.Id("formFiltroMensal:dataInicialAno")));
            UI.Wait(1);

            // Clica em buscar
            UI.Click(driver, By.Id("formFiltroMensal:botaoBuscar"));
        }

        // Aguarda carregar
        UI.WaitPageLoad(driver);

        // "Não há lançamentos/operações para o período selecionado."
        if (UI.IsDisplayed(driver, By.XPath("//table[@class='tabSaldosExtratos']")))
        {
            // Lê o extrato
            var table = UI.WaitForDisplayed(driver, By.XPath("//table[@class='tabSaldosExtratos']"));

            IList <IWebElement> trs = table.FindElement(By.TagName("tbody")).FindElements(By.TagName("tr"));
            string data             = null;

            foreach (IWebElement tr in trs)
            {
                IList <IWebElement> tds = tr.FindElements(By.TagName("td"));

                if (!string.IsNullOrWhiteSpace(tds[0].Text))
                {
                    data = tds[0].Text;
                }

                var extrato = new Extrato();
                extrato.conta = conta;
                extrato.data  = DateTime.ParseExact(data, "dd/MM/yy", CultureInfo.InvariantCulture);
                if (extrato.data > DateTime.Now)
                {
                    continue;
                }

                var    spans     = tds[1].FindElements(By.TagName("span"));
                string descricao = spans[0].Text.Trim();
                if (spans.Count > 1)
                {
                    descricao += " " + spans[1].Text.Trim();
                }
                extrato.descricao = ExtratoHelper.GetDescricao(descricao);

                if (extrato.descricao != null)
                {
                    decimal?nullable;
                    extrato.credito = string.IsNullOrWhiteSpace(tds[3].Text) ? ((decimal?)(nullable = null)) : new decimal?(decimal.Parse(tds[3].Text, NumberStyles.Currency, cultureBR));
                    extrato.debito  = string.IsNullOrWhiteSpace(tds[4].Text) ? ((decimal?)(nullable = null)) : new decimal?(-1 * decimal.Parse(tds[4].Text.Replace("-", "").Trim(), NumberStyles.Currency, cultureBR));
                    if (tipoLink == TipoLink.Por_Periodo)
                    {
                        extrato.saldo = string.IsNullOrWhiteSpace(tds[5].Text) ? ((decimal?)(nullable = null)) : new decimal?(decimal.Parse(tds[5].Text.Replace("- ", "-"), NumberStyles.Currency, cultureBR));
                    }
                    ExtratoHelper.AddExtrato(ref extratos, extrato);
                }
            }
        }
        return(extratos);
    }
Esempio n. 5
0
    private static void ReadTable(ref IWebDriver driver, IList <IWebElement> tables, string conta, ref List <Extrato> extratos, CultureInfo cultureBR)
    {
        foreach (var table in tables)
        {
            IList <IWebElement> trs = table.FindElement(By.TagName("tbody")).FindElements(By.TagName("tr"));

            foreach (var tr in trs)
            {
                var tds = tr.FindElements(By.TagName("td"));

                if (tds.Count > 0)
                {
                    var s = tds[0].Text + "/" + DateTime.Today.Year.ToString();

                    if (UI.IsDate(s))
                    {
                        var extrato = new Extrato();
                        extrato.conta     = conta;
                        extrato.data      = DateTime.ParseExact(s, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                        extrato.descricao = ExtratoHelper.GetDescricao(tds[3].Text);
                        if (extrato.descricao == null)
                        {
                            continue;
                        }

                        s = tds[5].Text;

                        if (!string.IsNullOrWhiteSpace(s))
                        {
                            var d = tds[6].Text;

                            if (d.Trim() == "")
                            {
                                if (tds[5].GetAttribute("class").ToUpper().Contains("NEG") || s.Contains("-"))
                                {
                                    extrato.debito = -1 * (decimal?)decimal.Parse(s.Replace("-", ""), NumberStyles.Currency, cultureBR);
                                }
                                else
                                {
                                    extrato.credito = (decimal?)decimal.Parse(s.Replace("-", ""), NumberStyles.Currency, cultureBR);
                                }
                            }
                            else
                            {
                                if (tds[5].GetAttribute("class").ToUpper().Contains("NEG") || d.Contains("-"))
                                {
                                    extrato.debito = -1 * (decimal?)decimal.Parse(s.Replace("-", ""), NumberStyles.Currency, cultureBR);
                                }
                                else
                                {
                                    extrato.credito = (decimal?)decimal.Parse(s.Replace("-", ""), NumberStyles.Currency, cultureBR);
                                }
                            }
                        }

                        extrato.saldo = string.IsNullOrWhiteSpace(tds[7].Text) ? (decimal?)null : decimal.Parse(tds[7].Text, NumberStyles.Currency, cultureBR);
                        ExtratoHelper.AddExtrato(ref extratos, extrato);
                    }
                }
            }
        }
    }
Esempio n. 6
0
    public static List <Extrato> Sync(List <Conta> contas)
    {
        var extratos  = new List <Extrato>();
        var cultureBR = new CultureInfo("pt-BR");

        foreach (var conta in (from a in contas where a.classe.ToUpper() == "ITAU" select a).ToList())
        {
            IWebDriver driver = null;

            try
            {
                UI.StartChrome(ref driver, 4);

                driver.Url = "https://www.itau.com.br/";
                UI.WaitPageLoad(driver);


                // ------------------------------------------------------------------------------------------------------------------------------
                // Tela: Home
                // ------------------------------------------------------------------------------------------------------------------------------

                UI.SetTextBoxValue(driver, By.XPath("//*[@id=\"agencia\"]"), conta.agencia);
                UI.SetTextBoxValue(driver, By.XPath("//*[@id=\"conta\"]"), conta.conta);
                UI.Wait(1.5);
                UI.Click(driver, By.Id("btnLoginSubmit"));
                UI.WaitPageLoad(driver);
                UI.Wait(2);

                // ------------------------------------------------------------------------------------------------------------------------------
                // Tela: Login
                // ------------------------------------------------------------------------------------------------------------------------------

                var teclado = UI.WaitForDisplayed(driver, By.XPath(".//div[@class='teclas clearfix']"), 20);

                IList <IWebElement> teclas = teclado.FindElements(By.TagName("a"));
                var digitos = new List <KeyValuePair <string, IWebElement> >();
                IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;

                foreach (char c in conta.senha)
                {
                    foreach (var tecla in teclas)
                    {
                        if (tecla.Text.Contains(" ou ") && tecla.Text.Contains(c.ToString()))
                        {
                            UI.ClickWithJavascript(driver, executor, tecla);
                        }
                    }
                }

                UI.ClickWithJavascript(driver, executor, By.Id("acessar"));
                UI.WaitPageLoad(driver);


                UI.Wait(10);



                // ------------------------------------------------------------------------------------------------------------------------------
                // Recupera o JSON dos lançamentos
                // ------------------------------------------------------------------------------------------------------------------------------

                var url        = driver.Url.Replace("#30horas", "");
                var cookies    = UI.GetCookies(executor);
                var xauthtoken = cookies.First(x => x.Key == "X-AUTH-TOKEN").Value;
                var op         = driver.FindElement(By.XPath("html/body/header/div[3]/nav/ul/li/div/div/div[1]/ul[1]/li[2]/a")).GetAttribute("data-op");


                string html = UI.GetRequestHtml(HttpMethod.Post, url, xauthtoken, op);
                html = html.Substring(html.IndexOf("function consultarLancamentosPorPeriodo"));
                html = html.Substring(html.IndexOf("url =") + 7);
                var op2 = html.Substring(0, html.IndexOf("\"")); // 15 dias, não vai usar

                html = html.Substring(html.IndexOf("url =") + 7);
                var op3 = html.Substring(0, html.IndexOf("\"")); // 90 dias

                var json        = UI.GetRequestJson(HttpMethod.Post, url, xauthtoken, op3, "periodoConsulta=90");
                var lancamentos = json["lancamentos"];

                foreach (var lancamento in lancamentos)
                {
                    if (!UI.JsonNullOrEmpty(lancamento["dataLancamento"]))
                    {
                        var data = DateTime.ParseExact(lancamento["dataLancamento"].ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);

                        if (data >= conta.ultima_atulizacao)
                        {
                            var extrato = new Extrato();
                            extrato.conta     = conta.nome;
                            extrato.data      = data;
                            extrato.descricao = ExtratoHelper.GetDescricao(lancamento["descricaoLancamento"].ToString());

                            if (!string.IsNullOrEmpty(extrato.descricao))
                            {
                                var valor = decimal.Parse(lancamento["valorLancamento"].ToString(), NumberStyles.Currency, cultureBR);

                                if (extrato.descricao == "SALDO DO DIA")
                                {
                                    extrato.saldo = valor;
                                }
                                else if (lancamento["indicadorOperacao"].ToString().ToUpper() == "DEBITO")
                                {
                                    extrato.debito = Math.Abs(valor) * -1;
                                }
                                else
                                {
                                    extrato.credito = valor;
                                }

                                ExtratoHelper.AddExtrato(ref extratos, extrato);
                            }
                        }
                    }
                }

                //UI.ClickWithJavascript(driver, executor, By.ClassName("mfp-close"));
            }
            catch (Exception ex)
            {
                UI.SaveHtmlAndPrint(driver, "Itau", ex);
                throw ex;
            }
            finally
            {
                if (driver != null)
                {
                    try
                    {
                        UI.Click(driver, By.Id("linkSairHeader")); // Sair
                        UI.WaitPageLoad(driver);
                        UI.Wait(2);

                        UI.Click(driver, By.XPath("//*[@id=\"telaSair\"]/div/div/div[1]/section/div/div[2]/a")); // Confirmar
                        UI.WaitPageLoad(driver);

                        driver.Close();
                    }
                    catch { }
                    driver.Quit();
                    driver.Dispose();
                    driver = null;
                }
            }
        }

        // Retorna os registros
        return(extratos);
    }
Esempio n. 7
0
    public static List <Extrato> Sync(Dictionary <string, DateTime> contas)
    {
        var conta    = "Itau Personnalite";
        var extratos = new List <Extrato>();

        IWebDriver driver    = null;
        var        cultureBR = new CultureInfo("pt-BR");

        try
        {
            UI.StartChrome(ref driver, 4);

            driver.Url = "https://www.itau.com.br/";
            UI.WaitPageLoad(driver);


            // ------------------------------------------------------------------------------------------------------------------------------
            // Tela: Home
            // ------------------------------------------------------------------------------------------------------------------------------

            UI.SetTextBoxValue(driver, By.XPath("//*[@id=\"agencia\"]"), "agencia");
            UI.SetTextBoxValue(driver, By.XPath("//*[@id=\"conta\"]"), "conta");
            UI.Wait(1.5);
            UI.Click(driver, By.XPath("//*[@id=\"btnLoginSubmit\"]"));

            // ------------------------------------------------------------------------------------------------------------------------------
            // Tela: Login
            // ------------------------------------------------------------------------------------------------------------------------------

            // Clica no nome FERNANDO
            UI.WaitPageLoad(driver);
            UI.Wait(2);

            // div class teclas clearfix
            var teclado = UI.WaitForDisplayed(driver, By.XPath(".//div[@class='teclas clearfix']"), 20);

            IList <IWebElement> teclas = teclado.FindElements(By.TagName("a"));
            var digitos = new List <KeyValuePair <string, IWebElement> >();
            IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;


            var senha = "senha";

            foreach (char c in senha)
            {
                foreach (var tecla in teclas)
                {
                    if (tecla.Text.Contains(" ou ") && tecla.Text.Contains(c.ToString()))
                    {
                        UI.ClickWithJavascript(driver, executor, tecla);
                    }
                }
            }

            UI.ClickWithJavascript(driver, executor, By.Id("acessar"));

            // ------------------------------------------------------------------------------------------------------------------------------
            // Tela: Home logada
            // ------------------------------------------------------------------------------------------------------------------------------

            UI.WaitPageLoad(driver);
            UI.Wait(5);

            // Popup sobre o tour do site novo
            if (UI.IsDisplayed(driver, By.Id("divAcessTour")))
            {
                UI.ClickWhenClickable(driver, By.LinkText("Não, obrigado"));
            }

            UI.ChangeAttribute(driver, executor, driver.FindElement(By.XPath("//*[@id=\"person\"]/header/div/nav/ul/li/a")), "aria-expanded", "true");
            UI.ChangeAttribute(driver, executor, driver.FindElement(By.XPath("//*[@id=\"person\"]/header/div/nav/ul/li/div")), "class", "sub-mnu");
            UI.Wait(1);
            UI.ClickWithJavascript(driver, executor, By.XPath("//*[@id=\"person\"]/header/div/nav/ul/li/div/div/div[1]/ul[1]/li[3]/a"));
            UI.Wait(1);


            // ------------------------------------------------------------------------------------------------------------------------------
            // Tela: Extrato Conta Corrente
            // ------------------------------------------------------------------------------------------------------------------------------

            UI.WaitPageLoad(driver);
            UI.WaitIFrameLoad(driver, "CORPO");
            UI.WaitForDisplayed(driver, By.Name("periodoExtrato"));
            UI.Wait(1);

            var combo   = driver.FindElement(By.Name("periodoExtrato"));
            var options = new SelectElement(combo);
            options.SelectByText("Período específico (até 17 anos) ");

            var dataFim = DateTime.Today;

            // Seta a data início e fim
            UI.SetTextBoxValue(driver, By.Id("MesInicial"), contas[conta].Month.ToString());
            UI.Wait(1);
            UI.SetTextBoxValue(driver, By.Id("AnoInicial"), contas[conta].Year.ToString());
            UI.Wait(1);
            UI.SetTextBoxValue(driver, By.Id("MesFinal"), dataFim.Month.ToString());
            UI.Wait(1);
            UI.SetTextBoxValue(driver, By.Id("AnoFinal"), dataFim.Year.ToString());
            UI.Wait(1);
            UI.Click(driver, By.CssSelector("[href*='JavaScript:enviaDados();']")); // clica em OK
            UI.Wait(1);

            var ProximoMes = false;

            do
            {
                UI.WaitForDisplayed(driver, By.Id("buscaPesquisaOnline"));
                UI.Wait(2);

                List <IWebElement> trs = new List <IWebElement>();

                IWebElement table;

                try
                {
                    table = driver.FindElement(By.Id("TabelaExtrato"));
                    if (table != null)
                    {
                        trs.AddRange(table.FindElement(By.TagName("tbody")).FindElements(By.TagName("tr")).ToList());
                    }
                }
                catch
                { // nada
                }

                try
                {
                    table = driver.FindElement(By.Name("TabelaExtrato"));
                    if (table != null)
                    {
                        trs.AddRange(table.FindElement(By.TagName("tbody")).FindElements(By.TagName("tr")).ToList());
                    }
                }
                catch
                { // nada
                }

                foreach (var tr in trs)
                {
                    var tds = tr.FindElements(By.TagName("td"));

                    if (tds.Count > 0)
                    {
                        var s = tds[0].Text + "/" + dataFim.Year.ToString();

                        if (UI.IsDate(s))
                        {
                            var extrato = new Extrato();
                            extrato.conta     = conta;
                            extrato.data      = DateTime.ParseExact(s, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                            extrato.descricao = ExtratoHelper.GetDescricao(tds[3].Text);
                            if (extrato.descricao == null)
                            {
                                continue;
                            }

                            s = tds[5].Text;

                            if (!string.IsNullOrWhiteSpace(s))
                            {
                                if (tds[5].GetAttribute("class").ToUpper().Contains("NEG") || s.Contains("-"))
                                {
                                    extrato.debito = -1 * (decimal?)decimal.Parse(s.Replace("-", ""), NumberStyles.Currency, cultureBR);
                                }
                                else
                                {
                                    extrato.credito = (decimal?)decimal.Parse(s, NumberStyles.Currency, cultureBR);
                                }
                            }

                            extrato.saldo = string.IsNullOrWhiteSpace(tds[7].Text) ? (decimal?)null : decimal.Parse(tds[7].Text, NumberStyles.Currency, cultureBR);
                            ExtratoHelper.AddExtrato(ref extratos, extrato);
                        }
                    }
                }

                ProximoMes = UI.ElementExist(driver, By.XPath("//*[@id=\"linhaMesProximo\"]/a"));
                if (ProximoMes)
                {
                    UI.ClickWithJavascript(driver, executor, By.XPath("//*[@id=\"linhaMesProximo\"]/a"));
                }
            } while (ProximoMes == true);
        }
        catch (Exception ex)
        {
            UI.SaveHtmlAndPrint(driver, conta, ex);
            throw ex;
        }
        finally
        {
            if (driver != null)
            {
                try { driver.Close(); } catch { }
                driver.Quit();
                driver.Dispose();
                driver = null;
            }
        }

        // Retorna os registros
        return(extratos);
    }