Function not executing with defined variables - javascript

The gist of the project is: I have Google Form answers that get populated on a Google doc, let's call this doc the template. The template is copied so I never overwrite the original. That copy is converted to PDF, sent to email, and moved to a specific folder on my Drive. This function happens flawlessly with every Form submission and gets triggered on submit. My next function is supposed to send that copied doc to my Google Cloud Print, but I'm having trouble writing the code for that. I have it to the point where it will print the doc on Form submit, but I have to specifically define the doc's ID. Unfortunately the ID is not static since a new doc is made with every submission. Here's my full code minus any sensitive information:
// Work Order
// Get template from Google Docs and name it
var docTemplate = ""; // *** replace with your template ID ***
var docName = "Work Order";
function addDates() {
var date = new Date(); // your form date
var holiday = ["09/04/2017", "10/09/2017", "11/23/2017", "12/24/2017", "12/25/2017", "01/01/2018"]; //Define holiday dates in MM/dd/yyyy
var days = 5; //No of days you want to add
date.setDate(date.getDate());
var counter = 0;
if (days > 0) {
while (counter < days) {
date.setDate(date.getDate() + 1);
var check = date.getDay();
var holidayCheck = holiday.indexOf(Utilities.formatDate(date, "EDT", "MM/dd/yyyy"));
if (check != 0 && check != 6 && holidayCheck == -1) {
counter++;
}
}
}
Logger.log(date) //for this example will give 08/16/2017
return date;
}
function createNewDoc(values) {
//Get information from form and set as variables
var email_address = "";
var job_name = values[1];
var ship_to = values[11];
var address = values[12];
var order_count = values[7];
var program = values[2];
var workspace = values[3];
var offer = values[4];
var sort_1 = values[5];
var sort_2 = values[6];
var image_services = values[9];
var print_services = values[10];
var priority = values[13];
var notes = values[14];
var formattedDate = Utilities.formatDate(new Date(), "EDT", "MM/dd/yyyy");
var expirationDate = Utilities.formatDate(addDates(), "EDT", "MM/dd/yyyy");
// Get document template, copy it as a new temp doc, and save the Doc's id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName + ' for ' + job_name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document's body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyJobName', job_name);
copyBody.replaceText('keyShipTo', ship_to);
copyBody.replaceText('keyAddress', address);
copyBody.replaceText('keyOrderCount', order_count);
copyBody.replaceText('keyProgram', program);
copyBody.replaceText('keyWorkspace', workspace);
copyBody.replaceText('keyOffer', offer);
copyBody.replaceText('keySort1', sort_1);
copyBody.replaceText('keySort2', sort_2);
copyBody.replaceText('keyImageServices', image_services);
copyBody.replaceText('keyPrintServices', print_services);
copyBody.replaceText('keyPriority', priority);
copyBody.replaceText('keyNotes', notes);
copyBody.replaceText('keyDate', formattedDate);
copyBody.replaceText('keyDue', expirationDate);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "New Job Submission";
var body = "Here is the work order for " + job_name + "";
MailApp.sendEmail(email_address, subject, body, {
htmlBody: body,
attachments: pdf
});
// Move file to folder
var file = DriveApp.getFileById(copyId);
DriveApp.getFolderById("").addFile(file);
file.getParents().next().removeFile(file);
}
function printGoogleDocument(copyId, docName) {
// For notes on ticket options see https://developers.google.com/cloud-print/docs/cdd?hl=en
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR"
},
duplex: {
type: "NO_DUPLEX"
},
}
};
var payload = {
"printerid": "",
"content": copyId,
"title": docName,
"contentType": "google.kix", // allows you to print google docs
"ticket": JSON.stringify(ticket),
};
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
method: "POST",
payload: payload,
headers: {
Authorization: 'Bearer ' + GoogleCloudPrint.getCloudPrintService().getAccessToken()
},
"muteHttpExceptions": true
});
// If successful, should show a job here: https://www.google.com/cloudprint/#jobs
response = JSON.parse(response);
if (response.success) {
Logger.log("%s", response.message);
} else {
Logger.log("Error Code: %s %s", response.errorCode, response.message);
}
return response;
}
// When Form Gets submitted
function onFormSubmit(e) {
var values = e.values;
createNewDoc(values);
printGoogleDocument(copyId, docName);
}

