Problems with Puppeter - javascript

Hello im new in programing ive been using the libery pupperter. My problem is i can't get all the information from same selector. The website is http://eportal.miteco.gob.es/BoleHWeb/, and i need to get information Embases Guadarquivir. If i do it on the websites console i get all the infomation from the selector but if i do it in .js i only get 30 to 40 elements from the same array.
Information i want
The information i get from the console
const puppeter = require('puppeteer');
let embalse = require('../controlador/controladorEmbalse');
(async () => {
//inicializamos en la constante browser, la libreria puppeter.
//Con {headless: false}, nos sale una ventana chrome con los movimientos que estamos realizando.
const browser = await puppeter.launch({headless: false});
//creamos una pagina de chrome
const page = await browser.newPage();
let year = ['2020','2019','2018','2017','2016','2015','2014','2013','2012','2011','2010','2008','2007','2006','2005'];
let month = ["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"];
let day = '#idDate27'
let cuenca = [{nombre: 'Tinto, Odiel y Piedras', id:"#btnMod_Reserva_Hidraulica_Datos_16" }, {nombre: 'Guadalete-Barbate', id: '#btnMod_Reserva_Hidraulica_Datos_15'},
{nombre: 'Guadalquivir', id: '#btnMod_Reserva_Hidraulica_Datos_5'}, {nombre: 'Cuenca Mediterránea Andaluza', id: "#btnMod_Reserva_Hidraulica_Datos_6"}]
//Solo utilizar este metodo si la tabla watershed esta vacia.
// embalse.añadirCuencas(cuenca);
for(let anho of year){
for(let mes of month){
for(let agua of cuenca){
await page.goto('http://eportal.miteco.gob.es/BoleHWeb/');
await page.type('#year' , anho );
await page.type('#month', mes);
await page.click( day);
await page.waitForSelector('#btnMnuReserva');
await page.click('#btnMnuReserva');
await page.waitForSelector(agua.id);
await page.click(agua.id);
await page.waitForSelector('td.tdfondosinbordes');
const elements = await page.evaluate(()=> {
let textos = [];
const td = document.querySelectorAll("td.tdfondosinbordes");
for ( let texto of td){
textos.push(texto.innerText);
}
return textos;
});
await page.waitForSelector('td.tdblancosinbordesletraazul');
const elem = await page.evaluate(()=> {
let textos = [];
const td = document.querySelectorAll("td.tdblancosinbordesletraazul");
for ( let texto of td){
textos.push(texto.innerText);
}
return textos;
});
const indicador = elements.findIndex(element => element == 'Guadiato' )
if(indicador !== -1){
elements.splice(indicador + 1,0,'Cala');
}
let nombreEmbalse =[];
// console.log(elements);
function filtrarNombres(nombres, array){
const arrayFiltrado = array.filter(numero => isNaN(numero));
for(let i = 0 ; i < arrayFiltrado.length ; i++){
if(i % 2 == 0){
nombres.push(arrayFiltrado[i]);
}
}
return nombres;
}
//console.log(filtrarNombres(nombreEmbalse, elements));
const nombre = filtrarNombres(nombreEmbalse, elements);
const datos = elem.slice(0, nombre.length)
//console.log(datos);
function realizarObjeto(nom, dat) {
let infoTotal = [];
let posicion = 0;
for(let i = 0 ; i < dat.length; i++){
let historico = {}
historico.nombre = nom[i];
historico.data = dat[posicion].trim();
historico.fecha = anho;
historico.mes = mes;
historico.cuenca = agua.nombre;
posicion++;
infoTotal.push(historico)
}
return infoTotal;
}
console.log(realizarObjeto(nombre, datos));
//let objeto = realizarObjeto(nombre, datos);
//embalse.añadirHistorico(objeto);
}
}
}
await page.screenshot({path: 'amanzon1.jpg'});
//cerramos el programa
await browser.close();
})();
------------------------------------------------------------------------
await page.waitForSelector('td.tdfondosinbordes');
const elements = await page.evaluate(()=> {
let textos = [];
const td = document.querySelectorAll("td.tdfondosinbordes");
for ( let texto of td){
textos.push(texto.innerText);
}
return textos;
});
This is the funtion ive used to get the information from the images.
On the console of the website i get all the info. But when i do it in .Js every time i run the code i only get half of the infomation and its never the same it varies.
Ive tried it Page.$$eval and other methods but i never get all of the info.

