Why the "if" gets ignored in this Google apps script? - dictionary

I am trying to get a spreadsheet to update a calendar on my Google account, but I am struggling to get the if condition on the code below to work. When I run inseritoNelCal the debug says that it is unspecified even though the spreadsheet has actually data in each row/column.
var IN_CAL = new String('INSERITO');
function dallaTabellaAlCalendario() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 2; // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, 3);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var title = row[0]; // First column
var startTime = new Date(row[1]); // 2nd column
var endTime = new Date(row[02]); // 3rd column
var description = row[3]; // 4th column
var location = row[4]; // 5th column
var guests = row[5]; // 6th column
var inseritoNelCal = row[6]; // 7th column
}
if (inseritoNelCal != IN_CAL){
var calendar CalendarApp.getCalendarById("mycalendarID").createEvent(title, startTime, endTime, {Descrizione: description, Luogo: location, Allievi: guests, Inserito: inseritoNelCal });
sheet.getRange(startRow, 7).setValue(IN_CAL);
}
}

Related

does anyone have experience with the on form submission trigger creating an error code: "Exception: Event start time must be before event end time"

I am including the script ( below), the trigger, the sample of the spreadsheet, image of the start and end time formatting and the error(below)...
When I run the createCalendarEvent script manually...no issues..it is when i try to automate the script by creating an event trigger for on form submit that I get the following error:
Error Exception: Event start time must be before event end time.
at createCalendarEvent(create event:26:16)
function createCalendarEvent() {
var sheet = SpreadsheetApp.getActiveSheet();
var calendar =
CalendarApp.getCalendarById("c_71lju3i096qeqsg69bd7togo9g#group.calendar.google.com");
var startRow = 2; // First row of data to process - 2 exempts my header row
var numRows = sheet.getLastRow(); // Number of rows to process
var numColumns = sheet.getLastColumn();
var dataRange = sheet.getRange(startRow, 1, numRows-1, numColumns);
var data = dataRange.getValues();
var complete = "Done";
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var startTime = new Date(row[0]); //start Time
var endTime = new Date(row[1]); //end Time
var title = row[2]; //Item Title
var option = row[3]; //event option
var location = row[4]; //location
var eventID = row[6]; //event marked Done
if (eventID != complete) {
var currentCell = sheet.getRange(startRow + i, numColumns);
calendar.createEvent(title, startTime, endTime, {description: option + '\r' , location:
location});
currentCell.setValue(complete);
}
}
}
I have edited the original script and included the trigger just in the script itself ( By passing the automated trigger creation)...this way worked....1 time!..now i get the following error.
Exception: Action not allowed setUpTrigger # create event.gs5
function setUpTrigger() {
ScriptApp.newTrigger('createCalendarEvent')
.forForm('1FAIpQLScQvxc8EUSjGvrrVc6-QE3LwNZOytetIrfOVX-RKrJwS8_ALw')
.onFormSubmit()
.create();
}
function createCalendarEvent() {
var sheet = SpreadsheetApp.getActiveSheet();
var calendar = CalendarApp.getCalendarById("c_71lju3i096qeqsg69bd7togo9g#group.calendar.google.com");
var startRow = 2; // First row of data to process - 2 exempts my
header row
var numRows = sheet.getLastRow(); // Number of rows to process
var numColumns = sheet.getLastColumn();
var dataRange = sheet.getRange(startRow, 1, numRows-1, numColumns);
var data = dataRange.getValues();
var complete = "Done";
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var startTime = new Date(row[0]); //start Time
var endTime = new Date(row[1]); //end Time
var title = row[2]; //Item Title
var option = row[3]; //event option
var location = row[4]; //location
var eventID = row[6]; //event marked Done
if (eventID != complete) {
var currentCell = sheet.getRange(startRow + i, numColumns);
calendar.createEvent(title, startTime, endTime, {description:
option + '\r' , location: location});
currentCell.setValue(complete);
}
}
}
The error message is pretty self explanatory.
Error Exception: Event start time must be before event end time
Check the values you are sending for start and end time. Make sure that the event does not end before it starts.
var startTime = new Date(row[0]); //start Time
var endTime = new Date(row[1]); //end Time

Google sheet + App Script : Rename every sheet if it meet criteria