Return the new document from the 'createNewDoc(values);' function by changing by adding this to the end of the createNewDoc() function, right before the closing bracket:
//Starting at the code here
// Move file to folder
var file = DriveApp.getFileById(copyId);
DriveApp.getFolderById("").addFile(file);
file.getParents().next().removeFile(file);
//Add this
var newDocName = docName + ' for ' + job_name;
return [file, newDocName];
//To this point
}
Then change the onFormSubmit() function as shown below:
// When Form Gets submitted
function onFormSubmit(e) {
var values = e.values;
var returnedDocValues = createNewDoc(values);
var file = returnedDocValues[0];
var docName= returnedDocValues[1];
printGoogleDocument(file, docName);
}
Let me know if there are errors as I have not tested this code myself.

Related

Send Message to LINE Notify from Google Spreadsheets with Apps Script

So I am trying to send message to LINE Notify from Google Spreadsheets via google form responses, I already testing the API with Postman and it works, I got the Notification, however it doesn't works on the Apps Script Code. here's the error log:
function autoFillPendataanKontak(e) {
var nama = e.values[1];
var nim = e.values[2];
var bidang = e.values[3];
var file = DriveApp.getFileById('------');
var doc = DocumentApp.openById(file.getId());
var body = doc.getBody();
function sendLineNotify(messageNama, messageBidang) {
var token = ["------"];
var options = {
"method": "post",
"payload": messageNama + " telah mendaftar di Bidang " + messageBidang,
"headers": {
"Authorization": "Bearer " + token
}
};
UrlFetchApp.fetch("https://notify-api.line.me/api/notify", options);
}
function appendTable(variabel1, variabel2){
var rangePSDI = null;
var searchElement = body.findElement(DocumentApp.ElementType.TABLE, rangePSDI);
element = searchElement.getElement();
table = element.asTable();
if (bidang == 'PSDI') {
body.replaceText('{{a}}', variabel1);
body.replaceText('{{b}}', variabel2);
var tr = table.appendTableRow();
var ukur = table.getNumRows();
ukur -= 3;
tr.appendTableCell(ukur+1);
tr.appendTableCell("{{a}}");
tr.appendTableCell("{{b}}");
} else if (bidang == 'PSDM') {
body.replaceText('{{c}}', variabel1);
body.replaceText('{{d}}', variabel2);
var tr = table.appendTableRow();
var ukur = table.getNumRows();
ukur -= 3;
tr.appendTableCell(ukur + 1);
tr.appendTableCell("{{c}}");
tr.appendTableCell("{{d}}");
}
}
appendTable(nama, nim);
sendLineNotify(nama, bidang);
doc.saveAndClose();
}
Solved the problem, I just forgot the "message=" on payload
"payload": "message=" + messageNama + " telah mendaftar di Bidang " + messageBidang,

How to filter by file path in Google apps script