If nobody knows no reason. The most problame is that the web has an antiscrapping process. With a waitFor (they are obsolete). It seems that this pause does not activate this process.

Related

How to use local storage in my TODO list js

I'm trying to solve a task in javascript, I'm learning but don't now how to use the local storage, or how to use it in my todo list, I can add task, mark them and delete, but when I refresh the browser the task vanishes, I've been trying for days an do not find the answer haha. This is my js code:
//informacion de las fechas
const dateNumber = document.getElementById("dateNumber");
const dateText = document.getElementById("dateText");
const dateMonth = document.getElementById("dateMonth");
const dateYear = document.getElementById("dateYear");
const placeDate = () => {
const date = new Date();
dateNumber.textContent = date.toLocaleString('es', { day: 'numeric' });
dateText.textContent = date.toLocaleString('es', { weekday: 'long' });
dateMonth.textContent = date.toLocaleString('es', { month: 'short' });
dateYear.textContent = date.toLocaleString('es', { year: 'numeric' });
};
placeDate();
//div contenedor de las tareas
const taskListContainer = document.getElementById("taskListContainer");
const setDate = () => {
return moment().format('MMMM, Do, YYYY');
};
setDate();
const addNewTask = event => {
event.preventDefault();
const value = document.getElementById("taskText").value;
if (!value) {
alert ("Debes escribir algo para que se agregue la tarea!!!");
return};
task.classList.add ("task", "roundborder");
task.addEventListener("click", changeTaskState)
task.addEventListener("dblclick", function(){
taskListContainer.removeChild(task)
})
task.textContent = value;
taskListContainer.prepend(task);
event.target.reset();
};
const changeTaskState = event => {
event.target.classList.toggle('marked');
}
const order = () => {
const marked = [];
const toDo = [];
taskListContainer.childNodes.forEach( element => {
element.classList.contains('marked') ? marked.push(element) : toDo.push (element)
})
return [...toDo, ...marked];
}
//funcion para que al darle al boton de ordenar, se marquen como realizadas
//iteramos cada elemento de los arrays en order y lo agregamos a la lista de tareas del taskListContainer
const orderedTasks = () => {
order().forEach(element => taskListContainer.appendChild(element))
}
and my HTML:
<h1 >Lista de tareas</h1>
<form onsubmit="addNewTask(event)" >
<input type="text" id="taskText" autocomplete="off" placeholder=" " class="roundBorder">
<button type="submit" class="add-button">+</button>
<button type="button" class="orderButton roundBorder" onclick="orderedTasks()">Ordenar</button>
</form>
<h4><small> 1 click = marcar, 2 click = eliminar</small> </h4>
<div id="taskListContainer"></div>
</div>
So I notice you never even set anything to the local storage
https://developer.mozilla.org/en/docs/Web/API/Window/localStorage
I'd recommend this docs to find on how to interact with the localstorage api.
Or this guide: https://blog.logrocket.com/localstorage-javascript-complete-guide/
So like in add new task you say getItem from local Storage but you never set the Item to the local storage.

How to print data from an object and error [object Object] does not appear?