Hi I'm using this script to rename every sheet by inserting 'Copy of' in front of the existing sheet name where the text in cell 'B36' = 'SAFETY ANALISIS' and the date from cell 'K3'is older then 30 days. My issue is having to do with the date I can't quite figure how to do it. Cell 'K3' cell are in this format "1-Aug-2021" I think I need to convert the date in 'K3' to a number format.
Any help would be greatly appreciated
function getSheet() {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var sum = 0;
for (var i = 0; i < sheets.length ; i++ ) {
var sheet = sheets[i];
var date = new Date();
var ageInDays = 30;
var threshold = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate() - ageInDays)
.getTime();
var val = sheet.getRange('K3').getValue();
var val2 = sheet.getRange('B36').getValue();
if (val >= threshold && val2 == 'SAFETY ANALYSIS') {
var sheetName = sheet.getName()
sheet.setName('Copy Of '+sheetName)
}
}
}
You may want to wrap the value you get from cell K3 in a Date() constructor. That should work with spreadsheet dates as well as text strings that look like dates.
I think you have the comparison in val >= threshold the wrong way around. Try something like this:
function renameOldSafetyAnalysisSheets() {
const timeLimit = 30 * 24 * 60 * 60 * 1000; // 30 days
const now = new Date();
const sheets = SpreadsheetApp.getActive().getSheets();
sheets.forEach(sheet => {
if (sheet.getRange('K3').getValue() !== 'SAFETY ANALYSIS') {
return;
}
const date = new Date(sheet.getRange('B36').getValue());
if (!date.getTime()
|| now.getTime() - date.getTime() < timeLimit) {
return;
}
try {
sheet.setName('Copy of ' + sheet.getName());
} catch (error) {
;
}
});
}
function getSheet() {
const shts = SpreadsheetApp.getActive().getSheets();
let d = new Date();
let ageInDays = 30;
let threshold = new Date(d.getFullYear(),d.getMonth(),d.getDate() - ageInDays).valueOf();
shts.forEach(sh => {
let val = new Date(sh.getRange('K3').getValue()).valueOf();
let val2 = sh.getRange('B36').getValue();
if (val <= threshold && val2 == 'SAFETY ANALYSIS') {
sh.setName('Copy Of ' + sh.getName())
}
});
}

How to convert duration to seconds in Google Sheets which uses IMPORTRANGE

I have copied the data from Googlesheet1 to Googlesheet2 using the below query
=IMPORTRANGE("url","!A2:H")
Which has copied the data from Googlesheet1 to Googlesheet2.
In that sheet, I am having a duration column like the below image
When i used the app script to copy the data to the firestore instead of saving the duration it saves the data in DateTime format like below.
Is there any way to convert the given duration to seconds in Google sheet.
I have tried using =value(G2*24*3600) but it didn't work in the Googlesheet2 since that sheet is a clone of Googlesheet1
App script Logic:
function firestore() {
// Firestore setup
const email = "//client-email";
const key = "//client-key";
const projectId = "timesheet-aog";
var firestore = FirestoreApp.getFirestore (email, key, projectId);
// get document data from ther spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetname = "timesheet";
var sheet = ss.getSheetByName(sheetname);
// get the last row and column in order to define range
var sheetLR = sheet.getLastRow(); // get the last row
var sheetLC = sheet.getLastColumn(); // get the last column
var dataSR = 2; // the first row of data
// define the data range
var sourceRange = sheet.getRange(2,1,sheetLR-dataSR+1,sheetLC);
// get the data
var sourceData = sourceRange.getValues();
// get the number of length of the object in order to establish a loop value
var sourceLen = sourceData.length;
console.log('sourceLen is', sourceLen);
// Loop through the rows
for (var i=0;i<sourceLen;i++){
var data = {};
console.log('data is', sourceData);
data.date = sourceData[i][0];
data.name = sourceData[i][1];
data.workFrom = sourceData[i][2];
data.project = sourceData[i][3];
data.phase = sourceData[i][4];
data.task = sourceData[i][5];
data.totalHrs = sourceData[i][6];
data.comments = sourceData[i][7];
firestore.createDocument("timesheet",data);
}
}
Here is the formula for A1 cell of the second sheet:
={
IMPORTRANGE("url","!A2:F"),
ARRAYFORMULA(
IF(
IMPORTRANGE("url","!G2:G") = "",
"",
N(IMPORTRANGE("url","!G2:G")) * 24 * 3600
)
),
IMPORTRANGE("url","!H2:H")
}
Try using named ranges for columns (A2:F, G2:G, H2:H) in the original sheet, and import them by those names so you won't need to adjust the formula where exact column names are used.

