/// <summary> /// Gera a tabela com os totais e escreve-a num ficheiro /// </summary> /// <param name="totaisTipoPagamento"></param> /// <param name="totaisTipoAdiantamento"></param> /// <param name="totaisTipoAdiantamentoPagamento"></param> /// <param name="totaisAnulados"></param> /// <param name="tipo">Prestador ou Adquirente</param> private static void GeraTabelaTxtTotais(RecibosVerdesValores totaisTipoPagamento, RecibosVerdesValores totaisTipoAdiantamento, RecibosVerdesValores totaisTipoAdiantamentoPagamento, RecibosVerdesValores totaisAnulados, int mes, TipoReciboVerdePrestOUAdquir tipo) { //Gera a tabela para txt RecibosVerdesValores total = totaisTipoPagamento + totaisTipoAdiantamento + totaisTipoAdiantamentoPagamento; DataTable table = new DataTable(); table.Columns.Add("Tipo", typeof(string)); table.Columns.Add("Valor base", typeof(decimal)); table.Columns.Add("IVA", typeof(decimal)); table.Columns.Add("Imp. Selo", typeof(decimal)); table.Columns.Add("IRS", typeof(decimal)); table.Columns.Add("Recebido", typeof(decimal)); table.Rows.Add("Pagamento", totaisTipoPagamento.valorBase, totaisTipoPagamento.valorIvaContinente, totaisTipoPagamento.impostoSelo, totaisTipoPagamento.irsSemRetencao, totaisTipoPagamento.importanciaRecebida); table.Rows.Add("Adiantamento", totaisTipoAdiantamento.valorBase, totaisTipoAdiantamento.valorIvaContinente, totaisTipoAdiantamento.impostoSelo, totaisTipoAdiantamento.irsSemRetencao, totaisTipoAdiantamento.importanciaRecebida); table.Rows.Add("Adiant. para despesas", totaisTipoAdiantamentoPagamento.valorBase, totaisTipoAdiantamentoPagamento.valorIvaContinente, totaisTipoAdiantamentoPagamento.impostoSelo, totaisTipoAdiantamentoPagamento.irsSemRetencao, totaisTipoAdiantamentoPagamento.importanciaRecebida); table.Rows.Add("Total", total.valorBase, total.valorIvaContinente, total.impostoSelo, total.irsSemRetencao, total.importanciaRecebida); table.Rows.Add("Total anulados", totaisAnulados.valorBase, totaisAnulados.valorIvaContinente, totaisAnulados.impostoSelo, totaisAnulados.irsSemRetencao, totaisAnulados.importanciaRecebida); var text = ConsoleTableBuilder.From(table).Export().ToString(); var diretorio = Path.Combine(DownloadFolder, GetFolderTipoDeclaracao(Declaracao.AT_LISTA_RECIBOS_VERDES_PARA_WINTOUCH_PRESTADOS, mes), empresaAutenticada.Codigo + "-" + empresaAutenticada.NIF); Directory.CreateDirectory(diretorio); string nomeFicheiro; if (tipo == TipoReciboVerdePrestOUAdquir.Adquirente) { nomeFicheiro = "Totais adquiridos.txt"; } else { nomeFicheiro = "Totais emitidos.txt"; } File.WriteAllText(Path.Combine(diretorio, nomeFicheiro), text); }
//Tipo: Prestador e Adquirente internal static void DownloadRecibosVerdesEmitidosWintouch(int ano, int mes, TipoReciboVerdePrestOUAdquir tipo) { List <string> detailsURLs = new List <string>(); //Vai à lista de recibos verdes, para obter o URL de detalhes de cada um RecibosVerdesEmitidosNavegarPorCadaRecibo(ano, mes, tipo, (string downloadURL, string numRecibo, string nomeCliente) => { //Para cada recibo, regista o URL para obter os detalhes string detailsUrl = downloadURL.Replace("/imprimir/", "/detalhe/").Replace("/normal", ""); detailsURLs.Add(detailsUrl); }); //Para contar os totais por tipo de recibo RecibosVerdesValores totaisTipoPagamento = new RecibosVerdesValores(); RecibosVerdesValores totaisTipoAdiantamento = new RecibosVerdesValores(); RecibosVerdesValores totaisTipoAdiantamentoPagamento = new RecibosVerdesValores(); RecibosVerdesValores totaisAnulados = new RecibosVerdesValores(); List <ReciboVerde> recibosVerdes = new List <ReciboVerde>(detailsURLs.Count); //List<ReciboVerde> recibosVerdes = (List<ReciboVerde>)new BinaryFormatter().Deserialize(new FileStream(@"C:\users\miguel\desktop\a.txt", FileMode.Open, FileAccess.Read));//TEMP //Depois de obtidos os URLs, navegar até à pagina de detalhes de cada um foreach (string detailsUrl in detailsURLs) { //Obtem os dados do recibo verde, navegado até à página de detalhes ReciboVerde reciboVerde = ObterDadosReciboVerde(detailsUrl, tipo); recibosVerdes.Add(reciboVerde); //Soma os valores para obter um total por tipo de recibo verde if (!reciboVerde.anulado) { if (reciboVerde.tipoReciboVerde == TipoReciboVerde.Pagamento) { totaisTipoPagamento += reciboVerde.valores; } if (reciboVerde.tipoReciboVerde == TipoReciboVerde.Adiantamento) { totaisTipoAdiantamento += reciboVerde.valores; } if (reciboVerde.tipoReciboVerde == TipoReciboVerde.AdiantamentoPagamento) { totaisTipoAdiantamentoPagamento += reciboVerde.valores; } } else { totaisAnulados += reciboVerde.valores; } } //new BinaryFormatter().Serialize(new FileStream(@"c:\users\miguel\desktop\b.txt", FileMode.Create), recibosVerdes); GeraTabelaTxtTotais(totaisTipoPagamento, totaisTipoAdiantamento, totaisTipoAdiantamentoPagamento, totaisAnulados, mes, tipo); ExportarFicheiroWintouch(recibosVerdes, mes, tipo); }
/** * Esta função navega até à pagina de detalhes, e obtem os dados do recibo, * tipo: Prestador ou Adquirente **/ private static ReciboVerde ObterDadosReciboVerde(string detailsUrl, TipoReciboVerdePrestOUAdquir tipo) { driver.Navigate().GoToUrl(detailsUrl); ReciboVerde reciboVerde = new ReciboVerde(); reciboVerde.detailsUrl = detailsUrl; reciboVerde.tipo = tipo; // Prestador ou Adquirente //Obter dados string[] doc = driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div[2]/div/div/div[1]/div[1]/h1")).Text.Split(' '); reciboVerde.tipoDoc = doc[0]; reciboVerde.numDoc = doc[2]; string estado = driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div[2]/div/div/div[1]/div[1]/h1/span")).Text; reciboVerde.anulado = estado.ToLower() == "anulado"; string dataEmissao = driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div[2]/div/div/div[2]/div/legend/small")) .Text.Replace("Emitida a ", ""); string dataTransmissao = driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div[5]/div[2]/div/div[2]/dl/dd")).Text; reciboVerde.dataEmissao = DateTime.ParseExact(dataEmissao, "yyyy-MM-dd", CultureInfo.InvariantCulture); reciboVerde.dataTransmissao = DateTime.ParseExact(dataTransmissao, "yyyy-MM-dd", CultureInfo.InvariantCulture); reciboVerde.nifTransmitente = driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div[3]/div[2]/div/div[1]/dl/dd")).Text; reciboVerde.nifAdquirente = driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div[4]/div[2]/div[1]/div[1]/dl/dd")).Text; reciboVerde.descricao = driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div[5]/div[2]/div/div[3]/dl/dd")).Text; reciboVerde.nomeAdquirente = driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div[4]/div[2]/div[1]/div[2]/dl/dd")).Text; reciboVerde.nomeTrasmitente = driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div[3]/div[2]/div/div[2]/dl/dd")).Text; reciboVerde.paisAdquirente = driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div[4]/div[2]/div[2]/div/dl/dd")).Text; //Obtem as string que têm os valores string valorBaseStr = driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div[5]/div[2]/div/div[4]/dl/div[2]/dd")).Text; string valorIvaContinenteStr = driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div[5]/div[2]/div/div[4]/dl/div[4]/dd")).Text; string impostoSeloStr = driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div[5]/div[2]/div/div[4]/dl/div[6]/dd")).Text; string irsSemRetencaoStr = driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div[5]/div[2]/div/div[4]/dl/div[8]/dd")).Text; string importanciaRecebidaStr = driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div[5]/div[2]/div/div[4]/dl/div[10]/dd")).Text; //Converte os valores para decimal reciboVerde.valores = new RecibosVerdesValores(); reciboVerde.valores.valorBase = Convert.ToDecimal(valorBaseStr.Remove(valorBaseStr.Length - 2), culture); reciboVerde.valores.valorIvaContinente = Convert.ToDecimal(valorIvaContinenteStr.Remove(valorIvaContinenteStr.Length - 2), culture); reciboVerde.valores.impostoSelo = Convert.ToDecimal(impostoSeloStr.Remove(impostoSeloStr.Length - 2), culture); reciboVerde.valores.irsSemRetencao = Convert.ToDecimal(irsSemRetencaoStr.Remove(irsSemRetencaoStr.Length - 2), culture); reciboVerde.valores.importanciaRecebida = Convert.ToDecimal(importanciaRecebidaStr.Remove(importanciaRecebidaStr.Length - 2), culture); //Obtem o tipo de recibo verde, vendo qual checkbox est]a checked IWebElement checkboxTipoPagamento = driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div[5]/div[2]/div/div[1]/dl/dt[2]/div/div[1]/label/input")); IWebElement checkboxTipoAdiantamento = driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div[5]/div[2]/div/div[1]/dl/dt[2]/div/div[2]/label/input")); IWebElement checkboxTipoAdiantamentoPagam = driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div[5]/div[2]/div/div[1]/dl/dt[2]/div/div[3]/label/input")); if (checkboxTipoPagamento.Selected) { reciboVerde.tipoReciboVerde = TipoReciboVerde.Pagamento; } else if (checkboxTipoAdiantamento.Selected) { reciboVerde.tipoReciboVerde = TipoReciboVerde.Adiantamento; } else { reciboVerde.tipoReciboVerde = TipoReciboVerde.AdiantamentoPagamento; } return(reciboVerde); }
/// <summary> /// Esta função exporta os recibos para o ficheiro do wintouch /// </summary> private static void ExportarFicheiroWintouch(List <ReciboVerde> recibosVerdes, int mes, TipoReciboVerdePrestOUAdquir tipo) { var diretorio = Path.Combine(DownloadFolder, GetFolderTipoDeclaracao(Declaracao.AT_LISTA_RECIBOS_VERDES_PARA_WINTOUCH_PRESTADOS, mes), empresaAutenticada.Codigo + "-" + empresaAutenticada.NIF); Directory.CreateDirectory(diretorio); string nomeFicheiro; if (tipo == TipoReciboVerdePrestOUAdquir.Adquirente) { nomeFicheiro = Path.Combine(diretorio, GenNovoNomeFicheiro(Definicoes.estruturaNomesFicheiros.AT_LISTA_RECIBOS_VERDES_WINTOUCH_ADQUIRIDOS)); } else { nomeFicheiro = Path.Combine(diretorio, GenNovoNomeFicheiro(Definicoes.estruturaNomesFicheiros.AT_LISTA_RECIBOS_VERDES_WINTOUCH_PRESTADOS)); } using (StreamWriter fileStream = new StreamWriter(nomeFicheiro)) { fileStream.WriteLine("WCONTAB5.60"); foreach (ReciboVerde reciboVerde in recibosVerdes) { WintouchExportarRecibo(fileStream, reciboVerde); } } }
/** * Esta função vai a cada recibo verde, navegando todas as páginas, e corre a action, dizendo qual o URL para transferir o PDF * ModoConsulta: Prestador ou Adquirente * Mes: -1 é o ano todo */ internal static void RecibosVerdesEmitidosNavegarPorCadaRecibo(int ano, int mes, TipoReciboVerdePrestOUAdquir modoConsulta, Action <string, string, string> action) { int diaInicial = 1; int diaFinal; int mesInicial; int mesFinal; if (mes == -1) { //De 1-Jan a 31-Dez diaFinal = 31; mesInicial = 1; mesFinal = 12; } else { diaFinal = DateTime.DaysInMonth(ano, mes); mesInicial = mes; mesFinal = mes; } string url = String.Format("https://irs.portaldasfinancas.gov.pt/recibos/portal/consultar#?isAutoSearchOn=on&dataEmissaoInicio={0}-{1}-{2}&dataEmissaoFim={0}-{3}-{4}", ano, mesInicial, diaInicial, mesFinal, diaFinal); if (modoConsulta == TipoReciboVerdePrestOUAdquir.Prestador) { url += String.Format("&modoConsulta=Prestador&nifPrestadorServicos={0}", empresaAutenticada.NIF); } else { url += String.Format("&modoConsulta=Adquirente&nifAdquirente={0}", empresaAutenticada.NIF); } driver.Navigate().GoToUrl(url); Thread.Sleep(500); driver.Navigate().GoToUrl(url); Thread.Sleep(500); var xPathTotalRecibos = By.XPath("/html/body/div/main/div/div[2]/div/section/div/div/consultar-app/div[3]/div/div[1]/consultar-tabela/div/div/table/tfoot/tr/td/div/div[1]/p"); //Se não encontrar o numero de recibos, é porque há um erro. Faz log desse erro if (!Util.IsElementPresent(driver, xPathTotalRecibos)) { LogError(driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div/div/consultar-app/div[2]")).Text); return; } int totalResultados = Int32.Parse(driver.FindElement(xPathTotalRecibos).Text); if (totalResultados == 0) { return; } //Escolhe mostrar 50 items por pagina driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div/div/consultar-app/div[2]/div/div/div/div/div/pf-table-size-picker/div/button")).Click(); driver.FindElement(By.XPath("//*[@id=\"main-content\"]/div/div/consultar-app/div[2]/div/div/div/div/div/pf-table-size-picker/div/ul/li[4]/a")).Click(); const int NUM_RESULTADOS_POR_PAG = 50; Thread.Sleep(500); //Obtem o numero de paginas var xPathNumeroPaginas = By.XPath("//*[@id=\"main-content\"]/div/div/consultar-app/div[3]/div/div[1]/consultar-tabela/div/div/table/tfoot/tr/td/div/div[3]/st-pagination/ul/li[last()-1]/a"); int numeroPaginas = 1; if (Util.IsElementPresent(driver, xPathNumeroPaginas)) { numeroPaginas = Int32.Parse(driver.FindElement(xPathNumeroPaginas).Text); } else { numeroPaginas = 1; //Se não houver nada a dizer o numero de paginas é porque é a única } for (int pag = 0; pag < numeroPaginas; pag++) { //Se é a ultima página bool ultimaPagina = pag == numeroPaginas - 1; //Calcula o numero de resultados que devem estar nesta pagina int numResultadosNestaPagina; if (ultimaPagina) { numResultadosNestaPagina = totalResultados % NUM_RESULTADOS_POR_PAG; if (numResultadosNestaPagina == 0) { numResultadosNestaPagina = NUM_RESULTADOS_POR_PAG; } } else { numResultadosNestaPagina = NUM_RESULTADOS_POR_PAG; } for (int i = 0; i < numResultadosNestaPagina; i++) { string xPathConjuntoBotoes = "/html/body/div/main/div/div[2]/div/section/div/div/consultar-app/div[3]/div/div[1]/consultar-tabela/div/div/table/tbody/tr[" + (i + 1) + "]/td[5]/div"; //Obtem nr recibo string numRecibo = driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div/div/consultar-app/div[3]/div/div[1]/consultar-tabela/div/div/table/tbody/tr[" + (i + 1) + "]/td[1]/p[1]")).Text; numRecibo = numRecibo.Split('º')[1].Trim(); string nomeCliente = driver.FindElement(By.XPath("/html/body/div/main/div/div[2]/div/section/div/div/consultar-app/div[3]/div/div[1]/consultar-tabela/div/div/table/tbody/tr[" + (i + 1) + "]/td[1]/p[2]")).Text; string downloadURL = driver.FindElement(By.XPath(xPathConjuntoBotoes + "/ul/li[2]/a")).GetAttribute("href"); //Invoca a action action.Invoke(downloadURL, numRecibo, nomeCliente); } if (ultimaPagina) { continue; //Não anda uma página para a frente se for a ultima } //Anda uma pagina para a frente driver.FindElement(By.XPath("//*[@id=\"main-content\"]/div/div/consultar-app/div[3]/div/div[1]/consultar-tabela/div/div/table/tfoot/tr/td/div/div[3]/st-pagination/ul/li[last()]/a")).Click(); } }