I have this program that as soon as it starts up, it asks you to enter the number of books that you want to register in the program and the number of authors that each book will have.
The program will ask you to register a name for each author, surname, age and nationality.
Once this is done, there is a button that shows all the books registered with their authors and the data of the books, and I have the problem that I am not able to show the data of the authors since only [object Object] appears.
Edit:
I have managed to print the element.autores by console.log, without the error obejct object appearing but I am not able to get it out through a document.write or something similar, here I leave a screenshot of how it should appear:
And if I try to put elements.autores.nombre to print only the name, it appears undefined both in the console.log and in the document.write
Here my code:
javascript:
var biblioteca = new Array();
function libro(titulo, autores, anyo, editorial) {
this.titulo = titulo;
this.autores = autores;
this.anyo = anyo;
this.editorial = editorial;
}
function autor(nombre, apellidos, edad, nacionalidad) {
this.nombre = nombre;
this.aepellidos = apellidos;
this.edad = edad;
this.nacionalidad = nacionalidad;
}
window.onload = function () {
document.getElementById("mostrar").onclick = Mostrar;
document.getElementById("insertar").onclick = insertarlibro;
document.getElementById("insertar").onclick = insertarautor;
}
function insertarlibro() {
var autores = new Array();
var titulo = prompt("Insertar el nombre del titulo del libro");
var anyo = parseInt(prompt("Año"));
var editorial = prompt("Inserta su editorial");
var numautores = parseInt(prompt("Cuantos autores vas a insertar"));
for (let i = 0; i < numautores; i++) {
let autor = insertarautor();
autores.push(autor);
}
var registrohecho = new libro(titulo, autores, anyo, editorial);
return registrohecho;
}
console.log(insertarlibro);
function insertarautor() {
var nombre = prompt("Insertar el nombre del autor").toUpperCase();
var apellidos = prompt("Insertar el apellidos del autor").toUpperCase();
var edad = parseInt(prompt("Edad"));
var nacionalidad = prompt("¿De que pais es el autor?");
var registrohecho = new autor(nombre, apellidos, edad, nacionalidad);
return registrohecho;
}
console.log(insertarautor);
var numlibros = parseInt(prompt("Cuantos libros vas a insertar"));
for (let i = 0; i < numlibros; i++) {
var insertalibro = insertarlibro();
biblioteca.push(insertalibro);
}
function Mostrar() {
biblioteca.forEach(element => {
console.log("Error" + JSON.stringify(element.autores));
var muestra = "Nombre del libro:" + element.titulo + " autores: " + element.autores + " Año en el que se publico: " + element.anyo + " Editorial: " + element.editorial;
document.write(muestra);
});
}
And the html part:
<div id="insertar">
<input type="button" value="Insertar">
</div>
<div id="mostrar">
<input type="button" value="Mostrar">
</div>
You are trying to get element.autores, which is an array. To get e.g. get the nombre, you wold have to acces it with element.autores[0].nombre.
So your code to output all books (with authors) would be something like this:
biblioteca.forEach(element => {
var muestra = "Nombre del libro:" + element.titulo + " autores: ";
element.autores.forEach(author => {
muestra += `nombre: ${author.nombre}, aepellidos: ${author.aepellidos}, edad: ${author.edad}, nacionalidad: ${author.nacionalidad} `;
})
muestra += "Año en el que se publico: " + element.anyo + " Editorial: " + element.editorial;
document.write(muestra);
});

creating a class to be able to reduce my code and reuse it