I need help for woocommerce integration in google sheet through web hook

I just attach my woocommerce through webhook in google sheet and get some code from internet for getting orders data on it every things looks fine but there is only one product name available even if the order contain more than one products.You can check the webhook data here when order is created. here is my google sheet 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_created = myData.date_created;
var product_name = myData.line_items[0].name;
var itemName = myData.line_items[0].name;
var quantity = myData.line_items[0].quantity;
var product_items = quantity + " x " + itemName + "\n";
var product_qty = myData.line_items[0].quantity;
var order_total = myData.total;
var billing_email = myData.billing.email;
var billing_first_name = myData.billing.first_name;
var billing_phone = myData.billing.phone;
var shipping_address = myData.shipping.address_1;
var timestamp = new Date();
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow([timestamp,order_created,billing_first_name,billing_phone,shipping_address,product_name,product_qty,order_total,billing_email,product_items]);
}
You are trying to loop through sone JSON transaction data that includes multiple line items.
There are two flaws in your code:
1 - the script does not loop through the product items:
var product_name = myData.line_items[0].name;
var itemName = myData.line_items[0].name;
var quantity = myData.line_items[0].quantity;
var product_items = quantity + " x " + itemName + "\n";
var product_qty = myData.line_items[0].quantity;
You are getting line_items[0], but if there are multiple line items in the transaction then you are only ever returning the first line item.
2 - The variables being appended in sheet.appendRow() need to be re-considered.
Your code specifies ten variables, including product name and product quantity. However there are no unique values for these two variables since they are form part of the line items and vary with each line item in the transaction.
Your variable product_items is an attempt to recognise this by concatenating the details for each line item; however the variable fails because it depends on looping through the line_items AND progressively concatenating line item values.
The following code is an example of how you might achieve your outcome:
function doPost(e) {
var myData = JSON.parse([e.postData.contents]);
var timestamp = new Date();
var order_created = myData.date_created;
var billing_first_name = myData.billing.first_name;
var billing_phone = myData.billing.phone;
var billing_email = myData.billing.email;
var shipping_address = myData.shipping.address_1;
var order_total = myData.total;
var lineitems=""
for (i in myData.line_items)
{
var product_name = myData.line_items[i].name;
var itemName = myData.line_items[i].name;
var quantity = myData.line_items[i].quantity;
var linetotal = myData.line_items[i].total;
var product_items = quantity + " x " + itemName + ":$"+linetotal +"\n";
var lineitems =lineitems+product_items;
}
Logger.log("Timestamp: "+timestamp);
Logger.log("Order created: "+order_created);
Logger.log("Billing first name: "+billing_first_name+", Phone: "+billing_phone+", Email: "+billing_email);
Logger.log("Shipping Address: "+shipping_address)
Logger.log("Line items = "+lineitems);
Logger.log("Order Total: "+order_total)
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow([timestamp,order_created,billing_first_name,billing_phone,shipping_address,order_total,billing_email,lineitems]);
}

sort ArrayCollection by date then time - Flex

I have an ArrayCollection that I'd like to sort by date and then time (in case there's two items with the same date). I've got it sorting by date fine (YYYY/MM/DD) but I can't figure out the time bit, time is in 24 hour format so the code would be basically the same as for the date.
This is the code I used for the date sorting, it works fine.
import mx.collections.SortField;
import mx.collections.Sort;
private function sort():void
{
var dataSortField:SortField = new SortField();
dataSortField.name = "date";
var arrayDataSort:Sort = new Sort();
arrayDataSort.fields = [dataSortField];
reminderXMLArray.sort = arrayDataSort;
reminderXMLArray.refresh();
}
You can use this code to sort by date and time:
private function sort():void
{
var dataSortField:SortField = new SortField();
dataSortField.name = "date";
dataSortField.compareFunction = function (a:Object, b:Object) : int {
var na:Number = a.date.getTime();
var nb:Number = b.date.getTime();
if (na < nb)
return -1;
if (na > nb)
return 1;
return 0;
};
var arrayDataSort:Sort = new Sort();
arrayDataSort.fields = [dataSortField];
reminderXMLArray.sort = arrayDataSort;
reminderXMLArray.refresh();
}
As there are two separate fields that you want to sort on you can just use the Sort object's fields Array to add two sort fields:
var sort:Sort = new Sort();
var fields:Array = [ new SortField("date"), new SortField("time") ];
sort.fields = sort;

Resources