I am once in a while getting this error:
Jan 5, 2023, 11:03:48 AM Error Exception: Failed to retrieve form
data. Please wait and try again. at processForm(Code:2:22)
Line 2 is:
var form = FormApp.getActiveForm();
Full script
function processForm(event) {
var form = FormApp.getActiveForm();
Logger.log("Form retrieved " + form)
var allResponses = form.getResponses();
var latestResponse = allResponses[allResponses.length - 1];
var itemResponses = latestResponse.getItemResponses();
//const itemResponses = event.response.getItemResponses();
const propertyAddress = itemResponses[0].getResponse();
Logger.log("Processing address " + propertyAddress);
// Get the number of units. index 5
const moreThan200Units = parseInt(itemResponses[5].getResponse(), 10);
var mainFolder = null;
if(moreThan200Units > 199) {
mainFolder = DriveApp.getFolderById('xx');
} else {
mainFolder = DriveApp.getFolderById('yy');
}
var propertyFolder = null;
for (var i = 0; i < itemResponses.length; i++) {
Logger.log(itemResponses[i].getItem().getType())
if (itemResponses[i].getItem().getType() == "FILE_UPLOAD") {
if(propertyFolder == null) {
propertyFolder = mainFolder.createFolder(propertyAddress);
}
var ids = itemResponses[i].getResponse();
for (var j = 0; j < ids.length; j++) {
var uploadedFile = DriveApp.getFileById(ids[j]);
Logger.log("Moving file" + uploadedFile + " to " + propertyFolder);
uploadedFile.moveTo(propertyFolder);
}
}
}
}
Related
This script import opportunities that we get. It populates rows which then calculates some numbers such as interest and stuff. However, I now have errors when populating my cells (#REF error, see pictures below). Nothing has changed so my first guess is it has do with the processing of the sheet which has become too heavy.
`
function onInstall(e) {
onOpen(e);
}
function onOpen(e) {
var menu = SpreadsheetApp.getUi().createAddonMenu();
menu.addItem('Créer étude', 'init');
menu.addToUi();
}
function init() {
ss = SpreadsheetApp.getActiveSpreadsheet();
identifyJe();
sheetMaker = ss.getActiveSheet();
currentRow = ss.getActiveCell().getRowIndex();
ssEtudes = SpreadsheetApp.openById(getSheetEtudesId());
var ui = SpreadsheetApp.getUi();
var respon se = ui.alert(
'Ligne sélectionnée : ' + currentRow + '. Exécuter ?',
ui.ButtonSet.OK_CANCEL
);
if (response !== ui.Button.OK) return;
doEtude();
doContrat();
doPhases();
}
function doEtude(nomEtude) {
var etudeData = [];
for (var i = 0; i < etudeNamedRanges.length; i++) {
var column = ss.getRangeByName(etudeNamedRanges[i]).getColumn();
etudeData.push(sheetMaker.getRange(currentRow, column).getValue());
}
var destSheet = ssEtudes.getSheetByName('etudes');
var rowToAppend = getFirstEmptyRow(destSheet, 0);
for (var i = 0; i < etudeData.length; i++) {
var column = ssEtudes.getRangeByName(etudeNamedRanges[i]).getColumn();
destSheet.getRange(rowToAppend, column).setValue(etudeData[i]);
}
}
function doContrat() {
var contratData = [];
for (var i = 0; i < contratNamedRanges.length; i++) {
var column = ss.getRangeByName(contratNamedRanges[i]).getColumn();
contratData.push(sheetMaker.getRange(currentRow, column).getValue());
}
var destSheet = ssEtudes.getSheetByName('contrats');
var rowToAppend = getFirstEmptyRow(destSheet, 11);
for (var i = 0; i < contratData.length; i++) {
destSheet.getRange(rowToAppend, i + 4).setValue(contratData[i]);
}
}
function doPhases() {
var phasesCoords = getPhasesCoords();
var phasesData = [];
for (var i = 0; i < phasesCoords.length; i++) {
var phaseData = getPhaseData(phasesCoords[i]);
phaseData.unshift(i + 1);
phasesData.push(phaseData);
}
var destSheet = ssEtudes.getSheetByName('phases');
var rowToAppend = getFirstEmptyRow(destSheet, 9);
var columns = [];
for (var nPhase = 0; nPhase < phasesData.length; nPhase++) {
var phaseData = phasesData[nPhase];
for (var i = 0; i < phaseData.length; i++) {
if (columns[i] === undefined)
columns[i] = ssEtudes.getRangeByName(phasesNamedRanges[i]).getColumn();
destSheet
.getRange(rowToAppend + nPhase, columns[i])
.setValue(phaseData[i]);
}
}
}
`
Type of formula
The results
The error, which translates into The result could not be auto-expanded. Please insert new columns (1).
The results actually appear for some time and disappear after a few seconds, constantly. Does it have something to do with the size of the spreadsheet ?
After getting interested in a code proposed on Github to get WooCommerce orders in Google Sheets: https://github.com/mithunmanohar/woocommerce-orders-google-sheets-integration
I integrated this code in a sheet with its script but this code has a defect: when updating the status of an order the script adds an extra line instead of changing the status of the line corresponding to the order.
We get a duplicate as you can see here :
Same ID but statut different
You can find the complete code of the script here: https://github.com/mithunmanohar/woocommerce-orders-google-sheets-integration/blob/master/wc-gc-integration.gs
// Updated code to v2 Woocommerce API
function start_syncv2() {
var sheet_name = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
fetch_orders(sheet_name)
}
function fetch_orders(sheet_name) {
var ck = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_name).getRange("B4").getValue();
var cs = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_name).getRange("B5").getValue();
var website = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_name).getRange("B3").getValue();
var manualDate = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_name).getRange("B6").getValue(); // Set your order start date in spreadsheet in cell B6
var m = new Date(manualDate).toISOString();
var surl = website + "/wp-json/wc/v2/orders?consumer_key=" + ck + "&consumer_secret=" + cs + "&after=" + m + "&per_page=100";
var url = surl
//Logger.log(url)
var options =
{
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
};
var result = UrlFetchApp.fetch(url, options);
Logger.log(result.getResponseCode())
if (result.getResponseCode() == 200) {
var params = JSON.parse(result.getContentText());
//Logger.log(params);
}
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = doc.getSheetByName(sheet_name);
var consumption = {};
var arrayLength = params.length;
for (var i = 0; i < arrayLength; i++) {
var a, c, d;
var container = [];
a = container.push(params[i]["billing"]["first_name"]);
a = container.push(params[i]["billing"]["last_name"]);
a = container.push(params[i]["billing"]["address_1"]+ " "+ params[i]["billing"]["postcode"]+ " "+ params[i]["billing"]["city"]);
a = container.push(params[i]["shipping"]["first_name"] + " "+ params[i]["shipping"]["last_name"]+" "+ params[i]["shipping"]["address_2"]+" "+ params[i]["shipping"]["address_1"]+" "+params[i]["shipping"]["postcode"]+" "+params[i]["shipping"]["city"]+" "+params[i]["shipping"]["state"]+" "+params[i]["shipping"]["country"]);
a = container.push(params[i]["billing"]["phone"]);
a = container.push(params[i]["billing"]["email"]);
a = container.push(params[i]["customer_note"]);
a = container.push(params[i]["payment_method_title"]);
c = params[i]["line_items"].length;
var items = "";
var total_line_items_quantity = 0;
for (var k = 0; k < c; k++) {
var item, item_f, qty, meta;
item = params[i]["line_items"][k]["name"];
qty = params[i]["line_items"][k]["quantity"];
item_f = qty + " x " + item;
items = items + item_f + ",\n";
total_line_items_quantity += qty;
}
a = container.push(items);
a = container.push(total_line_items_quantity); // Quantity
a = container.push(params[i]["total"]); //Price
a = container.push(params[i]["discount_total"]); // Discount
d = params[i]["refunds"].length;
var refundItems = "";
var refundValue = 0.0;
for (var r = 0; r < d; r++) {
var item, item_f, value;
item = params[i]["refunds"][r]["reason"];
value = params[i]["refunds"][r]["total"];
refundValue += parseFloat(value);
item_f = value +" - "+ item;
refundItems += item_f + ",\n";
}
a = container.push(refundValue); //Refunded value from order
a = container.push(parseFloat(container[10]) + refundValue); // Total minus refund
a = container.push(refundItems); //Refunded items from order
a = container.push(params[i]["id"]);
a = container.push(params[i]["date_created"]);
a = container.push(params[i]["date_modified"]);
a = container.push(params[i]["status"]);
a = container.push(params[i]["order_key"]);
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = doc.getSheetByName(sheet_name);
temp.appendRow(container);
Logger.log(params[i]);
removeDuplicates(sheet_name);
}
}
function removeDuplicates(sheet_name) {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sheet = doc.getSheetByName(sheet_name);
var data = sheet.getDataRange().getValues();
var newData = new Array();
for (i in data) {
var row = data[i];
/* TODO feature enhancement in de-duplication
var date_modified =row[row.length-2];
var order_key = row[row.length];
var existingDataSearchParam = order_key + "/" + date_modified;
*/
var duplicate = false;
for (j in newData) {
var rowNewData = newData[j];
var new_date_modified =rowNewData[rowNewData.length-2];
var new_order_key = rowNewData[rowNewData.length];
//var newDataSearchParam = new_order_key + "/" + new_date_modified; // TODO feature enhancement in de-duplication
if(row.join() == newData[j].join()) {
duplicate = true;
}
// TODO feature enhancement in de-duplication
/*if (existingDataSearchParam == newDataSearchParam){
duplicate = true;
}*/
}
if (!duplicate) {
newData.push(row);
}
}
sheet.clearContents();
sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}
I have written an app script that will interact with the bigQuery API and fetch the bigQuery results.
API is been hit around close to 60-70 times. In this process sometimes I'm getting the following error message:
"JavaScript runtime exited unexpectedly"
could someone help me here?
Let me know if you need any additional information
function fetchTables() {
var timezone = "GMT+" + new Date().getTimezoneOffset()/60;
var date = Utilities.formatDate(new Date(), timezone, "yyyy-MM-dd HH:mm");
Logger.log(date);
var sheet = SpreadsheetApp.getActive().getSheetByName('Tables');
var value = sheet.getRange('A1').getValue();
var projectId = 'corpbi-dev';
var request = {
query: 'select table_id from [corpbi-dev:' + value + '.__TABLES__]'
};
var queryResults = BigQuery.Jobs.query(request, projectId);
var jobId = queryResults.jobReference.jobId;
var rows = queryResults.rows;
if (rows) {
// Append the results.
var data = new Array(rows.length);
for (var i = 0; i < rows.length; i++) {
var cols = rows[i].f;
data[i] = new Array(cols.length);
for (var j = 0; j < cols.length; j++) {
data[i][j] = cols[j].v;
}
}
}
var queries = [];
var totalbytes = [];
var timelapsed = [];
var rowcount = [];
var jobcode = [];
var finalSheet = SpreadsheetApp.getActive().getSheetByName('Final Metrics');
for(var i=1; i<=data.length; i++) {
var sql = "SELECT stage_loading_query FROM (SELECT stage_loading_query, job_start_time FROM [corpbi-dev:etl_log.job_details] WHERE target_table LIKE '%"+ value + "." + data[i-1]+"%' " +
"GROUP BY 1, 2 ORDER BY 2 desc) LIMIT 1"
var request1 = {
query: sql
};
var queryResults1 = BigQuery.Jobs.query(request1, projectId);
var sql1 = queryResults1.rows;
//Logger.log(sql1);
// break;
if (sql1) {
// Append the results.
var data1 = new Array(sql1.length);
for (var k = 0; k < sql1.length; k++) {
var cols = sql1[k].f;
data1[k] = new Array(cols.length);
for (var j = 0; j < cols.length; j++) {
data1[k][j] = cols[j].v;
}
}
}
queries.push(data1);
}
//Logger.log(queries.length);
finalSheet.getRange(2, 1, queries.length).setValues(queries);
// queries = finalSheet.getRange(2, 1, finalSheet.getLastRow()-1).getValues();
var endtime = (new Date()).getTime();
Logger.log(endtime);
for(var i=1; i<=queries.length; i++) {
var sqlstmt = queries[i-1];
try{
var request2 = {
query: sqlstmt,
useLegacySql: true
};
var sleepTimeMs = 50000;
var queryResults2 = BigQuery.Jobs.query(request2, projectId);
var jobId1 = queryResults2.jobReference.jobId;
while (!queryResults2.jobComplete) {
Utilities.sleep(sleepTimeMs);
sleepTimeMs *= 2;
queryResults2 = BigQuery.Jobs.getQueryResults(projectId, jobId1);
//continue;
}
var queryDetails = BigQuery.Jobs.get(projectId, jobId1);
totalbytes.push(queryDetails.statistics.totalBytesProcessed);
timelapsed.push(queryDetails.statistics.totalSlotMs);
rowcount.push(queryResults2.totalRows);
}
catch(e){
try{
var request2 = {
query: sqlstmt,
useLegacySql: false
};
var sleepTimeMs = 50000;
var queryResults2 = BigQuery.Jobs.query(request2, projectId);
var jobId1 = queryResults2.jobReference.jobId;
while(!queryResults2.jobComplete) {
Utilities.sleep(sleepTimeMs);
sleepTimeMs *= 2;
queryResults2 = BigQuery.Jobs.getQueryResults(projectId, jobId1);
// continue;
}
var queryDetails = BigQuery.Jobs.get(projectId, jobId1);
totalbytes.push(queryDetails.statistics.totalBytesProcessed);
timelapsed.push(queryDetails.statistics.totalSlotMs);
rowcount.push(queryResults2.totalRows);
}
catch(e){
Logger.log(e);
}
Logger.log(e);
}
finalSheet.getRange(i+1, 2,).setValue((totalbytes[i-1]/1048576).toFixed(2) + 'MB');
finalSheet.getRange(i+1, 3,).setValue((timelapsed[i-1]/1000).toFixed(2) + 's');
finalSheet.getRange(i+1, 4,).setValue((rowcount[i-1]));
}
}
The V8 Runtime for Google Apps Script is known to be on Alpha stage, which means you may encounter some bugs/errors.
In order to use the stable GAS version, you only need to change the runtimeVersion value in your script's manifest from V8 to STABLE.
I'm using a Google Script to pull information about Trello cards into a Google Sheet. It was working fine for me, but suddenly today all the cards are pulling in 'Undefined' for each piece of data. But I can't work out why this suddenly stopped working.
The Google Script is as follows:
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [ {name: "Update from Trello", functionName: "main"}];
ss.addMenu("Trello", menuEntries);
}
// trello variables
var api_key = "XXXXX";
var api_token = "XXXXX";
var board_id = "XXXXX";
var url = "https://api.trello.com/1/";
var key_and_token = "key=" + api_key + "&token=" + api_token;
//called by google docs apps
function main() {
var ss = SpreadsheetApp.getActiveSheet().clear();
ss.appendRow(["Date", "Task", "Who", "List", "Link"]);
var response = UrlFetchApp.fetch(url + "boards/" + board_id + "/lists/all/?" + key_and_token);
var lists = JSON.parse((response.getContentText()));
Logger.log(lists);
for (var i = 0; i < lists.length; i++) {
var list = lists[i];
var response = UrlFetchApp.fetch(url + "list/" + list.id + "/cards/all?" + key_and_token);
var cards = JSON.parse(response.getContentText());
if (!cards)
continue;
for (var j = 0; j < cards.length; j++) {
var card = cards[j];
Logger.log(cards);
var response = UrlFetchApp.fetch(url + "cards/" + card.id + "/actions/?" + key_and_token);
var carddetails = JSON.parse(response.getContentText());
if (!carddetails)
continue;
Logger.log(carddetails);
for (var k = 0; k < carddetails.length; k++) {
var dato = carddetails[k].date;
var fullname = carddetails[k].memberCreator.fullName;
var name = card.name;
var link = card.url;
var listname = list.name;
Logger.log(name);
Logger.log(dato);
Logger.log(fullname);
Logger.log(link);
Logger.log(listname);
}
ss.appendRow([dato, name, fullname, listname, link]);
}
}
}
One year after that question i was searching for this code then i realise the Trello Api don't respond with the same way when this code was created. So i fix it...
Here is the code that work for me
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [ {name: "Update from Trello", functionName: "main"},];
ss.addMenu("Trello", menuEntries);
}
// trello variables
var api_key = "XXXXX";
var api_token = "XXXXX";
var board_id = "XXXXX";
var url = "https://api.trello.com/1/";
var key_and_token = "key="+api_key+"&token="+api_token;
//called by google docs apps
function main() {
var ss = SpreadsheetApp.getActiveSheet().clear();
ss.appendRow(["Date", "Task", "Who", "List", "Link"]);
var response = UrlFetchApp.fetch(url + "boards/" + board_id + "/lists?cards=all&" + key_and_token);
var lists = JSON.parse((response.getContentText()));
Logger.log(lists);
for (var i=0; i < lists.length; i++) {
var list = lists[i];
//if(!list.closed) continue; //ignore open
//Logger.log(list);
var response = UrlFetchApp.fetch(url + "list/" + list.id + "/cards?" + key_and_token);
var cards = JSON.parse(response.getContentText());
if(!cards) continue;
for (var j=0; j < cards.length; j++) {
var card = cards[j];
Logger.log(url + "cards/" + card.id + "/actions?" + key_and_token);
var response = UrlFetchApp.fetch(url + "cards/" + card.id + "/?actions=all&" + key_and_token);
var carddetails = JSON.parse(response.getContentText()).actions;
if(!carddetails) continue;
Logger.log(carddetails);
for (var k=0; k < carddetails.length; k++) {
var dato = carddetails[k].date;
var fullname = carddetails[k].memberCreator.fullName;
var name = card.name;
var link = card.url;
var listname = list.name;
//var labelname = carddetails[k].labeldetails.name;
Logger.log(name);
Logger.log(dato);
Logger.log(fullname);
Logger.log(link);
//Logger.log(labelname);
Logger.log(listname);
}
ss.appendRow([dato, name, fullname, listname, link]);
}
}
}
Can I ask you for advice. I have a Google script that does this:
1) check whether there is any conversation marked by an asterisk
2) if so, deselect it, and then forward this conversation to that address
It works well, but I need to easily pimp. Rather than forward, I need to send the message to the address, which would be the subject of a report and found the body of a message by message body was found under the link to the thread found messages and the icing on the cake would have been references to attachments in the message.
function TJ() {
var threads = GmailApp.search('is:starred');
for (var h = 0; h < threads.length; h++) {
var messages = threads[h].getMessages();
for (var i = 0; i < messages.length; i++) {
if (messages[i].isStarred())
{
Logger.log(messages[i].getSubject());
messages[i].unstar();
messages[i].forward("--email-address--", {
cc: "",
bcc: ""
});
}
}
}
}
THX!
This is perfect!
function AddSM2GTDApp() {
var threads = GmailApp.search('is:starred');
for (var h = 0; h < threads.length; h++) {
var messages = threads[h].getMessages();
for (var i = 0; i < messages.length; i++) {
if (messages[i].isStarred())
{
Logger.log(messages[i].getSubject());
var subject = messages[i].getSubject();
Logger.log(messages[i].getBody());
var body = messages[i].getBody();
Logger.log(messages[i].getId());
var id = messages[i].getId();
var label = GmailApp.getUserLabelByName("Add2GTDApp");
threads[h].addLabel(label);
messages[i].unstar();
MailApp.sendEmail({
to: "your#email.com",
subject: subject,
htmlBody: "https://mail.google.com/mail/u/0/#inbox/"+id+"<br>--------------------------------------------------------------------------------------<br>"+body+"<br>--------------------------------------------------------------------------------------<br>Mail to Nirvana Script ",
});
}
}
}
}
Please try the below code , You can add 5 mins time driven event trigger to run the script
function MailForward() {
try{
var glabel = createLabel_("Mail-Forwarded");
var rtm_email = 'abc#abc.com';
var from_email = Session.getActiveUser().getEmail();
var threads = GmailApp.search('in:inbox is:unread newer_than:1d');
var mForward = 0;
for (var i=0;i<threads.length;i++) {
var messages=threads[i].getMessages();
for (var m = 0; m < messages.length; m++){
if (messages[m].isUnread()){
mForward = 0;
var mlabels = threads[i].getLabels();
for (var j = 0; j < mlabels.length; j++) {
Logger.log(mlabels[j].getName());
if (mlabels[j].getName() === "Mail-Forwarded") {
mForward = 1;
}
}
if (mForward===0) {
// Logger.log(messages.length)
// Logger.log(messages[m].getFrom());
var from = messages[m].getFrom();
//Logger.log(messages[m].getDate());
var date = messages[m].getDate();
// Logger.log(messages[m].getSubject());
var subject = messages[m].getSubject();
// Logger.log(messages[m].getTo());
var to = messages[m].getTo();
var body = messages[m].getBody();
var attachment = messages[m].getAttachments();
var emailoptions = ("---------- Forwarded message ----------" +'<br>'+'From: '+from+ "<'" + from.replace(/^.+<([^>]+)>$/, "$1") +"'>"+'<br>'+ 'Date: '+date+'<br>'+ 'Subject: ' +subject+'<br>'+
'To: ' +to+ "<'" + to.replace(/^.+<([^>]+)>$/, "$1") +"'>"+'<br>'+'<br>'+'<br>');
messages[m].forward(rtm_email,{htmlBody: emailoptions + body , Attachment: attachment});
glabel.addToThread(threads[i]);
Logger.log(glabel.getName());
messages[m].markRead();
mForward = 1;
}
}
}
}
} catch(e) {
MailApp.sendEmail("abc#abc.com", "Exception found in Sript", e );
Logger.log(e);
}
}
function autoForwardZoom() {
var s = "";
var m = "";
var c = 0;
var a = "";
var f = "";
var label = 'IT/Zoom';
var subject = 'Disconnected';
var from = 'no-reply#domain.us';
var threads = GmailApp.search("from:" + from + " label:" + label + " is:unread subject:(" + subject + ")", 0, 1);
for (var i = 0; i < threads.length; i++) {
var message = threads[i].getMessages();
c = threads[i].getMessageCount() - 1;
m = threads[i].getMessages()[c];
b = m.getBody();
s = m.getSubject();
a = m.getAttachments();
var returnData = [];
var html = HtmlService.createTemplateFromFile('Temp');
html.data = returnData;
var template = html.evaluate().getContent();
m.forward("youremail#gmail.com", {
replyTo: "myemail#gmail.com",
subject: s,
htmlBody: template + "<br>" + b,
attachments: a
});
GmailApp.markThreadsRead(threads);
}
}
My HTML Template,
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div>Dear Team</div>
<div> </div>
<div>Please kindly check zoom controller issue</div>
<div> </div>
<div>Regards</div>
<div><i>please reply this email with word "SOLVED" to earn credits, once you has solved this issue</i></div>
<div> </div>
<div style='text-align: center;'>---------- Forwarded message from Zoom ----------</div>
</body>
</html>