I am a javascript student so there are things that are still not entirely clear in my head. I want to rearrange my code to make it reusable by passing it certain parameters
At this moment I have built this credit simulator, in a much longer code, it occurred to me to build a class, with that class to be able to feed the data it requires and return the values that I need to be shown on the screen.
The first method "creacionClientes" builds the profile of the credit applicant and saves it in an array, what I need is that the second method which returns a value of the fee that the person must pay, is added in the client's profile requesting the credit. Likewise, I can't find a way for the "calcularCuotas" method to feed on the information that the client variable receives, I'm very stuck and I'm drowning in a glass of water thks!
const datosTabla = document.querySelector("#tftable,tbody"); const tasas = cambiarValorTasas() let planesVisible = false;
class Clientes {
constructor (){
this.clients = []
}
creacionClientes(nombre, apellido, email, monto, plazo, tasas){
this.clients.push({
id: Date.now(),
nombre: nombre,
apellido: apellido,
email: email,
monto: monto,
plazo: plazo,
tasas: tasas,
});
}
calcularCuotas(monto, tasas, plazos){
let hoy = new Date()
let pagoMensual = 0;
let pagoAmortizacion = 0;
let pagosIntereses = 0;
pagoMensual = monto * (Math.pow(1+tasas/100, plazos)*tasas/100)/(Math.pow(1+tasas/100, plazos)-1);
while (datosTabla.firstChild){
datosTabla.removeChild(datosTabla.firstChild);
}
//creacion de fechas sucesivas
function formatoFecha(fecha) {
fecha = new Date(fecha);
var dia = fecha.getDate();
var mesIndex = fecha.getMonth()+1;
var año = fecha.getFullYear();
return dia + "/" + mesIndex + "/" + año;
}
for(let i = 1; i <= plazos; i++) {
pagosIntereses = parseFloat(monto*(tasas/100));
pagoAmortizacion = parseFloat(pagoMensual - pagosIntereses);
monto = parseFloat(monto-pagoAmortizacion);
var fechaX = hoy.setMonth(hoy.getMonth() + 1);
//creacion de las filas
$("#tablaPrestamos").append(`<tr><td>${formatoFecha(fechaX)}
<td class="valorCuota">${pagoMensual.toFixed(2)}</td>
<td>${pagoAmortizacion.toFixed(2)}</td>
<td>${pagosIntereses.toFixed(2)}</td>
<td>${monto.toFixed(2)}</td>`);
}
} }
function cambiarValorTasas (){
let plazosOpc = $("#menuPlazos").prop('selectedIndex');
let opciones = $("#menuPlazos").prop('options');
if (opciones[plazosOpc].value == 12){
$('#tasasSeleccion').html(3.95);
} else if (opciones[plazosOpc].value == 24){
$('#tasasSeleccion').html(4.19);
} else if (opciones[plazosOpc].value == 36){
$('#tasasSeleccion').html(4.36);;
}
return $('#tasasSeleccion').val(); } $(document).on('change', cambiarValorTasas);
function mostrarTabla(nombre, visibilidad ){
let mostrar = document.getElementById(nombre);
if (visibilidad == false){
if(mostrar.classList.contains("noMostrar")){
mostrar.classList.remove("noMostrar")
}
mostrar.className += " mostrar"
} else {
if(mostrar.classList.contains("mostrar")){
mostrar.classList.remove("mostrar")
}
mostrar.className += " noMostrar"
} } $('#botonCalc').on('click', (e) =>{
e.preventDefault();
mostrarTabla('tasasSeleccion', planesVisible);
mostrarTabla('tasasLabel', planesVisible);
mostrarTabla('botonEnviar', planesVisible);
mostrarTabla('tablaPrestamos', planesVisible);
planesVisible = !planesVisible;
})
$('#botonEnviar').on("click", (e) =>{
e.preventDefault();
let cliente = new Clientes();
cliente.creacionClientes($('#nombre').val(), $('#apellido').val(), $('#mail').val(), parseInt($('#aSolicitar').val()), parseInt($('#menuPlazos').val()), parseFloat(tasas))
console.log(cliente)
cliente.calcularCuotas(parseInt($('#aSolicitar').val()), tasas, parseInt($('#menuPlazos').val())) })
The problem is that you are saving the list of clients inside the client
I would try this:
Get the list of clients outside every client
Create the client on the constructor (instead of creacionClientes)
Add it to the clients list before creating the client
NOW you can use this inside calcularCuotas where the client information is stored (e.g. this.nombre)
It could be something like that
const datosTabla = document.querySelector("#tftable,tbody"); const tasas = cambiarValorTasas() let planesVisible = false;
const clientes = []
class Clientes {
constructor (nombre, apellido, email, monto, plazo, tasas){
this = {
id: Date.now(),
nombre: nombre,
apellido: apellido,
email: email,
monto: monto,
plazo: plazo,
tasas: tasas,
}
clients.push(this);
}
calcularCuotas(monto, tasas, plazos){
let hoy = new Date()
let pagoMensual = 0;
let pagoAmortizacion = 0;
let pagosIntereses = 0;
pagoMensual = monto * (Math.pow(1+tasas/100, plazos)*tasas/100)/(Math.pow(1+tasas/100, plazos)-1);
while (datosTabla.firstChild){
datosTabla.removeChild(datosTabla.firstChild);
}
//creacion de fechas sucesivas
function formatoFecha(fecha) {
fecha = new Date(fecha);
var dia = fecha.getDate();
var mesIndex = fecha.getMonth()+1;
var año = fecha.getFullYear();
return dia + "/" + mesIndex + "/" + año;
}
for(let i = 1; i <= plazos; i++) {
pagosIntereses = parseFloat(monto*(tasas/100));
pagoAmortizacion = parseFloat(pagoMensual - pagosIntereses);
monto = parseFloat(monto-pagoAmortizacion);
var fechaX = hoy.setMonth(hoy.getMonth() + 1);
//creacion de las filas
$("#tablaPrestamos").append(`<tr><td>${formatoFecha(fechaX)}
<td class="valorCuota">${pagoMensual.toFixed(2)}</td>
<td>${pagoAmortizacion.toFixed(2)}</td>
<td>${pagosIntereses.toFixed(2)}</td>
<td>${monto.toFixed(2)}</td>`);
}
} }
function cambiarValorTasas (){
let plazosOpc = $("#menuPlazos").prop('selectedIndex');
let opciones = $("#menuPlazos").prop('options');
if (opciones[plazosOpc].value == 12){
$('#tasasSeleccion').html(3.95);
} else if (opciones[plazosOpc].value == 24){
$('#tasasSeleccion').html(4.19);
} else if (opciones[plazosOpc].value == 36){
$('#tasasSeleccion').html(4.36);;
}
return $('#tasasSeleccion').val(); } $(document).on('change', cambiarValorTasas);
function mostrarTabla(nombre, visibilidad ){
let mostrar = document.getElementById(nombre);
if (visibilidad == false){
if(mostrar.classList.contains("noMostrar")){
mostrar.classList.remove("noMostrar")
}
mostrar.className += " mostrar"
} else {
if(mostrar.classList.contains("mostrar")){
mostrar.classList.remove("mostrar")
}
mostrar.className += " noMostrar"
} } $('#botonCalc').on('click', (e) =>{
e.preventDefault();
mostrarTabla('tasasSeleccion', planesVisible);
mostrarTabla('tasasLabel', planesVisible);
mostrarTabla('botonEnviar', planesVisible);
mostrarTabla('tablaPrestamos', planesVisible);
planesVisible = !planesVisible;
})
$('#botonEnviar').on("click", (e) =>{
e.preventDefault();
let cliente = new Clientes($('#nombre').val(), $('#apellido').val(), $('#mail').val(), parseInt($('#aSolicitar').val()), parseInt($('#menuPlazos').val()), parseFloat(tasas))
console.log(cliente)
clientes.push(cliente)
cliente.calcularCuotas(parseInt($('#aSolicitar').val()), tasas, parseInt($('#menuPlazos').val())) })