I am trying to have the following script filter by file path. Ideally this should only show results from the folder marked 'GUEST' in my drive. Right now it shows those and anything else with the shared folder ID of this root (I do not want to use the GUEST folder ID because I will later use this to filter other users accessing my drive).
My google drive file path is as follows Root/GUEST
CODE UPDATED WITH ANSWER FROM COMMENTS:
var folderId = "MyID"; // <--- Your shared folder ID
function doGet() {
var t = HtmlService.createTemplateFromFile('index');
t.data = getFileList();
return t.evaluate() .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);;
}
function getparams(e) {
return zipping(typeof(e.fileId) == "string" ? [e.fileId] : e.fileId);
}
function getFileList() {
var folderlist = (function(folder, folderSt, results) {
var ar = [];
var folders = folder.getFoldersByName("GUEST");
while (folders.hasNext()) ar.push(folders.next());
folderSt += folder.getId() + "#_aabbccddee_#";
var array_folderSt = folderSt.split("#_aabbccddee_#");
array_folderSt.pop()
results.push(array_folderSt);
ar.length == 0 && (folderSt = "");
for (var i in ar) arguments.callee(ar[i], folderSt, results);
return results;
})(DriveApp.getFoldersByName("GUEST").next(), "", []);
var localTimeZone = Session.getScriptTimeZone();
var filelist = [];
var temp = {};
for (var i in folderlist) {
var folderid = folderlist[i][folderlist[i].length - 1];
var folder = DriveApp.getFoldersByName("GUEST");
var files = folder.next().getFiles();
while (files.hasNext()) {
var file = files.next();
temp = {
folder_tree: function(folderlist, i) {
if (i > 0) {
return "/" + [DriveApp.getFolderById(folderlist[i][j]).getName() for (j in folderlist[i])
if (j > 0)].join("/") + "/";
} else {
return "/";
}
}(folderlist, i),
file_id: file.getId(),
file_name: file.getName(),
file_size: file.getBlob().getBytes().length,
file_created: Utilities.formatDate(file.getDateCreated(), localTimeZone, "yyyy/MM/dd HH:mm:ss"),
file_updated: Utilities.formatDate(file.getLastUpdated(), localTimeZone, "yyyy/MM/dd HH:mm:ss"),
};
filelist.push(temp);
temp = {}
}
}
var sortedlist = filelist.sort(function(e1, e2) {
return (e1.folder_tree > e2.folder_tree ? 1 : -1) });
return sortedlist;
}
function zipping(fileId) {
var blobs = [];
var mimeInf = [];
fileId.forEach(function(e) {
try {
var file = DriveApp.getFileById(e);
var mime = file.getMimeType();
var name = file.getName();
} catch (e) {
return e
}
Logger.log(mime)
var blob;
if (mime.indexOf('google-apps') > 0) {
mimeInf =
mime == "application/vnd.google-apps.spreadsheet" ? ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", name + ".xlsx"] : mime == "application/vnd.google-apps.document" ? ["application/vnd.openxmlformats-officedocument.wordprocessingml.document", name + ".docx"] : mime == "application/vnd.google-apps.presentation" ? ["application/vnd.openxmlformats-officedocument.presentationml.presentation", name + ".pptx"] : ["application/pdf", name + ".pdf"];
blob = UrlFetchApp.fetch("https://www.googleapis.com/drive/v3/files/" + e + "/export?mimeType=" + mimeInf[0], {
method: "GET",
headers: { "Authorization": "Bearer " + ScriptApp.getOAuthToken() },
muteHttpExceptions: true
}).getBlob().setName(mimeInf[1]);
} else {
blob = UrlFetchApp.fetch("https://www.googleapis.com/drive/v3/files/" + e + "?alt=media", {
method: "GET",
headers: { "Authorization": "Bearer " + ScriptApp.getOAuthToken() },
muteHttpExceptions: true
}).getBlob().setName(name);
}
blobs.push(blob);
});
var zip = Utilities.zip(blobs, Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyyMMdd_HHmmss") + '.zip');
var bytedat = DriveApp.createFile(zip).getBlob().getBytes();
return Utilities.base64Encode(bytedat);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
function postLogin(event) {
var form = document.getElementById("myForm");
form.submit();
event.preventDefault();
}
</script>
<a href="" onClick="postLogin(event);" >Click!</a>
<form id="myForm" action="MYEXECLINK" target="my_iframe"></form>
<iframe id="my_iframe"name="my_iframe" style= "width: 500px; height: 50%;" frameBorder="0" style="overflow:hidden"></iframe>
I tried to use an if statement at line 61, but it could not pull the variables for some reason (I think I'm not setting up my variables correctly):
if (filelist(folder_tree == "/GUEST/"){
return sortedlist;}
else
{return null}
Does anyone know how to make this script filter by folder_tree? Hopefully by comparing it to a var (like user=guest)?
To clarify, here is the current result:
And this is the expected output:
Thanks for any help, I'll post updates as I work on it to clarify.
You want to retrieve a file list under the specific folder.
Subfolders in the specific folder are not required to be retrieved.
You want to achieve this using Google Apps Script.
I could understand like above. If my understanding is correct, how about this modification? I think that your updated script works. But I thought that your script might be able to be modified more simple. So how about the following modification?
Modification point:
In this modification, getFileList() was modified.
In your script, at first, the folder tree is retrieved. Then, the files in all folders are retrieved. But in your situation, the folder tree is not required to be retrieved. By this, your script can be modified more simple.
At first, "FileIterator" are retrieved with DriveApp.getFoldersByName("GUEST").next().getFiles(). Then, the values are retrieved from "FileIterator".
Modified script:
function getFileList() {
var folderName = "GUEST";
var files = DriveApp.getFoldersByName(folderName).next().getFiles();
var localTimeZone = Session.getScriptTimeZone();
var filelist = [];
while (files.hasNext()) {
var file = files.next();
var temp = {
file_id: file.getId(),
file_name: file.getName(),
file_size: file.getBlob().getBytes().length,
file_created: Utilities.formatDate(file.getDateCreated(), localTimeZone, "yyyy/MM/dd HH:mm:ss"),
file_updated: Utilities.formatDate(file.getLastUpdated(), localTimeZone, "yyyy/MM/dd HH:mm:ss"),
};
filelist.push(temp);
}
return filelist;
}
References:
getFoldersByName(name)
getFiles()
Class FileIterator

Merging two functions and executing in sequence

I'm having a few problems with this, so I'll try to keep it simple. What's happening in the first script is a new Google doc file gets made from a copy of a "master" doc I've defined, which gets its data populated from Form submissions, and that new copy is ultimately moved to a Folder on my Drive. The second script is supposed to send that copied file to the Google Cloud Print. The first script works perfect; I have it triggered on a form submit. The second script works by itself, but only when I explicitly define the master doc ID in the "content" section. Because with each Form submission a new doc gets made, I was having trouble integrating the new doc's ID with the second script. Right now, I tried pulling from the var file, but that's not working. I might have a syntax issue.
My other problem is I need to merge my second script with the first, in a way that gets triggered on the same Form Submit and probably execute after the PDF creation and Email send, but before it gets moved to the folder.
Any help or advice would be greatly appreciated.
And I've removed some of my IDs and sensitive information where you only see double quotes.
// Work Order
// Get template from Google Docs and name it
var docTemplate = ""; // *** replace with your template ID ***
var docName = "Work Order";
function addDates() {
var date = new Date(); // your form date
var holiday = ["09/04/2017", "10/09/2017", "11/23/2017", "12/24/2017", "12/25/2017", "01/01/2018"]; //Define holiday dates in MM/dd/yyyy
var days = 5; //No of days you want to add
date.setDate(date.getDate());
var counter = 0;
if (days > 0) {
while (counter < days) {
date.setDate(date.getDate() + 1);
var check = date.getDay();
var holidayCheck = holiday.indexOf(Utilities.formatDate(date, "EDT", "MM/dd/yyyy"));
if (check != 0 && check != 6 && holidayCheck == -1) {
counter++;
}
}
}
Logger.log(date) //for this example will give 08/16/2017
return date;
}
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from form and set as variables
var email_address = "";
var job_name = e.values[1];
var ship_to = e.values[11];
var address = e.values[12];
var order_count = e.values[7];
var program = e.values[2];
var workspace = e.values[3];
var offer = e.values[4];
var sort_1 = e.values[5];
var sort_2 = e.values[6];
var image_services = e.values[9];
var print_services = e.values[10];
var priority = e.values[13];
var notes = e.values[14];
var formattedDate = Utilities.formatDate(new Date(), "EDT", "MM/dd/yyyy");
var expirationDate = Utilities.formatDate(addDates(), "EDT", "MM/dd/yyyy");
// Get document template, copy it as a new temp doc, and save the Doc's id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName + ' for ' + job_name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document's body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyJobName', job_name);
copyBody.replaceText('keyShipTo', ship_to);
copyBody.replaceText('keyAddress', address);
copyBody.replaceText('keyOrderCount', order_count);
copyBody.replaceText('keyProgram', program);
copyBody.replaceText('keyWorkspace', workspace);
copyBody.replaceText('keyOffer', offer);
copyBody.replaceText('keySort1', sort_1);
copyBody.replaceText('keySort2', sort_2);
copyBody.replaceText('keyImageServices', image_services);
copyBody.replaceText('keyPrintServices', print_services);
copyBody.replaceText('keyPriority', priority);
copyBody.replaceText('keyNotes', notes);
copyBody.replaceText('keyDate', formattedDate);
copyBody.replaceText('keyDue', expirationDate);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "New Job Submission";
var body = "Here is the work order for " + job_name + "";
MailApp.sendEmail(email_address, subject, body, {
htmlBody: body,
attachments: pdf
});
// Move file to folder
var file = DriveApp.getFileById(copyId);
DriveApp.getFolderById("").addFile(file);
file.getParents().next().removeFile(file);
}
function printGoogleDocument(file, docName) {
// For notes on ticket options see https://developers.google.com/cloud-print/docs/cdd?hl=en
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR"
},
duplex: {
type: "NO_DUPLEX"
},
}
};
var payload = {
"printerid": "",
"content": file,
"title": docName,
"contentType": "google.kix", // allows you to print google docs
"ticket": JSON.stringify(ticket),
};
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
method: "POST",
payload: payload,
headers: {
Authorization: 'Bearer ' + GoogleCloudPrint.getCloudPrintService().getAccessToken()
},
"muteHttpExceptions": true
});
// If successful, should show a job here: https://www.google.com/cloudprint/#jobs
response = JSON.parse(response);
if (response.success) {
Logger.log("%s", response.message);
} else {
Logger.log("Error Code: %s %s", response.errorCode, response.message);
}
return response;
}
**
Update 8/14 with Sandy Good's suggestion:
**
I've attempted to do what you suggested, but now it's not creating the doc or sending to the cloud print. Any thoughts?
// Work Order
// Get template from Google Docs and name it
var docTemplate = ""; // *** replace with your template ID ***
var docName = "Work Order";
function addDates() {
var date = new Date(); // your form date
var holiday = ["09/04/2017", "10/09/2017", "11/23/2017", "12/24/2017", "12/25/2017", "01/01/2018"]; //Define holiday dates in MM/dd/yyyy
var days = 5; //No of days you want to add
date.setDate(date.getDate());
var counter = 0;
if (days > 0) {
while (counter < days) {
date.setDate(date.getDate() + 1);
var check = date.getDay();
var holidayCheck = holiday.indexOf(Utilities.formatDate(date, "EDT", "MM/dd/yyyy"));
if (check != 0 && check != 6 && holidayCheck == -1) {
counter++;
}
}
}
Logger.log(date) //for this example will give 08/16/2017
return date;
}
function createNewDoc(values) {
var email_address = "";
var job_name = e.values[1];
var ship_to = e.values[11];
var address = e.values[12];
var order_count = e.values[7];
var program = e.values[2];
var workspace = e.values[3];
var offer = e.values[4];
var sort_1 = e.values[5];
var sort_2 = e.values[6];
var image_services = e.values[9];
var print_services = e.values[10];
var priority = e.values[13];
var notes = e.values[14];
var formattedDate = Utilities.formatDate(new Date(), "EDT", "MM/dd/yyyy");
var expirationDate = Utilities.formatDate(addDates(), "EDT", "MM/dd/yyyy");
// Get document template, copy it as a new temp doc, and save the Doc's id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName + ' for ' + job_name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document's body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyJobName', job_name);
copyBody.replaceText('keyShipTo', ship_to);
copyBody.replaceText('keyAddress', address);
copyBody.replaceText('keyOrderCount', order_count);
copyBody.replaceText('keyProgram', program);
copyBody.replaceText('keyWorkspace', workspace);
copyBody.replaceText('keyOffer', offer);
copyBody.replaceText('keySort1', sort_1);
copyBody.replaceText('keySort2', sort_2);
copyBody.replaceText('keyImageServices', image_services);
copyBody.replaceText('keyPrintServices', print_services);
copyBody.replaceText('keyPriority', priority);
copyBody.replaceText('keyNotes', notes);
copyBody.replaceText('keyDate', formattedDate);
copyBody.replaceText('keyDue', expirationDate);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "New Job Submission";
var body = "Here is the work order for " + job_name + "";
MailApp.sendEmail(email_address, subject, body, {
htmlBody: body,
attachments: pdf
});
// Move file to folder
var file = DriveApp.getFileById(copyId);
DriveApp.getFolderById("").addFile(file);
file.getParents().next().removeFile(file);
}
function printGoogleDocument(file, docName) {
// For notes on ticket options see https://developers.google.com/cloud-print/docs/cdd?hl=en
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR"
},
duplex: {
type: "NO_DUPLEX"
},
}
};
var payload = {
"printerid": "",
"content": file,
"title": docName,
"contentType": "google.kix", // allows you to print google docs
"ticket": JSON.stringify(ticket),
};
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
method: "POST",
payload: payload,
headers: {
Authorization: 'Bearer ' + GoogleCloudPrint.getCloudPrintService().getAccessToken()
},
"muteHttpExceptions": true
});
// If successful, should show a job here: https://www.google.com/cloudprint/#jobs
response = JSON.parse(response);
if (response.success) {
Logger.log("%s", response.message);
} else {
Logger.log("Error Code: %s %s", response.errorCode, response.message);
}
return response;
}
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from form and set as variables
var values = e.values;
createNewDoc(values);
printGoogleDocument(file, docName);
}
Not sure if that is what you are after, but the easiest way to execute functions consecutively is to pass a callback function as an argument to your function.
Here's the list of simple functions assigned to variables.
var addFive = function(number, callback){
number += 5;
if (callback) {
return callback(number);
}
return number;
}
var multiplyByFive = function(number, callback){
number *= 5;
if (callback) {
return callback(number);
}
return number;
}
var subtractFive = function(number, callback){
number -= 5;
if (callback) {
return callback(number);
}
return number;
}
You can then just chain call them like this.
function test() {
var result = addFive(7, function(number) {
return multiplyByFive(number, function(number){
return subtractFive(number);
});
});
Logger.log(result); //logs (7 + 5) * 5 - 5 = 55
}
Of course, if your functions only perform operations like creating files and don't return values, feel free to omit the 'return' statement.
I have more questions in regards to this project, but I think this specific question has been answered, so here's the final code for future reference.
// Work Order
// Get template from Google Docs and name it
var docTemplate = ""; // *** replace with your template ID ***
var docName = "Work Order";
function addDates() {
var date = new Date(); // your form date
var holiday = ["09/04/2017", "10/09/2017", "11/23/2017", "12/24/2017", "12/25/2017", "01/01/2018"]; //Define holiday dates in MM/dd/yyyy
var days = 5; //No of days you want to add
date.setDate(date.getDate());
var counter = 0;
if (days > 0) {
while (counter < days) {
date.setDate(date.getDate() + 1);
var check = date.getDay();
var holidayCheck = holiday.indexOf(Utilities.formatDate(date, "EDT", "MM/dd/yyyy"));
if (check != 0 && check != 6 && holidayCheck == -1) {
counter++;
}
}
}
Logger.log(date) //for this example will give 08/16/2017
return date;
}
function createNewDoc(values) {
//Get information from form and set as variables
var email_address = "";
var job_name = values[1];
var ship_to = values[11];
var address = values[12];
var order_count = values[7];
var program = values[2];
var workspace = values[3];
var offer = values[4];
var sort_1 = values[5];
var sort_2 = values[6];
var image_services = values[9];
var print_services = values[10];
var priority = values[13];
var notes = values[14];
var formattedDate = Utilities.formatDate(new Date(), "EDT", "MM/dd/yyyy");
var expirationDate = Utilities.formatDate(addDates(), "EDT", "MM/dd/yyyy");
// Get document template, copy it as a new temp doc, and save the Doc's id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName + ' for ' + job_name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document's body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyJobName', job_name);
copyBody.replaceText('keyShipTo', ship_to);
copyBody.replaceText('keyAddress', address);
copyBody.replaceText('keyOrderCount', order_count);
copyBody.replaceText('keyProgram', program);
copyBody.replaceText('keyWorkspace', workspace);
copyBody.replaceText('keyOffer', offer);
copyBody.replaceText('keySort1', sort_1);
copyBody.replaceText('keySort2', sort_2);
copyBody.replaceText('keyImageServices', image_services);
copyBody.replaceText('keyPrintServices', print_services);
copyBody.replaceText('keyPriority', priority);
copyBody.replaceText('keyNotes', notes);
copyBody.replaceText('keyDate', formattedDate);
copyBody.replaceText('keyDue', expirationDate);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "New Job Submission";
var body = "Here is the work order for " + job_name + "";
MailApp.sendEmail(email_address, subject, body, {
htmlBody: body,
attachments: pdf
});
// Move file to folder
var file = DriveApp.getFileById(copyId);
DriveApp.getFolderById("").addFile(file);
file.getParents().next().removeFile(file);
}
function printGoogleDocument(file, docName) {
// For notes on ticket options see https://developers.google.com/cloud-print/docs/cdd?hl=en
var ticket = {
version: "1.0",
print: {
color: {
type: "STANDARD_COLOR"
},
duplex: {
type: "NO_DUPLEX"
},
}
};
var payload = {
"printerid": "",
"content": file,
"title": docName,
"contentType": "google.kix", // allows you to print google docs
"ticket": JSON.stringify(ticket),
};
var response = UrlFetchApp.fetch('https://www.google.com/cloudprint/submit', {
method: "POST",
payload: payload,
headers: {
Authorization: 'Bearer ' + GoogleCloudPrint.getCloudPrintService().getAccessToken()
},
"muteHttpExceptions": true
});
// If successful, should show a job here: https://www.google.com/cloudprint/#jobs
response = JSON.parse(response);
if (response.success) {
Logger.log("%s", response.message);
} else {
Logger.log("Error Code: %s %s", response.errorCode, response.message);
}
return response;
}
// When Form Gets submitted
function onFormSubmit(e) {
var values = e.values;
createNewDoc(values);
printGoogleDocument(file, docName);
}

