My Javascript/GAS code uses the user ID to call for time entries via API for a specific date range (1 week) and sum up the hours. These time entries are saved in an array and then summed up. The first 50 additions on the log are correct but as you go through the list you realize wrong summed figures and long decimal places. What could be wrong and what can I do to solve this. Here is my code:
var TKF_URL = 'https://api.10000ft.com/api/v1/';
var TKF_AUTH = 'auth'
var TKF_PGSZ = 2500
var from = '2020-01-06'
var to = '2020-01-22'
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + TKF_AUTH
}
};
function getUsers() {
var userarray = [];
var lastpage = false;
var page = 1;
do {
// gets 10kft data
var users = read10k_users(page);
// writes data from current page to array
for (var i in users.data) {
var rec = {};
// pushing of mandatory data
rec.id = users.data[i].id;
rec.display_name = users.data[i].display_name;
rec.email = users.data[i].email;
userarray.push(rec);
}
// checks if this is the last page (indicated by paging next page link beeing null
if (users.paging.next != null) {
lastpage = false;
var page = page + 1;
} else {
lastpage = true;
}
}
while (lastpage == false);
return (userarray);
return (userarray);
}
function read10k_users(page) {
var endpoint = 'users?';
var url = TKF_URL + endpoint + 'per_page=' + TKF_PGSZ + '&auth=' + TKF_AUTH + '&page=' + page;
var response = UrlFetchApp.fetch(url, options);
var json = JSON.parse(response);
//Logger.log(json.data)
return (json);
}
function showTimeData() {
var users = getUsers()
var endpoint = 'users/';
var time_array = [];
for (var i = 0; i < users.length; i++) {
var total_hours = 0;
// Logger.log(users[i].id)
var url = 'https://api.10000ft.com/api/v1/users/' + users[i].id + '/time_entries?fields=approvals' + '&from=' + from + '&to=' + to + '&auth=' + TKF_AUTH;
var response = UrlFetchApp.fetch(url, options);
var info = JSON.parse(response.getContentText());
var content = info.data;
for (var j = 0; j < content.length; j++) {
total_hours += content[j].hours;
// }
//
// if(total_hours < 35){
//
// sendMail(user[i]);
//
// }
Logger.log('User name: ' + users[i].display_name + ' ' + 'User id: ' + users[i].id + ' ' + 'total hours: ' + total_hours)
}
}
function sendMail(user) {
var emailAddress = user.email;
var message = 'Dear ' + user.display_name + 'Your timesheets is incomplete , please visist 10k Ft and commlete your timesheet'
var subject = 'TimeSheet';
MailApp.sendEmail(emailAddress, subject, message);
}
}
Log results
You have total_hours declared outside of your loop. So what you are doing is calculating the total hours all workers combined, not total hours per worker.
(removed a lot of code to show only the important parts for your bug)
function showTimeData() {
var users = getUsers()
var total_hours = 0; // you declare the variable here
for (var i = 0; i < users.length; i++) {
var content = info.data;
// Calculate the sum for current user
for (var j = 0; j < content.length; j++) {
total_hours += content[j].hours;
}
// Check if total_hours for ALL workers is less than 35
if (total_hours < 35) sendMail(user[i]);
// total_hours is not reset, so the sum is used in next iteration.
}
}
Move the declaration of total_hours to inside the loop, or reset it to zero.
function showTimeData() {
for (var i = 0; i < users.length; i++) {
var total_hours = 0; // you declare the variable here
}
}
Your loop should look something like this:
for (var i = 0; i < users.length; i++) {
var total_hours = 0;
var url = "https://api.10000ft.com/api/v1/users/" + users[i].id + "/time_entries?fields=approvals" + "&from=" + from + "&to=" + to + "&auth=" + TKF_AUTH;
var response = UrlFetchApp.fetch(url, options);
var info = JSON.parse(response.getContentText());
var content = info.data;
for (var j = 0; j < content.length; j++) {
total_hours += content[j].hours;
}
if (total_hours < 35) {
sendMail(user[i]);
}
Logger.log("User name: " + users[i].display_name + " " + "User id: " + users[i].id + " " + "total hours: " + total_hours);
}
Related
function displayEvent(array) {
var vOutput = "";
var ind = 0;
for(var i = 0; i < array.length; i++) {
ind += 1;
vOutput += "Name " + ind + ": " + array[i].name + ", Age " + array[i].age + "<br />";
}
document.getElementById("output").innerHTML = vOutput;
}
function init() {
var arrEvent = [];
var objEvent = {};
objEvent.name = prompt("Enter name of Event");
objEvent.age = prompt("Enter number of Guests");
arrEvent.push(objEvent);
while(objEvent.name.length > 0) {
objEvent.name = prompt("Enter name of Event");
objEvent.age = prompt("Enter number of Guests");
if(objEvent.name.length > 0) {
arrEvent.push(objEvent);
}
}
displayEvent(arrEvent);
}
window.onload = init;
Trying to print an object array into the HTML paragraph id and whenever I execute the code above I get the correct output but the array elements just show as blank.
You are always pushing the same object into your array.
Change to:
function displayEvent(array) {
var vOutput = "";
var ind = 0;
for(var i = 0; i < array.length; i++) {
ind += 1;
vOutput += "Name " + ind + ": " + array[i].name + ", Age " + array[i].age + "<br />";
}
document.getElementById("output").innerHTML = vOutput;
}
function init() {
var arrEvent = [];
var name = '';
var age = '';
name = prompt("Enter name of Event");
age = prompt("Enter number of Guests");
arrEvent.push({name: name, age: age});
while(name.length > 0) {
name = prompt("Enter name of Event");
age = prompt("Enter number of Guests");
if(name.length > 0) {
arrEvent.push({name: name, age: age});
}
}
displayEvent(arrEvent);
}
window.onload = init;
I have a JavaScript code that gets response from API and sets the values on google spreadsheet.
The data that I get are users on a project that I need recorded to a sheet in spreadsheet.
The only challenge that I need help is avoiding overwriting existing sheet data on subsequent loop, how can I handle this ?
This first part gets project codes and uses it to make API call where the teams on all the projects are contained in a response.
function readDates() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range1 = sheet.getRange("C2:C" + sheet.getLastRow()).getValues();
var searchString = "Project";
var ahead = nextweek()
var behind = lastweek()
var team_array = [];
for (var i = 0; i < range1.length; i++) {
if (range1[i][0] >= behind && range1[i][0] <= ahead) {
var lastRow = sheet.getRange(2 + i, 1, 1, 8).getValues();
var dateval = lastRow[0][2]
var data = {
'project_id': lastRow[0][3]
};
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + AUTH
}
};
var url = tknurlL + Endpoint + data.project_id + '/users?auth=' + AUTH
var response = UrlFetchApp.fetch(url, options);
var team = JSON.parse(response);
var content = team.data;
team_array.push(content);
var ss = SpreadsheetApp.getActive().getSheetByName('Team');
const lr = sheet.getLastRow();
for (var j = 0; j < content.length; j++) {
ss.getRange(2 + j, 1).setValue(content[j].id);
ss.getRange(2 + j, 2).setValue(content[j].first_name);
ss.getRange(2 + j, 3).setValue(content[j].last_name);
ss.getRange(2 + j, 4).setValue(content[j].display_name);
ss.getRange(2 + j, 5).setValue(content[j].email);
ss.getRange(2 + j, 6).setValue(content[j].user_type_id);
ss.getRange(2 + j, 7).setValue(content[j].role);
}
}
}
}
How about this modification?
Modification points:
In your script, the same range of getRange(2 + j, 1) is used as the start range every time in the loop. By this, the values are overwritten by new content.
In this modification, the for loop for content is removed and put the values at the outside of the for loop. The retrieved content is added to the array of contents in the 1st for loop. By this, all content values (contents) can be put to the sheet of Team by setValues. And also, the process cost can be reduced a little.
Modified script:
When your script is modified, please modify as follows.
From:
var team_array = [];
for (var i = 0; i < range1.length; i++) {
if (range1[i][0] >= behind && range1[i][0] <= ahead) {
var lastRow = sheet.getRange(2 + i, 1, 1, 8).getValues();
var dateval = lastRow[0][2]
var data = {'project_id': lastRow[0][3]};
var options = {method: 'get',headers: {Authorization: 'Bearer ' + AUTH}};
var url = tknurlL + Endpoint + data.project_id + '/users?auth=' + AUTH
var response = UrlFetchApp.fetch(url, options);
var team = JSON.parse(response);
var content = team.data;
team_array.push(content);
var ss = SpreadsheetApp.getActive().getSheetByName('Team');
const lr = sheet.getLastRow();
for (var j = 0; j < content.length; j++) {
ss.getRange(2 + j, 1).setValue(content[j].id);
ss.getRange(2 + j, 2).setValue(content[j].first_name);
ss.getRange(2 + j, 3).setValue(content[j].last_name);
ss.getRange(2 + j, 4).setValue(content[j].display_name);
ss.getRange(2 + j, 5).setValue(content[j].email);
ss.getRange(2 + j, 6).setValue(content[j].user_type_id);
ss.getRange(2 + j, 7).setValue(content[j].role);
}
}
}
To:
var contents = []; // Added
var team_array = [];
for (var i = 0; i < range1.length; i++) {
if (range1[i][0] >= behind && range1[i][0] <= ahead) {
var lastRow = sheet.getRange(2 + i, 1, 1, 8).getValues();
var dateval = lastRow[0][2]
var data = {'project_id': lastRow[0][3]};
var options = {method: 'get',headers: {Authorization: 'Bearer ' + AUTH}};
var url = tknurlL + Endpoint + data.project_id + '/users?auth=' + AUTH
var response = UrlFetchApp.fetch(url, options);
var team = JSON.parse(response);
var content = team.data;
team_array.push(content);
contents = contents.concat(content); // Added
}
}
// I added below script.
if (contents.length > 0) {
var dstSheet = SpreadsheetApp.getActive().getSheetByName('Team');
var values = contents.map(e => ([e.id, e.first_name, e.last_name, e.display_name, e.email, e.user_type_id, e.role]));
dstSheet.getRange(2, 1, values.length, values[0].length).setValues(values);
}
Reference:
setValues(values)
Is there a way to get the 'username' and 'questionid' variable's value in my send() function like how I did with inputText?
var username;
var questionid;
function renderHTML(data) {
var htmlString = "";
var username = data[0].username;
//var examid = data[1].examid;
var questionid = data[2].questionid;
for (var i = 0; i < data.length; i++) {
htmlString += "<p>" + data[i].questionid + "." + "\n" + "Question: " + data[i].question + "\n" + "<input type='text'>";
htmlString += '</p>';
}
response.insertAdjacentHTML('beforeend', htmlString);
}
function send() {
var inputText = document.querySelectorAll("input[type='text']");
var data = [];
for (var index = 0; index < inputText.length; index++) {
input = inputText[index].value;
data.push({
'text': input
});
}
console.log(data);
You do not need var before username and questionid in your renderHTML function, as they have already been defined:
var username;
var questionid;
function renderHTML(data) {
var htmlString = "";
username = data[0].username;
//var examid = data[1].examid;
questionid = data[2].questionid;
for (var i = 0; i < data.length; i++) {
htmlString += "<p>" + data[i].questionid + "." + "\n" + "Question: " + data[i].question + "\n" + "<input type='text'>";
htmlString += '</p>';
}
response.insertAdjacentHTML('beforeend', htmlString);
}
function send() {
var inputText = document.querySelectorAll("input[type='text']");
var data = [];
for (var index = 0; index < inputText.length; index++) {
input = inputText[index].value;
data.push({
'text': input
});
}
console.log(data);
I am been trying to create a html table that is populated by objects.
The table was supposed to be selectable by row (via hover), when the row was hovered over a function ran.
The table headers are in an array:
var topTitles = ["Type","Origin","Destination","T","A","G"];
all the data are sitting inside arrays,
var Type = [];
var Origin = [];
var Destination = [];
var T = [];
var A = [];
var G = [];
I tried to modify an example piece of code, but it was very difficult to conceptualize it and place it into a programatic solution. What is an easy way to map such data directly into a interactive table.
function createTable() {
var table = document.getElementById('matrix');
var tr = addRow(table);
for (var j = 0; j < 6; j++) {
var td = addElement(tr);
td.setAttribute("class", "headers");
td.appendChild(document.createTextNode(topTitles[j]));
}
for (var i = 0; i < origins.length; i++) {
var tr = addRow(table);
var td = addElement(tr);
td.setAttribute("class", "origin");
td.appendChild(document.createTextNode(mode[i]));
for (var j = 0; j < topTitles.length; j++) {
var td = addElement(tr, 'element-' + i + '-' + j);
td.onmouseover = getRouteFunction(i,j);
td.onclick = getRouteFunction(i,j);
}
}
}
function populateTable(rows) {
for (var i = 0; i < rows.length; i++) {
for (var j = 0; j < rows[i].elements.length; j++) {
var distance = rows[i].elements[j].distance.text;
var duration = rows[i].elements[j].duration.text;
var td = document.getElementById('element-' + i + '-' + j);
td.innerHTML = origins[i] + "<br/>" + destinations[j];
}
}
}
if (highlightedCell) {
highlightedCell.style.backgroundColor="#ffffff";
}
highlightedCell = document.getElementById('element-' + i + '-' + j);
highlightedCell.style.backgroundColor="#e0ffff";
showValues();
}
This is probably the easiest way I could think of building the table without changing your data structure and make it very clear where all the data is coming from. It is defiantly not the best code, but it should work for your situation.
CodePen
var topTitles = ["Type","Origin","Destination","T","A","G"];
var Type = ["Type1", "type2", "type3"];
var Origin = ["Origin1", "origin2", "origin3"];
var Destination = ["Destination1", "Destination2", "dest3"];
var T = ["t1", "t2","T3"];
var A = ["steaksauce", "a2", "a3"];
var G = ["G1", "G2", "G3"];
var appendString = [];
for(var i =0; i < topTitles.length; i++){
if(!i){
appendString.push("<tr><td>" + topTitles[i] + "</td>");
}
else if(i === topTitles.length -1){
appendString.push("<td>" + topTitles[i] + "</td></tr>");
}
else{
appendString.push("<td>" + topTitles[i] + "</td>");
}
}
for(var i =0; i < Type.length; i++){
appendString.push("<tr><td>" + Type[i] + "</td><td>" + Origin[i] + "</td><td>" + Destination[i] + "</td><td>" + T[i] + "</td><td>" + A[i] + "</td><td>" + G[i] + "</td></tr>");
}
var table = document.getElementById('table');
table.innerHTML = appendString.join('');
I need to display a date from an array and it needs to be incremented for each input by 1 day. The date should display as mm/dd/yyyy. I was able to get the date to display correctly with the code that is in the message but after each input the all the dates would increment. I need just the last input to increment a day and I thought putting it in an array would work but now nothing displays. Thanks for helping.
var lowTempArray = [];
var highTempArray = [];
var nowArray = [];
function process() {
'use strict';
//declare variables
var lowTemp = document.getElementById('lowTemp');
var highTemp = document.getElementById('highTemp');
var output = document.getElementById('output');
var date = new Date();
var message = ' ';
if (lowTemp.value) {
lowTempArray.push(lowTemp.value);
if (highTemp.value) {
highTempArray.push(highTemp.value);
message = '<table><th>Date </th><th> Low Temperatures</th><th> High Temperatures</th>';
for (var i = 0, count = lowTempArray.length; i < count; i++) {
for (var i = 0, count = highTempArray.length; i < count; i++) {
for (var i = 0, count = nowArray.length; i < count; i++) {
nowArray.push(new Date(date.getTime()));
date.setDate(date.getDate() + count);
message += '<tr><td>' + ((nowArray.getMonth() + 1) + '/' + (nowArray.getDate() + count) + '/' + nowArray.getFullYear()) + '</td><td> ' + lowTempArray[i] + '</td><td> ' + highTempArray[i] + '</td></tr>';
}
message += '</table>';
output.innerHTML = message;
}
}
}
}
return false;
}
function init() {
'use strict';
document.getElementById('theForm').onsubmit = process;
} // End of init() function.
window.onload = init;