How do I use loops with discord reactions?

I'm trying to code a fighting discord bot game but I ran into troubles lately!
Everything works with reactions.
So basically what i want to do is : roll a dice to determine the one who starts. The winner rolls 2 dices to determine the damages he will do and then its player 2's turn.
Until here, everything works.
What i would like it to do is loop this last part when the first player rolls the 2 dices to inflict damages.
I tried placing while loops userhealth<=0 here and there, but it never works.
I know it has to do with promises and stuff like that, but Im still lost.
A little help would be appreciated!
Here is the code:
const { ReactionCollector } = require('discord.js');
function rolldice(numero){
return Math.floor(Math.random() * numero + 1);
}
function premier(msg,user){
diceroll1 = rolldice(20)
diceroll2 = rolldice(20)
msg.channel.send(`${msg.author.tag} a eu : ${diceroll1} \n\n ${user.tag} a eu : ${diceroll2}`)
if(diceroll1 > diceroll2){
msg.channel.send(`${msg.author.tag} gagne`)
return msg.author.id
}
else if(diceroll1 < diceroll2){
msg.channel.send(`${user.tag} gagne`)
return user.id
}
else{
msg.channel.send(`Vous avez fait égalité. On recommence le tirage.`)
premier(msg,user)
}
}
function attaque1(msg, user){
damagedice1 = rolldice(6)
damagedice2 = rolldice(6)
somme = damagedice1 + damagedice2
return {somme,damagedice1,damagedice2}
}
function bagarre(msg,user,winner,user1health,user2health,fighter1,fighter2){
if(winner === msg.author.id){
msg.channel.send(`Joueur 1 Clique sur 🎲 pour determiner les dégats que tu vas infliger.`).then((riposte) => {
riposte.react('🎲')
var atksmme = attaque1(msg,user)
const filter1 = (reaction, user) => {
return ['🎲'].includes(reaction.emoji.name) && user.id === fighter1;
};
const collector1 = riposte.createReactionCollector(filter1,{
max: 1
});
collector1.on('collect',(collected,reason) => {
user2health = user2health - atksmme.somme
msg.channel.send(`${msg.author.tag} inflige ${atksmme.somme} de dégâts à ${user.tag}! (${atksmme.damagedice1} + ${atksmme.damagedice2})`)
msg.channel.send(`Il reste ${user2health} points de vie à ${user.tag}`)
if(user2health<=0) return msg.channel.send('Vous avez perdu')
collector1.stop()
msg.channel.send(`Joueur 2 Clique sur 🎲 pour determiner les dégats que tu vas infliger.`).then((riposte1) => {
riposte1.react('🎲')
var atk2smme = attaque1(msg,user)
const filter2 = (reaction, user) => {
return ['🎲'].includes(reaction.emoji.name) && user.id === fighter2;
};
const collector2 = riposte1.createReactionCollector(filter2,{
max: 1
});
collector2.on('collect',(collected,reason) => {
user1health = user1health - atk2smme.somme
msg.channel.send(`${user.tag} inflige ${atk2smme.somme} de dégâts à ${msg.author.tag}! (${atk2smme.damagedice1} + ${atk2smme.damagedice2})`)
msg.channel.send(`Il reste ${user1health} points de vie à ${msg.author.tag}`)
if(user1health<=0) return msg.channel.send('Vous avez perdu')
collector2.stop()
})
})
})
})
}
else if(winner === user.id){
var atksmme = attaque1(msg,user)
user1health = user1health - atksmme.somme
msg.channel.send(`${user.tag} inflige ${atksmme.somme} de dégâts à ${msg.author.tag}! (${atksmme.damagedice1} + ${atksmme.damagedice2})`)
msg.channel.send(`Il reste ${user1health} points de vie à ${msg.author.tag}`)
}
}
module.exports = {
name: 'fight',
args : true,
usage : '#<user>',
async execute(msg,args) {
//VARIABLES
const { client } = msg;
var diceroll1;
var diceroll2;
var damagedice1;
var damagedice2;
var user1health = 12;
var user2health = 12;
var winner;
//checks if the username to fight is in the msg
var author1 = msg.author.username;
var user = msg.mentions.users.first();
if(!user) return msg.reply("you did not specify who you would like to fight!");
//checks if the users is trying to fight themselves
if(user.id == msg.author.id) return msg.reply('you cannot fight yourself!');
//checks if the user is trying to fight the bot
if(user.bot == true)
return msg.reply('you cannot fight a bot!');
//saves the two user ids to variables
var fighter1 = msg.author.id;
var fighter2 = user.id;
var challenged = user.toString();
msg.channel.send(`${challenged}, tu veux te battre?`).then((bataille) => {
bataille.react('🎲')
const filter = (reaction, user) => {
return ['🎲'].includes(reaction.emoji.name) && user.id === fighter2;
};
const collector = bataille.createReactionCollector(filter,{
max: 1
});
collector.on('collect',(collected,reason) => {
winner = premier(msg,user)
bagarre(msg,user,winner,user1health,user2health,fighter1,fighter2)
})
})
}}
Okay, there's a lot of weird things about this.
First of all, there are a lot of unused variables. Please use a proper IDE like Visual Studio Code that informs you about these things.
Second, you should be using await instead of then in most cases. (dont just replace then with await - see javascript async tutorials for good examples)
Third, this is just all a mess. You will have to divide your code into more functions: Create a function to initiate an attack from one user to another. That code should be usable for both player 1 and 2 so that no code is copypasted for both players. Then you can just call that function after one player has made their turn to start the next turn for the other player.

