Related
I have setup a woocommerce website, used for delivery of meals from different restaurants in my area. I have tried to setup an automatic transfer of the order data from the json file straight to a Google sheet our drivers use, but I have found myself encountering errors in Google Script everytime woo's webhook fires, and not being able to detect the issue.
Here is my google script code
//this is a function that fires when the webapp receives a GET request
function doGet(e) {
return HtmlService.createHtmlOutput("request received");
}
//this is a function that fires when the webapp receives a POST request
function doPost(e) {
var myData = JSON.parse([e.postData.contents]);
var order_number = myData.number;
var order_address = myData.billing.address_1;
var item = ""
var url = "https://fivestars-delivery.com/mon-compte//driver-dashboard/?orderid=" + order_number;
for (var i = 0; i < myData.line_items.length(); ++i) {
item += myData.line_items[i].product_id + "\n"
total += parseInt(myData.line_items[i].total)
}
var fees = ""
// var feesTotal = 0
for (var i = 0; i < myData.fee_lines.length(); ++i) {
// convertir en entier
// feesTotal += parseInt(myData.fee_lines[i].total)
fees += myData.fee_lines[i].amount + " " + myData.fee_lines[i].name + " - " + myData.fee_lines[i].total + "\n"
}
var discount = myData.discount_total
// nom client
var nomClient = myData.first_name + " " + myData.last_name
var order_total = myData.total;
var payment_method = myData.payment_method_title;
var phone = myData.billing.phone
var note = myData.billing.address_2 + "\n" + myData.customer_note
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
sheet.appendRow([order_number, " ", " ", " ",order_address, " ", "Attente d'envoi",url, order_total, payment_method, nomClient, phone, note, item + fees + discount, ]);
}
-I set up a WooCommerce API and webhook using the api's secret key
-Entered my web application's URL as delivery URL in the webhook
I cannot find out what is wrong and none of the situations I found online have found no help so far.
The variable total is never created, but it is used within the for loop.
How to send an email once, if the row is repeated in the sheet where this is bringing it from?
If I put the MailApp.sendEmail part outside the loop and within a certain period of time the user changes two products' statuses, it only sends one email, containing one of the product's updated status. If I put MailApp.sendEmail within each condition met, it sends one email for each row.
Below is an image of what the sheet looks like:
There are usually multiple rows of data for one product and there should be only one email sent.
var EMAIL_SENT = "Sim";
function sendEmails() {
var file = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("");
var startRow = 2; // First row of data to process
var numRows = sheet.getLastRow(); // Number of rows to process
var dataRange = sheet.getRange(startRow, 1, numRows, 48)
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var rowData = data[i];
if (rowData[18] === "Estudo" || rowData[18] === "Desenvolvimento" || rowData[18] === "Aprovação" || rowData[18] === "Ativo" || rowData[18] === "Cancelado" || rowData[14] === "Descontinuado") {
//var updateAsDate = new Date(rowData[13]);
//var update = Utilities.formatDate(updateAsDate, "GMT" , "dd/MM/yyyy" );
var produto = rowData[1];
var emailTo = file.getOwner().getEmail();
//var emailCC = file.getEditors().map(function(e){return [e.getEmail()]}).join(",");
var versao = rowData[2];
var status = rowData[18];
var lastUpdated = rowData[19];
var lastUpdatedAsDate = Utilities.formatDate(lastUpdated, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "dd/MM/yyyy HH:mm") + "hs";
var usuario = rowData[20];
var message = "<HTML><BODY>"
+ "<P>Olá!"
//+ "<br><br />"
+ "<P>O status do produto " + produto + ", versão " + versao + ", foi atualizado para " + "<b>" +status +"</b>" + "."
//+ "<brr /><br />"
+ "<br>Data da última atualização: </b>" + lastUpdatedAsDate + "<br />"
+ "<br>Usuário: </b>" + usuario + "<br />"
+ "<br /><br />"
//+ "<br>Clique para explorar detalhes, ou para atualizar o status: </b>" + "https://docs.google.com/spreadsheets/d/15pL_AMKVtH4dGk1U7VWMeg590MxtNe7VY4gRqm_GhrM/edit?usp=sharing" + "<br />"
+ "<br /><br />"
+ "</HTML></BODY>";
var emailEstudo = rowData[42];
var emailDesenvolv = rowData[43];
var emailAprov = rowData[44];
var emailAtivo = rowData[45];
var emailCancelado = rowData[46];
var emailDescont = rowData[47];
var subject = "O produto " + produto + ", versão " + versao + " " +", mudou de status.";
Logger.log(rowData[18]);
if (emailDesenvolv != EMAIL_SENT && rowData[18] === "Desenvolvimento") { // Prevents sending duplicates
sheet.getRange(startRow + i, 44).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
} else if(emailEstudo != EMAIL_SENT && rowData[18] === "Estudo") { // Prevents sending duplicates
sheet.getRange(startRow + i, 43).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}else if(emailAprov != EMAIL_SENT && rowData[18] === "Aprovação") { // Prevents sending duplicates
sheet.getRange(startRow + i, 45).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}else if(emailAtivo != EMAIL_SENT && rowData[18] === "Ativo") { // Prevents sending duplicates
sheet.getRange(startRow + i, 46).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}else if(emailCancelado != EMAIL_SENT && rowData[18] === "Cancelado") { // Prevents sending duplicates
sheet.getRange(startRow + i, 47).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}else if(emailDescont != EMAIL_SENT && rowData[18] === "Descontinuado") { // Prevents sending duplicates
sheet.getRange(startRow + i, 48).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
}
}
}
MailApp.sendEmail({
name: "P&D - PB",
to: emailTo,
//cc: emailCC,
subject: subject,
htmlBody: message
});
}
The intent is to send one email containing the product name, version and its current status. Therefore, although I have multiple rows with repeated data, the email would only need one row of data, but mark these repeated rows with EMAIL_SENT to avoid another email being sent later.
function SendEmail() {
var mgrcol=4;
var file = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("ArquivoItens");
var rg=sheet.getDataRange();
var values=rg.getValues();
var productList=[];
var html='';
for(var i=1;i<values.length;i++) {
if(productList.indexOf(values[i][0])==-1 && productList.indexOf(values[i][2])==-1) {
//mgrA.push(vA[i][3]);
productList.push(values[i]); // Joga toda a linha que será usada pra dar os dados para o email.
}
}
var productObj={}
for(var i=0;i<productList.length;i++) {
for(var j=0;j<values.length;j++) {
if(productList[i]==values[j][0] && productList[i]==values[j][2]){
if(productObj.hasOwnProperty(productList[i])) {
productObj[productList[i]]+=Utilities.formatString('~~~%s<br />%s<br />%s',values[j][0],values[j][2],values[j][18]);
}else{
productObj[productList[i]]=Utilities.formatString('%s<br />%s<br />%s',values[j][0],values[j][2],values[j][18]);
}
}
}
}
Logger.log(productList);
for(var i=0;i<productList.length;i++) {
var tA=productObj[productList[i]].split('~~~'); //This is presenting the error
var s='Status atualizado<br /></br />';
for(var j=0;j<tA.length;j++) {
s+=tA[j].toString() + '<br />';
}
s+='<hr widht="100" />';
GmailApp.sendEmail(productList[i], 'User Names and Emails', null, {htmlBody:s})
html+=Utilities.formatString('Email Recipient: <strong>%s</strong><br />',productList[i]) + s;//debug
}
var ui=HtmlService.createHtmlOutput(html);//debug
SpreadsheetApp.getUi().showModelessDialog(ui, 'Emails');//debug
}
This is just an example to show you how to build arrays of rows that have common properties. I used the values of ColumnA and ColumnC to create the property because they match in the areas that I want to combine together.
Here's the code:
function makingObjects() {
const ss=SpreadsheetApp.getActive();
const sh=ss.getActiveSheet();
const rg=sh.getDataRange();
const vs=rg.getValues();
const hA=vs.shift();
let col={};
let idx={};
hA.forEach(function(h,i){col[h]=i+1;idx[h]=i;});
let obj={pA:[]};
vs.forEach(function(r,i){
let prop=r[idx["COL1"]]+ "-" + r[idx["COL3"]];
if(!obj.hasOwnProperty(prop)) {
obj[prop]=[];
obj[prop].push({"COL2":r[idx["COL2"]],"COL4":r[idx["COL4"]],"COL5":r[idx["COL5"]],"COL6":r[idx["COL6"]]});
obj.pA.push(prop);//I find easier just keep the properties here
}else{
obj[prop].push({"COL2":r[idx["COL2"]],"COL4":r[idx["COL4"]],"COL5":r[idx["COL5"]],"COL6":r[idx["COL6"]]});
}
});
//SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(JSON.stringify(obj)), "Rows Combined");//This will display a dialog showing how the rows are combined in separated arrays for each property.
obj.pA.forEach(function(r,i){
//Here you have to decide and how you want to combine them in each row.
});
}
Here's the data from my spreadsheet:
COL1,COL2,COL3,COL4,COL5,COL6
1,1,a,1,1,1
1,2,a,2,2,2
2,3,b,3,3,3
2,4,b,4,4,4
3,5,c,5,5,5
3,6,c,6,6,6
4,7,d,7,7,7
4,8,d,8,8,8
5,9,e,9,9,9
5,10,e,10,10,10
6,11,f,11,11,11
6,12,f,12,12,12
7,13,g,13,13,13
7,14,g,14,14,14
8,15,h,15,15,15
8,16,h,16,16,16
9,17,i,17,17,17
9,18,i,18,18,18
Here's the solution I've come up with:
var produtoEmail = new Array();
var versaoEmail = new Array();
var statusEmail = new Array();
and then, within the if statements that qualify the row's data to be sent, it pushes the columns' data I want to the arrays above.
if (emailDesenvolv != EMAIL_SENT && status === "Desenvolvimento") { // Prevents sending duplicates
sheet.getRange(startRow + i, 44).setValue(EMAIL_SENT);
produtoEmail.push(data[i][1]);
versaoEmail.push(data[i][2]);
statusEmail.push(data[i][18]);
Then, when writing the email, it gets only the first element of each array.
I'm sure this isn't the most efficient way, given my poor technical understanding, but its solved my problem.
Appreciate the ones who helped me.
Cheers,
I'm new to Google Apps Script so I'm looking for some advice. There's multiple parts and I managed to do some of it but I'm stuck on others. Any help would be much appreciated.
I'm trying to make a script that:
drafts a reply to emails that contain specific keywords (found in the body or the subject line).
I also want it to include a template with data inputted from a Google Sheets file.
It would be preferable if the draft can be updated without making a duplicate whenever the Sheet is modified.
I plan on also including a row of values (the first one) that correspond to the Subject columns in the second row the but I haven't gotten to it yet.
Some details about the Google Sheet:
Each row corresponds to a different person and email address that regularly emails me.
The first three columns are details about the person which I include in the body of my draft.
Each column after that represents a different string or keyword I expect to find in the subject of the emails sent to me.
The rows underneath contain two patterned code-words separated by a space in one cell that I want to be able to choose from. Such as:
3 letters that can contain permutations of the letters m, g, r (for ex: mmg, rgm, rgg, gmg)
and 0-3 letters with just p's (for ex: p, pp, ppp, or blank)
I want to be able to detect the different codes and assign it to a variable I can input into my draft.
What I have so far:
I'm able to draft replies for emails within my specified filter. However, I only have it set up to reply to the person's most recent message. I want to be able for sort through the filter for specific emails that contain a keyword in the subject line when it loops through the columns.
I'm able to input static strings from the Sheet into the body of my email but I'm still having trouble with the patterned codewords.
I was able to loop through more than one row in earlier version but now it's not. I'll look over it again later.
Here's my code:
function draftEmail() {
var sheet = SpreadsheetApp.getActiveSheet(); // Use data from the active sheet
var startRow = 1; // First row of data to process
var numRows = sheet.getLastRow() - 1; // Number of rows to process
var lastColumn = sheet.getLastColumn(); // Last column
var dataRange = sheet.getRange(startRow, 1, numRows, lastColumn) // Fetch the data range of the active sheet
var data = dataRange.getValues(); // Fetch values for each row in the range
// Work through each row in the spreadsheet
for (var i = 2; i < data.length; ++i) {
var row = data[i];
// Assign each row a variable
var grader = row[0]; // Col A: Grader's name
var firstName = row[1]; // Col B: Student's first name
var studentEmail = row[2]; // Col C: Student's email
var grade = row[3].split(' '); // Col D: Grade
var pgrade = grade[1];
var hgrade = grade[0];
for (var n = 1; n < data.length; ++n) {
var srow = data[n];
var subjectCol = srow[3];
var threads = GmailApp.getUserLabelByName('testLabel').getThreads();
for (i=0; i < threads.length; i++)
{
var thread = threads[i];
var messages = thread.getMessages(); // get all messages in thread i
var lastmsg = messages.length - 1; // get last message in thread i
var emailTo = WebSafe(messages[lastmsg].getTo()); // get only email id from To field of last message
var emailFrom = WebSafe(messages[lastmsg].getFrom()); // get only email id from FROM field of last message
var emailCC = WebSafe(messages[lastmsg].getCc()); // get only email id from CC field of last message
// form a new CC header for draft email
if (emailTo == "")
{
var emailCcHdr = emailCC.toString();
} else
{
if (emailCC == "")
{
var emailCcHdr = emailTo.toString();
} else
{
var emailCcHdr = emailTo.toString() + "," + emailCC.toString();
}
}
var subject = messages[lastmsg].getSubject().replace(/([\[\(] *)?(RE|FWD?) *([-:;)\]][ :;\])-]*|$)|\]+ *$/igm,"");
// the above line remove REs and FWDs etc from subject line
var emailmsg = messages[lastmsg].getBody(); // get html content of last message
var emaildate = messages[lastmsg].getDate(); // get DATE field of last message
var attachments = messages[lastmsg].getAttachments(); // get all attachments of last message
var edate = Utilities.formatDate(emaildate, "IST", "EEE, MMM d, yyyy"); // get date component from emaildate
var etime = Utilities.formatDate(emaildate, "IST", "h:mm a"); // get time component from emaildate
if (emailFrom.length == 0)
{
// if emailFrom is empty, it probably means that you may have written the last message in the thread. Hence 'you'.
var emailheader = '<html><body>' +
'On' + ' ' +
edate + ' ' +
'at' + ' ' +
etime + ',' + ' ' + 'you' + ' ' + 'wrote:' + '</body></html>';
} else
{
var emailheader = '<html><body>' +
'On' + ' ' +
edate + ' ' +
'at' + ' ' +
etime + ',' + ' ' + emailFrom + ' ' + 'wrote:' + '</body></html>';
}
var emailsig = '<html>' +
'<div>your email signature,</div>' +
'</html>'; // your email signature i.e. common for all emails.
// Build the email message
var emailBody = '<p>Hi ' + firstName + ',<p>';
emailBody += '<p>For ' + subjectCol + ', you will be graded on #1, 2, and 3: <p>';
emailBody += '<p>Participation: ' + pgrade + '</p>';
emailBody += '<p>HW grade: ' + hgrade + '</p>';
emailBody += '<p>If you have any questions, you can email me at ' + grader + '#email.com.<p>';
emailBody += '<p>- ' + grader;
var draftmsg = emailBody + '<br>' + emailsig + '<br>' + emailheader + '<br>' + emailmsg + '\n'; // message content of draft
// Create the email draft
messages[lastmsg].createDraftReply(
" ", // Body (plain text)
{
htmlBody: emailBody // Options: Body (HTML)
}
);
}
}
}
function WebSafe(fullstring)
{
var splitString = fullstring.split(",");
var finalarray = [];
for (u=0; u < splitString.length; u++)
{
var start_pos = splitString[u].indexOf("<") + 1;
var end_pos = splitString[u].indexOf(">",start_pos);
if (!(splitString[u].indexOf("<") === -1 && splitString[u].indexOf(">",start_pos) === -1)) // if < and > do exist in string
{
finalarray.push(splitString[u].substring(start_pos, end_pos));
} else if (!(splitString[u].indexOf("#") === -1))
{
finalarray.push(splitString[u]);
}
}
var index = finalarray.indexOf(grader + "#email.com"); // use your email id. if the array contains your email id, it is removed.
if (index > -1) {finalarray.splice(index, 1);}
return finalarray
}
}
I've never coded in JavaScript before or used Google Scripts so I mostly looked at similar examples.
Thank you for any feedback.
I prefer reading code that isn't too nested. So I took the liberty to re-write your code and make it easier to read.
Your main function:
function mainFunction(){
// Use data from the active sheet
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
var threads = GmailApp.getUserLabelByName('<YOUR-LABEL-HERE>').getThreads();
var subject1 = data[1][3];
// Work through each row in the spreadsheet omit headers
for (var i = 2; i < data.length; ++i) {
// Get grader's data
var grader = getGrader(data[i]);
console.log(grader);
// Loop through threads
for (j=0; j < threads.length; j++){
var thread = threads[j];
// Get last message in thread
var messages = thread.getMessages();
var lastMsg = messages[messages.length - 1];
var email = new Email(grader, lastMsg, subject1);
// Create the draft reply.
var draftMessageBody = createDraftMessage(email);
lastMsg.createDraftReply(draftMessageBody);
}
}
}
Support functions:
Function getGrader:
function getGrader(array){
var row = array
var grader = {}
grader.grader = row[0];
grader.firstName = row[1];
grader.studentEmail = row[2];
var grade = row[3].split(' ');
grader.pgrade = grade[1];
grader.hgrade = grade[0];
return grader
}
Function webSafe:
function webSafe(fullstring, grader){
var splitString = fullstring.split(",");
var finalarray = [];
for (u=0; u < splitString.length; u++){
var start_pos = splitString[u].indexOf("<") + 1;
var end_pos = splitString[u].indexOf(">",start_pos);
// if < and > do exist in string
if (!(splitString[u].indexOf("<") === -1 && splitString[u].indexOf(">",start_pos) === -1)){
finalarray.push(splitString[u].substring(start_pos, end_pos));
} else if (!(splitString[u].indexOf("#") === -1)){
finalarray.push(splitString[u]);
}
}
// use your email id. if the array contains your email id, it is removed.
var index = finalarray.indexOf(grader.grader + "#mangoroot.com");
if (index > -1) {
finalarray.splice(index, 1);
}
return finalarray
}
Function Email: Behaves like a class
var Email = function(grader, lastMsg, subject){
this.signature = "your_email_signature,";
this.grader = grader;
this.to = webSafe(lastMsg.getTo(), this.grader);
this.from = webSafe(lastMsg.getFrom(), this.grader);
this.cc = webSafe(lastMsg.getCc(), this.grader);
this.subject = lastMsg.getSubject().replace(/([\[\(] *)?(RE|FWD?) *([-:;)\]][ :;\])-]*|$)|\]+ *$/igm,"");
this.message = lastMsg.getBody();
this.date = lastMsg.getDate();
this.attachments = lastMsg.getAttachments();
this.subject1 = subject;
this.ccHeader = function() {
var ccHeader = "";
if (this.to == "" || this.cc == ""){
ccHeader = this.cc.toString();
}
else {
ccHeader = this.to.toString() + "," + this.cc.toString();
}
return ccHeader
}
this.eDate = function() {
return Utilities.formatDate(this.date, "IST", "EEE, MMM d, yyyy");
}
this.eTime = function() {
return Utilities.formatDate(this.date, "IST", "h:mm a");
}
this.header = function() {
var header = ''.concat('On ');
if (this.from.length == 0){
header += this.eDate().concat(' at ',this.eTime(),', you wrote: ');
}
else {
header += this.eDate().concat(' at ',this.eTime(),', ',this.from,' wrote: ');
}
return header
}
this.body = function(){
var grader = this.grader;
var body = '<div>'.concat('<p>Hi ',grader.firstName,',</p>');
body += '<p>For '.concat(this.subject1,', you will be graded on #1, 2, and 3: </p>');
body += '<p>Participation: '.concat(grader.pgrade,'</p>');
body += '<p>HW grade: '.concat(grader.hgrade,'</p>');
body += '<p>If you have any questions, you can email me at '.concat(grader.grader,'#mangoroot.com.</p>');
body += '<p>- '.concat(grader.grader,'</p>','</div>');
return body;
}
}
Function createDraftMessage:
function createDraftMessage(email){
var draft = '<html><body>'.concat(email.body);
draft += '<br>'.concat(email.signature);
draft += '<br>'.concat(email.header);
draft += '<br>'.concat(email.message);
draft += '<br>'.concat('</body></html>');
return draft;
}
Now when you run mainFunction() you should get your expected drafts.
Notes:
It is good practice to keep functions flat, flat is better than nested. Makes the code more readable and maintainable.
Also be consistent in your variable naming style.
var emailMsg = ''; // Good.
var emailmsg = ''; // Hard to read.
Have a read about classes
I am trying to get all the values in column L which is indexed as column 11(var check). However I am only getting the value of the first cell in the column and it stops looping through. I have created a comment for a reference.
Could someone please help me?
Please ignore:
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.
function myFunction(e) {
var sheet = SpreadsheetApp.openById("1naSWINA8_uxeLUsj0lFntqILyDj2nirb56uvkBel79Y").getSheetByName("CRM Feedback");
var ss = SpreadsheetApp.getActive().getSheetByName("Form Responses 1");
var data = sheet.getRange(4, 1, ss.getLastRow(), ss.getLastColumn()).getValues();
var manager_email = "XXXXX";
for( var i = 0; i< data.length;i++ ) {
var timestamp = data[i][0];
var requesterEmail = data[i][1];
var starRating = data[i][2];
var requestCatergory = data[i][3];
var description = data[i][4];
var label = data[i][5];
var ticketId = data[i][6];
var comment = data[i][7];
var status = data[i][8];
var priority = data[i][9];
var office = data[i][10];
//I am trying to log all the values in column 11
var check = data[i][11];
Logger.log(check)
var checkTimestamp = data[i][0]
if(check == false){
continue;
} else {
var subject = "CT IT feedback - ";
var body = "<body>";
body += "<br><b>Requester email:</b> " + requesterEmail
body += "<br><b>Star Rating:</b> " + starRating
body += "<br><b>Request Category</b> " + requestCatergory
body += "<br><b>Description:</b> " + description
body += "<br><b>label: </b> " + label
body += "<br><b>Ticket ID: </b>" + ticketId
body += "<br><b>Comment: </b>" + comment
body += "<br><b>status: </b>" + status
body += "<br><b>priority:</b> " + priority
body += "<br><b>office: </b>" + office
body += "</body>";
MailApp.sendEmail(manager_email, subject, body, {htmlBody:body})
var sent_string = "sent";
ss.getRange(i + 1, 12).setValue(sent_string)
if (sent_string){
return
}
}
}
}
You want to loop through all data rows and send emails for each row where the status is not set to "sent" yet
You want to set the status of a row to "sent" after sending an email
The problem is that
you have a return statement which makes you exit the for loop and stop iterating
You seem not to change the status for the right sheet and the right row
I suggest you to modify your code as following:
function myFunction(e) {
var sheet = SpreadsheetApp.openById("1naSWINA8_uxeLUsj0lFntqILyDj2nirb56uvkBel79Y").getSheetByName("CRM Feedback");
var ss = SpreadsheetApp.getActive().getSheetByName("Form Responses 1");
var data = sheet.getRange(4, 1, ss.getLastRow(), ss.getLastColumn()).getValues();
var manager_email = "XXX";
for( var i = 0; i< data.length;i++ ) {
var timestamp = data[i][0];
var requesterEmail = data[i][1];
var starRating = data[i][2];
var requestCatergory = data[i][3];
var description = data[i][4];
var label = data[i][5];
var ticketId = data[i][6];
var comment = data[i][7];
var status = data[i][8];
var priority = data[i][9];
var office = data[i][10];
//I am trying to log all the values in column 11
var check = data[i][11];
Logger.log(check)
var checkTimestamp = data[i][0]
if(check != "sent"){
var subject = "CT IT feedback - ";
var body = "<body>";
body += "<br><b>Requester email:</b> " + requesterEmail
body += "<br><b>Star Rating:</b> " + starRating
body += "<br><b>Request Category</b> " + requestCatergory
body += "<br><b>Description:</b> " + description
body += "<br><b>label: </b> " + label
body += "<br><b>Ticket ID: </b>" + ticketId
body += "<br><b>Comment: </b>" + comment
body += "<br><b>status: </b>" + status
body += "<br><b>priority:</b> " + priority
body += "<br><b>office: </b>" + office
body += "</body>";
MailApp.sendEmail(manager_email, subject, body, {htmlBody:body})
var sent_string = "sent";
//are you sure you want to set the stutus in ss and not in sheet to 'sent'?
//Keep in mind that you start with row 4
sheet.getRange(i +4, 12).setValue(sent_string)
}
}
}
I have a function set up to look at a tab within a sheet, check for certain conditions and then send an email if those conditions are met. The body of the email is set up with certain variables that are comprised of columns from the sheet. The function seems to be working fine, but I'm receiving a warning from Apps Script about using "getValues()" instead of "getValue()" and minimizing calls to servers.
I've tried to grab the range of the spreadsheet into an array, but then I'm not sure how I can go ahead and define variables based off of individual columns within that array.
This is the code that I currently have. If it matters, I also have a separate function setup with this spreadsheet to move rows from one tab to another.
function emailNotification(){
var nowH=new Date().getHours();
var nowD=new Date().getDay();
if((nowD > 0 && nowD <6) && (nowH > 9.5 && nowH < 5.5)) {
var ss = SpreadsheetApp.openByUrl('spreadsheet url');
var dataSheet = ss.getSheetByName("tab name");
for (var i = 2; i <= dataSheet.getLastRow(); i++) {
var firstName = dataSheet.getRange(i, 5).getValue();
var lastName = dataSheet.getRange(i, 6).getValue();
var recipient = dataSheet.getRange(i, 3).getValue();
var isHired = dataSheet.getRange(i, 1).getValue();
var orgName = dataSheet.getRange(i, 11).getValue();
var emailSent = dataSheet.getRange(i, 18).getValue();
var body = "Hello" + "," + "\n" + "\n" + firstName + "
"+lastName + " " + "has been added to the"+ " " + orgName
+ "." + "\n" + "\n" + "Best," + "\n" + "Me";
var htmlText = body.replace(/\n/g,'<br\>');
var subject = "New Hire";
if (isHired == "Yes" && emailSent != "Email Notification
Sent" ) {
MailApp.sendEmail(recipient, "email", subject, body)
MailApp.sendEmail(recipient, subject, body,{
htmlBody : htmlText})
// MARK THE ROW AS COMPLETED
dataSheet.getRange(i, 18).setValue("Email Notification
Sent");
}
}
}
This is the message I receive:
Method Range.getValue is heavily used by the script
File: Code Line: 57
Any assistant would be kindly appreciated.
Try this:
Your missing the recipient and I would use SpreadsheetApp.openById();
function emailNotification() {
var nowH=new Date().getHours();
var nowD=new Date().getDay();
if(nowD>0 && nowD<6 && nowH>9 && nowH<5) {//integers only
var ss=SpreadsheetApp.openByUrl('spreadsheet url');//need url
var sh=ss.getSheetByName("tab name");//need sheet name
var vA=dataSheet.getRange(2,1,sh.getLastRow(),sh.getLastColumn()).getValues();
for (var i=0;i<vA.length;i++) {
var recipient=vA[i][?];//no recipient defined
var firstName=vA[i][4];
var lastName=vA[i][5];
var recipient=vA[i][2];
var isHired =vA[i][1];
var orgName =vA[i][2=10];
var emailSent =vA[i][17];
var html=Utilities.formatString('Hello,<br /><br /> %s %s has been added to the %s.<br /><br />Best, <br />Me',firstName,lastName,orgName);
var subject="New Hire";
if (isHired=="Yes" && emailSent != "Email Notification Sent" ) {
MailApp.sendEmail(recipient, subject,'',{htmlBody:html});
sh.getRange(i+2,18).setValue("Email Notification Sent");
}
}
}
}