How do I email an update to the table results for specific columns that meet the criteria less than 0? - google-apps-script

I have a table that I would like to send an email for based on the values of columns E(table below). The Columns I would like to append to the email are A,D,E,F. The Rows I would like to include are those that have dropped below 0 from column E. How do I amend my function to allow for this change?
function EmailUpdate() {
var hty = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Historical')
var data = hty.getRange("A1:F" + hty.getLastRow()).getValues().filter(([,e], i) => i == 0 || e < 0);
var TABLEFORMAT = 'cellspacing="2" cellpadding="2" dir="ltr" border="1" style="width:100%;table-layout:fixed;font-size:10pt;font-family:arial,sans,sans-serif;border-collapse:collapse;border:1px solid #ccc;font-weight:normal;color:black;background-color:white;text-align:left;text-decoration:none;font-style:normal;'
var htmltable = '<table ' + TABLEFORMAT + ' ">';
for (row = 0; row < data.length; row++) {
htmltable += '<tr>';
for (col = 0; col < data[row].length; col++) {
if (data[row][col] === "" || 0) {
htmltable += '<td>' + 'None' + '</td>';
} else
if (row === 0) {
htmltable += '<th>' + data[row][col] + '</th>';
} else {
htmltable += '<td>' + data[row][col] + '</td>';
}
}
htmltable += '</tr>';
}
htmltable += '</table>';
Logger.log(data);
Logger.log(htmltable);
MailApp.sendEmail(Session.getActiveUser().getEmail(), 'Email Report', '' ,{
htmlBody: htmltable
})
}

Replace:
var data = hty.getRange("A1:F" + hty.getLastRow()).getValues().filter(([,e], i) => i == 0 || e < 0);
With:
var data = hty.getRange("A1:F"+hty.getLastRow()).
getDisplayValues().
map(([a,,,d,e,f]) => [a,d,e,f]).
filter((r,i)=>r[2].includes("-") || i==0 );
References:
map
filter

Related

Google script won't sent out the emails using Gmailapp.sendemail()