Filter inputs/data from a event (e) on google script

I have the following script that takes the inputs on Google Forms, makes a document with those inputs, and sends an e-mail with the document attached. It works properly, but I needed to filter some of the responses, but I don't know how to filter data in an event.
One of the questions on the forms is asking what kind of document people want:
Right now, I have only done the script for the 2nd option (Licença Especial em Pecúnia). I need to filter the data from the forms, so when I choose the 1st option (Substituição de Chefia) it generates a different document from a different template. Right now, the function afterSubmit(e) is triggered on form submit.
Excuse the portuguese names of vars and consts, the important ones for this questions I changed to english.
function afterSubmit(e) {
const info = e.namedValues;
const pdfFileLP = createPDFLP(info);
const url = e.namedValues['Anexos ao ofício'][0];
function getIdFromUrl(url) {return url.match(/[-\w]{25,}$/);};
var idAnexo = getIdFromUrl(url);
const nrof = e.namedValues['Numeração do ofício'][0];
function pdfAnexado(idAnexo,nrof) {return DriveApp.getFileById(idAnexo).setName("Anexos do ofício of. " + nrof + "-PGE/PRF.pdf");};
var pdfAnexo = pdfAnexado(idAnexo);
eprotocolo(e.namedValues['Expresso do solicitante'][0],nrof,pdfFileLP,pdfAnexo);
}
function eprotocolo(email,ofi,pdfFileLP,pdfAnexo){
var EmailTemp = HtmlService.createTemplateFromFile("mailLP");
EmailTemp.mail = email;
var htmlMessage = EmailTemp.evaluate().getContent();
GmailApp.sendEmail("estag.pedron#pge.pr.gov.br","Of. " + ofi + "-PGE/PRF",
"SEU EMAIL NÃO SUPORTA O FORMATO HTML, FAVOR RESPONDER ESTE E-MAIL PARA SOLUCIONAR O PROBLEMA OU ENTRAR EM CONTATO PELO TELEFONE (41)3281-6392.",{
from: "procuradoriafuncional#gmail.com", name: "Gerador de ofícios da PRF", htmlBody: htmlMessage,
replyTo: email, cc: email,
attachments: [pdfFileLP, pdfAnexo]
});
}
function createPDFLP(info) {
const pdfFolder = DriveApp.getFolderById("1mgNPhM9f2U0BWrDK0FAfCYyq968rJ3E8");
const tempFolder = DriveApp.getFolderById("1FfW3Jn9hHARpBU8t8szlQ2YwR9OPR1ZV");
const templateChefia = DriveApp.getFileById("1qP3A8O27Ms8OuybaqrQ6jQBB_PQpo-RhDU9xjIw_a44");
const templateLP = DriveApp.getFileById("1lRab5lPdbRcdl4gaI3zonFseE180cNu4-hWaovamerc");
const newTempFileLP = templateLP.makeCopy(tempFolder);
const openDocLP = DocumentApp.openById(newTempFileLP.getId());
const bodyLP = openDocLP.getBody();
bodyLP.replaceText("{of}", info['Numeração do ofício'][0]);
bodyLP.replaceText("{data}", info['Data do ofício'][0]);
bodyLP.replaceText("{serv}", info['Nome completo'][0]);
bodyLP.replaceText("{rg}", info['Número do RG'][0]);
bodyLP.replaceText("{autos}", info['Numero dos autos'][0]);
bodyLP.replaceText("{prazo}", info['Prazo'][0]);
bodyLP.replaceText("{procurador}", info['Procurador solicitante'][0]);
bodyLP.replaceText("{orgao}", info['GRHS de destino'][0]);
openDocLP.saveAndClose();
const blobPDFLP = newTempFileLP.getAs(MimeType.PDF);
const pdfFileLP = pdfFolder.createFile(blobPDFLP).setName("Of. " + info['Numeração do ofício'][0] + "-PGE/PRF.pdf");
tempFolder.removeFile(newTempFileLP);
return pdfFileLP;}
If anyone was curious, I did a simple if statement at the end:
function createPDFLP(info) {
const pdfFolder = DriveApp.getFolderById("1mgNPhM9f2U0BWrDK0FAfCYyq968rJ3E8");
const tempFolder = DriveApp.getFolderById("1FfW3Jn9hHARpBU8t8szlQ2YwR9OPR1ZV");
const templateChefia = DriveApp.getFileById("1qP3A8O27Ms8OuybaqrQ6jQBB_PQpo-RhDU9xjIw_a44");
const templateLP = DriveApp.getFileById("1lRab5lPdbRcdl4gaI3zonFseE180cNu4-hWaovamerc");
const tipo = info['Tipo de ofício'][0];
if(tipo == "Licença Especial em Pecúnia"){
const newTempFileLP = templateLP.makeCopy(tempFolder);
const openDocLP = DocumentApp.openById(newTempFileLP.getId());
const bodyLP = openDocLP.getBody();
bodyLP.replaceText("{of}", info['Numeração do ofício'][0]);
bodyLP.replaceText("{data}", info['Data do ofício'][0]);
bodyLP.replaceText("{serv}", info['Nome completo'][0]);
bodyLP.replaceText("{rg}", info['Número do RG'][0]);
bodyLP.replaceText("{autos}", info['Numero dos autos'][0]);
bodyLP.replaceText("{prazo}", info['Prazo'][0]);
bodyLP.replaceText("{procurador}", info['Procurador solicitante'][0]);
bodyLP.replaceText("{orgao}", info['GRHS de destino'][0]);
openDocLP.saveAndClose();
const blobPDFLP = newTempFileLP.getAs(MimeType.PDF);
const pdfFileLP = pdfFolder.createFile(blobPDFLP).setName("Of. " + info['Numeração do ofício'][0] + "-PGE/PRF.pdf");
tempFolder.removeFile(newTempFileLP);
return pdfFileLP;
} else if (tipo == "Substituição de Chefia") {
const newTempFileSC = templateChefia.makeCopy(tempFolder);
const openDocSC = DocumentApp.openById(newTempFileSC.getId());
const bodySC = openDocSC.getBody();
bodySC.replaceText("{of}", info['Numeração do ofício'][0]);
bodySC.replaceText("{data}", info['Data do ofício'][0]);
bodySC.replaceText("{servi}", info['Nome completo'][0]);
bodySC.replaceText("{rg}", info['Número do RG'][0]);
bodySC.replaceText("{autos}", info['Numero dos autos'][0]);
bodySC.replaceText("{prazo}", info['Prazo'][0]);
bodySC.replaceText("{procurador}", info['Procurador solicitante'][0]);
bodySC.replaceText("{orgao}", info['GRHS de destino'][0]);
bodySC.replaceText("{periodo}", info['Período que o autor alega que ocupou cargo de chefia'][0]);
openDocSC.saveAndClose();
const blobPDFSC = newTempFileSC.getAs(MimeType.PDF);
const pdfFileLP = pdfFolder.createFile(blobPDFSC).setName("Of. " + info['Numeração do ofício'][0] + "-PGE/PRF.pdf");
tempFolder.removeFile(newTempFileSC);
return pdfFileLP;
}
}

Categories