Send cross-domain HTTP-POST from google docs

I need to pass the POST request from the google docs by google scripts on the other site. The request must be transmitted whenever there is a change in the cell. The request shall contain the information from the different cells. I created the link but I can not send it.
function onEdit(e){
// Set a comment on the edited cell to indicate when it was changed.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = e.range;
// var to sent
var wait = 'wait'; // status
var approve = 'approve'; // status
var decline = 'decline'; // status
var amount = 990; // price
var sec = 'a1atugqv'; // ID to server
var vcode = sheet.getRange(range.getRow(), 9).getValue(); // ID clients` click
var orderID = sheet.getRange(range.getRow(), 2).getValue(); // ID order
// end
var listItem = e.value; // Value drop-down cell, wich edit
//var xhr = new XMLHttpRequest(); I tried using this transfer. It did not work
var url = 'http://example.com/common.php?vcode=' + vcode + '&amount=' + amount + '&order_id=' + orderID + '&sec=' + sec + '&status=';
if ((listItem == 'new') || (listItem == 'mobile off') || (listItem == 'send')){
var response = UrlFetchApp.fetch('http://www.example.com/'); // I tried using this transfer. It did not work
// i should send POST or GET here. With new status
//var site = url + wait;
//var resData = UrlFetchApp.fetch(site);
} else if ((listItem == 'approve') || (listItem == 'send') || (listItem == 'ok')){
// i should send POST or GET here. With new status
range.setNote('approve'); // check
//xhr.open('GET', url + approve, true);
// xhr.send();
} else if ((listItem == 'decline') || (listItem == 'return')){
range.setNote('decline');
//xhr.open('GET', url + decline, true);
// xhr.send();
}
}