I try to use google script to send out some automation emails based on values from a google sheet. all the variables are not in HTML format for the email body or email subject. the execution is complete but no email received. here is the sample code:
if(activitytype == "CTV" && datectvreceived == ""){
if(firstattemp == "" && 5000 >firstattempdays > 1){
var logic1message = l1content1 + plemail + l1content2 + ccemail + l1content3 + pvcemail + l1content4 +protocolNum + l1content5 + protocolNum + '-'+ studytitle + l1content6 + reportperiod + l1content7;
GmailApp.sendEmail(pvoemail,'First Attempt Reminder: ' +protocolNum ,logic1message);
}// first logic
else if(firstattemp != "" && secondattemp == "" && 5000>secondattempdays > 7){
var logic2message = l2content1 + plemail + l2content2 + ccemail+ l2content3 + pvcemail + l2content4 + protocolNum + l2content5 + protocolNum + '-' + studytitle + l2content6 + reportperiod + l2content7 + firstattemp + l2content8;
GmailApp.sendEmail(pvoemail,'Second Attempt Reminder: '+ protocolNum,logic2message);
} //second logic
else if(secondattemp != "" && firstattemp != "" && thirdattemp == "" && 5000>thirdattempdays > 7){
var logic3message = l3content1 + plemail + l3content2 + ccemail + l3content3 + pvcemail + l3content4 + protocolNum + l3content5 + protocolNum + '-' + studytitle + l3content6 + reportperiod + l3content7 + firstattemp + '&' + secondattemp + l3content8;
GmailApp.sendEmail(pvoemail,'Third Attempt Reminder: ' + protocolNum,logic3message);
} // third logic
else if (thirdattemp != "" && secondattemp != "" && firstattemp != "" &&srtattemp == "" && 5000 >srtattempday > 7){
var logicsrtmessage = lscontent1 + plemail + lscontent2 +ccemail + lscontent3 + pvcemail + lscontent4 + firstattemp + lscontent5 + secondattemp + lscontent6 + thirdattemp + lscontent7;
GmailApp.sendEmail(pvoemail,'SRT Esaclation Reminder: '+ protocolNum,logicsrtmessage);
} //srt logic
sheet.getRange(startRow +i, 26).setValue(EMAIL_SENT); // a note for the protocols which email were sent
SpreadsheetApp.flush();}
else {sheet.getRange(startRow +i, 26).setValue(No_Email_Sent);
SpreadsheetApp.flush();
please advice. thank you guys!!!!!
I believe you need to change all your if, else if(s)
if(firstattemp == "" && 5000 >firstattempdays > 1){
This is equivalent to
if( ( firstattemp == "" ) && ( ( 5000 >firstattempdays ) > 1) ) {
So ( 5000 >firstattempdays ) is either true or false
and ( true > 1 ) is false and ( false > 1 ) is also false
Change these to
if( ( firstattemp == "" ) && ( 5000 > firstattempdays ) && ( firstattempdays > 1) ) {

Google Apps Script For loop not repeating inside while loop

I have long code wherein there is a while loop and inside that while loop there is a for loop and then an if statement. I want that for loop to run again and again until condition of the while loop is fulfilled. Although, that If statement keeps repeating under while loop I am not understanding why that For loop only runs once and never repeats. Please guide what is wrong in the code;
while(affDisc == 'NotClr'){
//Finding affiliate discount row
for(var i = 20; i <= odrEn && slsRprtSh.getRange('I' + i).getValue() > 0 && slsRprtSh.getRange('J' + i).getValue() == 0; i++){
Logger.log(vndr + ' ' + i);
Logger.log(minOdrRw);
if(minOdr == 0){
minOdr = slsRprtSh.getRange('I' + i).getValue();
minOdrRw = i;
}else if(slsRprtSh.getRange('I' + i).getValue() < minOdr){
minOdr = slsRprtSh.getRange('I' + i).getValue();
minOdrRw = i;
}
}
//check if applying discount in minimum order fits here
if(aggFloor - runinFloor > runinFloor + minOdr * .05 - aggFloor && slsRprtSh.getRange('J' + minOdrRw).getValue() == 0){
Logger.log('runfloo ' + runinFloor);
//return false;
slsRprtSh.getRange('J' + minOdrRw).setValue(minOdr * .05);
slsRprtSh.getRange('J' + minOdrRw).setNote('5% discount for affiliate commission');
slsRprtSh.getRange('L' + minOdrRw).setFormulaR1C1('=R[0]C[-3]-R[0]C[-2]');
slsRprtSh.getRange('M' + minOdrRw).setFormulaR1C1('=R[0]C[-1]*0.15');
slsRprtSh.getRange('N' + minOdrRw).setFormulaR1C1('=R[0]C[-1]+R[0]C[-2]');
apldDisc = apldDisc + minOdr * .05;
runinFloor = runinFloor + minOdr * .05;
}else if(aggFloor - runinFloor < runinFloor + minOdr * .05 - aggFloor){
affDisc = 'Clr';
}
}

AWS Step Functions: Transform a state array output to an object with keys

I need to transform the output of a parallel step that comes out as an array into an object. Consider something like this:
Output of the parallel step:
[1, 2, 3]
I need to transform it to an object:
{ "one": 1, "two": 2, "three": 3 }
Any ideas?
try this, hope this can help you
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var array = [1, 2, 3, 21];
var output= {};
for (var i in array) {
output[inWords(array[i])] = array[i];
}
console.log(output);
function inWords (num) {
var a = ['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
if ((num = num.toString()).length > 9) return 'overflow';
n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
if (!n) return; var str = '';
str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';
str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';
str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';
str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
str += (n[5] != 0) ? ((str != '') ? 'and ' : '') + (a[Number(n[5])] || b[n[5][0]] + a[n[5][1]]) : '';
return str;
}
</script>
</body>
</html>

Google Apps Script to remove hangouts links from calendar events

I have successfully accessed a Google calendar event and can change the color, but I'm stuck when it comes to removing the hangouts link.
I'm attempting to use code to automatically remove the hangouts links when I am the meeting originator and have not changed the hangout name, but I'm not having any success in actually changing the link.
Any help greatly appreciated.
function removehangout() {
var calendarId = 'primary';
//var calendars = CalendarApp.getOwnedCalendarsByName('Mirage ELDRIDGE');
var now = new Date();
// Determines how many events are happening in the next 24 hours x 1 days.
var now = new Date();
var endr = new Date(now.getTime() + (1 * 24 * 60 * 60 * 1000));
var events2 = CalendarApp.getDefaultCalendar().getEvents(now, endr);
Logger.log('Number of events: ' + events2.length);
var events = Calendar.Events.list(calendarId, {
timeMin: now.toISOString(),
singleEvents: true,
orderBy: 'startTime',
maxResults: 5
});
if (events.items && events.items.length > 0) {
for (var i = 0; i < events.items.length; i++) {
var event1 = events.items[i];
var d = event1.description;
var ttitle = event1.summary;
var whoby = event1.creator.email;
Logger.log(ttitle + ' by: ' + whoby);
if(whoby.indexOf('mirage.eldridge') != -1){
Logger.log(ttitle + '--> was by mirage');
var hangoutname = event1.hangoutLink;
Logger.log(ttitle + '--> hangout link name --> ' + hangoutname);
if (hangoutname != null) {
if (hangoutname.indexOf('mirage-eldridge') != -1){
//delete this link here
Logger.log(ttitle + '--> remove hangout');
//event.setHangoutLink(null);
//var idno = event.iCalUID
//CalendarApp.getEventSeriesById(idno)
event1.HangoutLink = null;
Logger.log(ttitle + '... ' + event1.hangoutLink);
Logger.log(event1.iCalUID);
//event.setcolorId('11');
var event2 = Calendar.Events.get(calendarId, event1.id)
event2.colorId = 9;
event2.hangoutLink = 'fred';
//Calendar.Events.patch(event2,calendarId,event1.id);
Calendar.Events.update(event2,calendarId,event1.id);
}
} else {
Logger.log(ttitle + ' -- do not remove ' + hangoutname);
}
}
if (!d)
d = '';
//var foundlinkyes = d.indexOf('HangoutLink');
//var actuallink = event.hangoutLink;
//var hasrlink = 'True';
//if (!actuallink) {
//Logger.log(ttitle + ' no link found');
//hasrlink = "False";
//}
//Logger.log('desc: ' + ttitle + '-- foundyes: ' + foundlinkyes);
//if (foundlinkyes == -1 && hasrlink == 'True'){
//if (event.hangoutLink && (d.indexOf('Hangout: ')== -1)){
//Logger.log (event.summary + ' - ' + event.hangoutLink + ' - ' + event.description);
//Logger.log(ttitle + ' added this ' + event.hangoutLink);
//event.description = 'HangoutLink: ' + event.hangoutLink + '\n\n' + d;
//Calendar.Events.update(event, calendarId, event.id);
//foundlinkyes = 0;
//hasrlink = 'True';
//}
//}
}
} else {
Logger.log('No events found.');
}
}

How to export (dump) WebSQL data

I'm working on a Chrome Extension that uses WebSQL to store historical data.
Being WebSQL, the DB is stored on the client.
I'd like to add an option to export/import such data so that the user can share/use this data with other users, or with other PCs.
These are my first steps on a client-only database, so I wonder how to do this.
I was thinking to convert the DB to a huge json string that the user can copy/paste but doesn't look very user-friendly.
Is there any better solution?
I got a single table dump solution working on a HTML5 database client I wrote a few days ago.
Check out http://html5db.desalasworks.com/script.js and scroll down to SqlClient.exportTable, this has an example that needs to be expanded to cover the whole database.
The steps are:
Step 1: Create the schema:
SELECT sql FROM sqlite_master
Step 2: Get a list of tables:
SELECT tbl_name from sqlite_master WHERE type = 'table'
Step 3: Loop through each of them and create an INSERT script with the results
transaction.executeSql("SELECT * FROM " + _tbl_name + ";", [],
function(transaction, results) {
if (results.rows) {
for (var i = 0; i < results.rows.length; i++) {
var row = results.rows.item(i);
var _fields = [];
var _values = [];
for (col in row) {
_fields.push(col);
_values.push('"' + row[col] + '"');
}
_exportSql += ";\nINSERT INTO " + _tbl_name + "(" + _fields.join(",") + ") VALUES (" + _values.join(",") + ")";
}
}
}
);
Hope this is useful.
UPDATE JAN 2016 - WHOLE DB EXPORT
I've got a JS websqldump library that you can download from github as well.
This one will export the whole database. Check out the code on:
https://github.com/sdesalas/websqldump
Usage as follows
websqldump.export({
database: 'NorthwindLite',
success: function(sql) {alert(sql);}
});
Not the most elegant way, yet most convenient.
Just paste the script in chrome debugger tools then call c(), and you should get the file.
var looongSQL = "";
var x = function (options) {
if (options.n < options.sqlTables.length) {
onTheMove.openLocalDatabase().transaction(
function (tx) {
var sqlStatement = "SELECT * FROM " + options.sqlTables[options.n];
tx.executeSql(sqlStatement, [],
function (tx, rslt) {
if (rslt.rows) {
for (var m = 0; m < rslt.rows.length; m++) {
var dataRow = rslt.rows.item(m);
var _fields = [];
var _values = [];
for (col in dataRow) {
_fields.push(col);
_values.push('"' + dataRow[col] + '"');
}
looongSQL += "INSERT INTO " + options.sqlTables[options.n] + "(" + _fields.join(",") + ") VALUES (" + _values.join(",") + ");\n";
}
}
options.n++;
x(options);
}
);
});
}else
{
document.location = 'data:Application/octet-stream,' +
encodeURIComponent(looongSQL);
}
};
var c = function () {
onTheMove.openLocalDatabase().transaction(
function (transaction) {
transaction.executeSql("SELECT sql FROM sqlite_master;", [],
function (transaction, results) {
var sqlStatements = [];
if (results.rows) {
for (var i = 0; i < results.rows.length; i++) {
console.log(results.rows.item(i));
var row = results.rows.item(i);
if (row.sql != null && row.sql.indexOf("CREATE TABLE ") != -1 && row.sql.indexOf("__") == -1) {
var tableName = row.sql.replace("CREATE TABLE ", "").split(/ |\(/)[0];
sqlStatements.push('DROP TABLE IF EXISTS ' + tableName);
}if(row.sql != null && row.sql.indexOf("__") == -1){
sqlStatements.push(row.sql);}
}
}
for (var j = 0; j < sqlStatements.length; j++) {
if (sqlStatements[j] != null) {
looongSQL += sqlStatements[j] + ';\r\n';
}
}
transaction.executeSql("SELECT tbl_name from sqlite_master WHERE type = 'table'", [],
function (transaction, res) {
var sqlTables = [];
for (var k = 0; k < res.rows.length; k++) {
if (res.rows.item(k).tbl_name.indexOf("__") == -1) {
sqlTables.push(res.rows.item(k).tbl_name);
}
}
x({
sqlTables: sqlTables,
n: 0
});
});
}
);
});
};
Another version that exports it as JSON
var looongSQL = "[\n";
var stringidiedLocalStorage = JSON.stringify(JSON.stringify(localStorage));
looongSQL += "/* 1 */ " + stringidiedLocalStorage + ",\n";
var x = function (options) {
if (options.n < options.sqlTables.length) {
onTheMove.openLocalDatabase().transaction(
function (tx) {
var sqlStatement = "SELECT * FROM " + options.sqlTables[options.n];
tx.executeSql(sqlStatement, [],
function (tx, rslt) {
if (rslt.rows && rslt.rows.length > 0) {
var _fields = [];
for (var col in rslt.rows.item(0)) {
_fields.push(col);
}
var insertTableSQL = "\"INSERT INTO " + options.sqlTables[options.n] + "(" + _fields.join(",") + ") ";
looongSQL += "/* " + options.count + " */ " + insertTableSQL;
for (var m = 0; m < rslt.rows.length; m++) {
var dataRow = rslt.rows.item(m);
var _values = [];
for (var col in dataRow) {
_values.push('\'' + dataRow[col] + '\'');
}
looongSQL += "SELECT " + _values.join(",");
if (m < rslt.rows.length - 1 && (m % 499 != 0 || m == 0)) {
looongSQL += " UNION ALL ";
}
if (m % 499 == 0 && m != 0) {
options.count++;
looongSQL += "\",\r\n/* " + options.count + " */ " + insertTableSQL;
}
}
looongSQL += "\",\r\n";
options.count++;
}
options.n++;
x(options);
}
);
});
} else {
looongSQL += ']';
document.location = 'data:Application/octet-stream,' +
encodeURIComponent(looongSQL);
}
};
var c = function () {
onTheMove.openLocalDatabase().transaction(
function (transaction) {
transaction.executeSql("SELECT sql FROM sqlite_master;", [],
function (transaction, results) {
var sqlStatements = [];
var count = 2;
if (results.rows) {
for (var i = 0; i < results.rows.length; i++) {
console.log(results.rows.item(i));
var row = results.rows.item(i);
if (row.sql != null && row.sql.indexOf("CREATE ") != -1) {
var objectType = row.sql.replace("CREATE ", "").split(/ |\(/)[0];
if (row.sql.indexOf("CREATE " + objectType + " ") != -1 && row.sql.indexOf("__") == -1) {
var objectName = row.sql.replace("CREATE " + objectType + " ", "").split(/ |\(/)[0];
sqlStatements.push('/* ' + count + ' */ "DROP ' + objectType + ' IF EXISTS ' + objectName + '"');
count++;
}
if (row.sql != null && row.sql.indexOf("__") == -1) {
sqlStatements.push('/* ' + count + ' */ "' + row.sql.replace(/(\r\n|\n|\r)/gm, " ") + '"');
count++;
}
}
}
}
for (var j = 0; j < sqlStatements.length; j++) {
if (sqlStatements[j] != null) {
looongSQL += sqlStatements[j] + ',\r\n';
}
}
transaction.executeSql("SELECT tbl_name from sqlite_master WHERE type = 'table'", [],
function (transaction, res) {
var sqlTables = [];
for (var k = 0; k < res.rows.length; k++) {
if (res.rows.item(k).tbl_name.indexOf("__") == -1) {
sqlTables.push(res.rows.item(k).tbl_name);
}
}
x({
sqlTables: sqlTables,
n: 0,
count: count
});
});
}
);
});
};