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

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

Related

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())
}
});
}

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]);
}

Write to Spreadsheet in Google sheet from ASP.NET

I have a code, it should write in the Spreadsheet of google sheet. When I run the function, I receive this error:
Message[Requested writing within range ['6/12/2019-20:37'!A1], but
tried writing to column [B]] Location[ - ] Reason[badRequest]
Domain[global]
That its my code:
private void SheetPattern(Item webinar)
{
var valueRange = new ValueRange();
var range = $"{sheet}!A:D";
DateTime dateTime=(DateTime)webinar.webInfo.times[0].startTime;
var date = dateTime.Day+"-"+dateTime.Month+"-"+dateTime.Year;
var hour = dateTime.Hour + ":" + dateTime.Minute;
var webName = webinar.webInfo.subject;
var webDescription = webinar.webInfo.description;
var oblist = new List<object>() { date, hour, webName, webDescription};
valueRange.Values = new List<IList<object>> { oblist };
var appendRequest = service.Spreadsheets.Values.Append(valueRange, SpreadsheetId, range);
Console.WriteLine(appendRequest);
appendRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.USERENTERED;
var appendReponse = appendRequest.Execute();
}
I found the problem its a Syntax problem, here:
var hour = dateTime.Hour + ":" + dateTime.Minute;
when I make a new sheet with a new name, google sheet doesn't permit the char : in the sheet name. So I change this code for that code:
var hour = dateTime.Hour + "-" + dateTime.Minute;

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

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);
}
}

How to get the Current Date Time Formatted in Flex

I'm trying to get the current date time in Flex/AIR?
To get the current date time, just create a new Date object with no values into the constructor, like this:
var CurrentDateTime:Date = new Date();
Formatting it depends on how you want to format it; here is one option:
private function CurrentDateTimeString():String
{
var CurrentDateTime:Date = new Date();
var CurrentDF:DateFormatter = new DateFormatter();
CurrentDF.formatString = "MM/DD/YY LL:NN:SS A"
var DateTimeString:String = CurrentDF.format(CurrentDateTime);
return DateTimeString;
}
currentTime = new Date();
From : http://livedocs.adobe.com/flex/3/html/help.html?content=08_Dates_and_times_5.html
and
http://docs.huihoo.com/flex/4/Date.html
private function CurrentDateTimeString():String
{
var CurrentDateTime:Date = new Date();
var DateString:String = CurrentDateTime.getMonth().toString()+ "/"+CurrentDateTime.getDate().toString() +"/"+CurrentDateTime.getFullYear().toString();
var TimeString:String = CurrentDateTime.getHours().toString()+ ":"+ doubleDigitFormat(CurrentDateTime.getMinutes());
var DateTimeString:String = DateString + " " + TimeString;
return DateTimeString;
}
function doubleDigitFormat(num:uint):String
{
if(num < 10) {
return ("0" + num);
}
return num.toString();
}

Resources