Change the reply email address to the queue's email address in dynamic crm 2011

What i want to do is when we click on Reply button , the From address field will be populate with the email-id (default team's default queue's email-id). Current scenario is populated with logged in user.
I used the following js code onLoad, but I am getting an error that says "Object doesn't support property or method getAttributeValue
function CheckEnquiryReplyAddress() {
// Only complete this validate on Create Form
var formType = Xrm.Page.ui.getFormType();
var emailStatus = Xrm.Page.getAttributeValue("statecode").getValue();
var emailDirection = Xrm.Page.getAttributeValue("directioncode").getValue();
if (formType == 1 || (formType == 2 && emailStatus == "Open")) {
if (emailDirection == "1"){
var previousEmailId=getExtraqsParam("_InReplyToId", window.parent.location.search);
//getting context from the parent window
var context = Xrm.Page.context;
try {
var serverUrl = context.getServerUrl();
//The XRM OData end-point
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var query="/EmailSet?$select=ActivityId,ActivityTypeCode,DirectionCode,";
query=query+"ToRecipients,Email_QueueItem/QueueId&$expand=Email_QueueItem&$filter=ActivityId eq guid'" + previousEmailId +"'";
query =serverUrl+ODATA_ENDPOINT+ query;
var request= new XMLHttpRequest();
request.open("GET", query, false);
request.setRequestHeader("Accept", "application/json");
request.setRequestHeader("Content-Type", "application/json; charset=utf-8");
request.onreadystatechange=function(){ CompleteEnquiryReplyCheck(request,serverUrl);}
request.send(null);
}
catch(e) {
alert(e.Description);
}
}
}
}
function CompleteEnquiryReplyCheck(request,url)
{
if (request.readyState==4) {
if(request.status==200) {
var queue=JSON.parse(request.responseText).d.results[0];
if (queue != null) {
var queueId = queue.Email_QueueItem.results[0].QueueId.Id;
var lookup = new Array();
var lookupItem = new Object();
lookupItem.id = queueId;
lookupItem.name = queue.Email_QueueItem.results[0].QueueId.Name;
lookupItem.typename = "queue";
lookup[0] = lookupItem;
Xrm.Page.getAttribute("from").setValue(lookup);
}
}
}
}
The get attribute value method is incorrect, to get value of an attribute use the following:
var attributeValue = Xrm.Page.getAttribute("attributeName").getValue();
So, in your case it would be:
var emailStatus = Xrm.Page.getAttribute("statecode").getValue();
var emailDirection = Xrm.Page.getAttribute("directioncode").getValue();

Categories