Delete a newly created document? - google-apps-script

I am using a script to process a form as it is submitted. Part of it involves merging data from the form with a google doc and then emailing that doc as a pdf. Is there anyway to delete the doc once it has been sent?
If it helps, here is my script:
function onFormSubmit(e) {
//Get Form Values
var candID = parseInt(e.values[1]);
var emailAddress = e.values[2];
//Get Additional Settings
var ssMaster = SpreadsheetApp.openById("0AierVcXWELCudDY2Y3J2Z1hoX3pLOXYzTW1pOVF3Wmc");
var settings_sheet = ssMaster.getSheetByName("Settings");
var candCodeLength = settings_sheet.getRange("B20").getValue();
var candCodeChars = settings_sheet.getRange("B21").getValue();
var tempDocumentID = settings_sheet.getRange("B14").getValue();
var candInfoSheet = ssMaster.getSheetByName("Candidate Information");
var candInfoLastRow = candInfoSheet.getLastRow();
var candInfoArray = candInfoSheet.getRange(2,1,candInfoLastRow,7).getValues();
//Find Corresponding Row for Form Entry
for(var i=0; i<candInfoArray.length; i++) {
if (candInfoArray[i][3] === candID) {
var row = i+2;
}
}
var candIDRowNumber = row;
//Create & Record Candidate Code
do {
var candCode = createCandCode(candCodeLength, candCodeChars);
}
while(checkCandCode(candInfoArray, candCode) === true);
candInfoSheet.getRange(row,6,1,1).setValue(candCode);
candInfoSheet.getRange(row,7,1,1).setValue(emailAddress);
//Create PDF
var docid = DocsList.getFileById(tempDocumentID).makeCopy("Character Reference Instructions").getId();
var doc = DocumentApp.openById(docid);
Logger.log(candInfoArray);
Logger.log(row);
var firstName = candInfoArray[(row-2)][1];
var lastName = candInfoArray[(row-2)][0];
var body = doc.getActiveSection();
body.replaceText("<<first>>", firstName);
body.replaceText("<<last>>", lastName);
body.replaceText("<<code>>", candCode);
doc.saveAndClose();
//Send Email
var message = "You have successfully completed the NHS Registration form.\n\n Your Candidate Code (different from your Candidate ID) is \"" + candCode + "\" and should be given to your character reference so that they can fill out your character reference form.\n\n If you have any questions, please email Ann Perham at ann_perham#needham.k12.ma.us." ;
var subject = "NHS Registration Confirmation & Character Reference Instructions";
var advancedArgs = {name: "Ann Perham", replyTo: "ann_perham#needham.k12.ma.us", attachments: doc.getAs("application/pdf")};
MailApp.sendEmail(emailAddress, subject, message, advancedArgs);
}

You can use doc.setTrashed right at the end of your function while it is still the active document.

Related

Create new document from Google form and add to a new folder

I have a Google script triggered on submission of a form. It creates a new doc based on a template with certain variables in-filled from answers in the form.
I also have a folder created on the form submission.
The trouble I am having is creating the newly created doc within the newly created folder. Looking for some help merging the two scripts that work on their own to acheive this.
Creating a folder on form submission:
function createChannelFolder() {
var ss = SpreadsheetApp.getActive();
var names = ss.getSheetByName("Completed Certifications");
var ChannelName = names.getRange(names.getLastRow(), 2).getValue();
var parentFolder=DriveApp.getFolderById("FOLDERID");
return newFolder=parentFolder.createFolder(ChannelName);
}
Creating a document on form submission
function autoFillGoogleDocFromForm(e) {
//e.values is an array of form values
var Timestamp = e.values[0];
var Channel = e.values[1];
var Name = e.values[2];;
var file = DriveApp.getFileById('FILEID');
var folder = DriveApp.getFolderById('FOLDERID')
var copy = file.makeCopy(Channel + ',' + Name, folder);
var newId = copy.getId();
var doc = DocumentApp.openById(newId);
var body = doc.getBody();
body.replaceText('{{Timestamp}}', Timestamp);
body.replaceText('{{Channel}}', Channel);
body.replaceText('{{Name}}', Name);
doc.saveAndClose();
}
Explanation:
You need to call createChannelFolder() inside
autoFillGoogleDocFromForm(e).
just return the folder object within createChannelFolder():
return parentFolder.createFolder(ChannelName);
Solution:
Here is autoFillGoogleDocFromForm(e):
function autoFillGoogleDocFromForm(e) {
//e.values is an array of form values
var Timestamp = e.values[0];
var Channel = e.values[1];
var Name = e.values[2];;
var file = DriveApp.getFileById('FILEID');
var folder = createChannelFolder(); // 1st modification point
var copy = file.makeCopy(Channel + ',' + Name, folder);
var newId = copy.getId();
var doc = DocumentApp.openById(newId);
var body = doc.getBody();
body.replaceText('{{Timestamp}}', Timestamp);
body.replaceText('{{Channel}}', Channel);
body.replaceText('{{Name}}', Name);
doc.saveAndClose();
}
and here is createChannelFolder():
function createChannelFolder() {
var ss = SpreadsheetApp.getActive();
var names = ss.getSheetByName("Completed Certifications");
var ChannelName = names.getRange(names.getLastRow(), 2).getValue();
var parentFolder=DriveApp.getFolderById("FOLDERID");
return parentFolder.createFolder(ChannelName); // 2nd modification point
}

In Google sheets, I need a script to run on a form submit, but reference a separate sheet other than "form responses"

I am trying to get a script to look at a named sheet in the workbook when a form is submitted. I used this script for a while and now need to add some calculations to the data that gets submitted. I have the form response data going to a sheet to add some calculations, then gets put in a doc and emailed out. The email doc function works great, just can not got the script to look at the data on the "Output" sheet vs. the "Form_Responses" sheet.
This is the script as it has been, I have tried several things but no luck, always pulls from "Form_Responses". I removed my trial code for clarity.
Any thoughts?
Thanks!
My code :
var docTemplate = "1oeUqdaesyHM-WzUTFIlzHFzAqIm1DN4OiiGywgs622w"; // template ID
var docName = "Service Invoice";
function onFormSubmit(e) {
var email_address = "<>";
var email_address2 = "<>";
var job_number = e.values[1];
var date = e.values[2];
var tech_name = e.values[7];
var customer_name = e.values[3];
var customer_email = e.values[6];
var address = e.values[4];
var phone = e.values[5];
var work_description = e.values[9];
var project_manager = e.values[8];
var project_manager_email = "<>";
var known_issues = e.values[10];
var hours = e.values[11];
var labor_total = e.values[21];
var material_total = e.values[20];
var total = e.values[22];
var paid = e.values[15];
var type = e.values[16];
var check_num = e.values[17];
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName + ' for ' + job_number)
.getId();
var copyDoc = DocumentApp.openById(copyId);
var copyBody = copyDoc.getActiveSection();
copyBody.replaceText('keydate:', date);
copyBody.replaceText('keyjobnumber:', job_number);
copyBody.replaceText('keycustomername:', customer_name);
copyBody.replaceText('keyaddress:', address);
copyBody.replaceText('keyphonenumber:', phone);
copyBody.replaceText('keycustomeremailaddress:', customer_email);
copyBody.replaceText('keyemployeename:', tech_name);
copyBody.replaceText('keyworkdescription:', work_description);
copyBody.replaceText('keyprojectmanager:', project_manager);
copyBody.replaceText('keyfollowup:', known_issues);
copyBody.replaceText('keyhours:', hours);
copyBody.replaceText('keylabortotal:', labor_total);
copyBody.replaceText('keymaterialtotal:', material_total);
copyBody.replaceText('keytotal:', total);
copyBody.replaceText('keypaid:', paid);
copyBody.replaceText('keypaymenttype:', type);
copyBody.replaceText('keycheck:', check_num);
copyDoc.saveAndClose();
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
var subject = "ESCON Group Service Invoice";
var body = "Please find attached your invoice for the service work performed by ESCON Group.";
MailApp.sendEmail(customer_email, subject, body, {
htmlBody: body,
attachments: pdf
});
var subject = "ESCON Group Service Invoice" + job_number;
var body = "Here is the Service Invoice for: " + job_number + "";
MailApp.sendEmail(project_manager_email, subject, body, {
htmlBody: body,
attachments: pdf
});
var subject = "ESCON Group Service Invoice" + job_number;
var body = "Here is the Service Invoice for: " + job_number + " -Please contact Trevor Gross with any questions.";
MailApp.sendEmail(email_address, subject, body, {
htmlBody: body,
attachments: pdf
});
var subject = "ESCON Group Service Invoice" + job_number;
var body = "Here is the Service Invoice for " + job_number + "";
MailApp.sendEmail(email_address2, subject, body, {
htmlBody: body,
attachments: pdf
});
DriveApp.getFileById(copyId).setTrashed(true);
}
To get a value from a specific sheet, you need to get the spreadsheet (e.source), the sheet (getSheetByName()), the range (getRange()), and then the value (getValue()).
For example:
function onFormSubmit(e) {
var outputSheet = e.source.getSheetByName("Output");
var outputColumnA = outputSheet.getRange("A:A").getValues();
var outputA1 = outputColumnA[0][0];
console.log(outputA1);
}

Google form spreadsheet update script

I have some code for my form that works well for emailing the manager of an expense report for approval, as well as receiving a URL back with information needed to send the response back to the person who filled out the information on the form.
all i need it to do now is to update the field in the form with the proper approval message (accept or reject)
I think this will have to happen in the doGet method, but will I have to pass in more then just the row number and approval message to get this done? (e.g. getting the spreadsheet, getting the sheet, etc.)
here is what i have so far, both emails, and the URL generated appear to be correct:
function sendEmail(e){
/**
var email = e.values[1];
var item = e.values[2];
var cost = e.values[3];
*/
var serviceInformation = e.values[1];
var language = e.values[2];
var meetingType = e.values[3];
var eventDate = e.values[4];
var clientName = e.values[5];
var detailedDirections = e.values[6];
var onSitePOCName = e.values[7];
var onSitePOCNumber = e.values[8];
var department = e.values[9];
var contactPhoneNumber = e.values[10];
var approval = e.values[11]; //the one we need to modify
var requestorEmail = e.values[12];
var managerEmail = e.values[13];
var Language2 = e.values[14];
var interpreterName = e.values[15];
var interpreterAgency = e.values[16];
var dateConformationSent = e.values[17];
var specialNotes = e.values[18];
var row = e.range.getRow();
var url = 'https://script.google.com/a/macros/richmond.k12.va.us/s/AKfycbwuRr1boKTH0v1mprWmc7PE66_mQ_dmPE0lyWb7vkfiyW3pn31b/exec';
//add on the parameters to URL to send to the manager
var approve = url + '?approval=true'+'&reply='+requestorEmail+'&row='+row;
var reject = url + '?approval=false'+'&reply='+requestorEmail+'&row='+row;
var html = "<HTML><body>"+
"<h2>please review</h2><br />"
+"<P>" + language +" " + serviceInformation
+"<p>" + meetingType+ " on "+ eventDate + " for " +clientName
+"<p>" + "Location: "+ department
+"<p>" + "requester: "+ requestorEmail+ " "+
"<p>"+
"Approve<br />"+
"<p>"+
"Reject<br />"+
"</HTML></body>";
MailApp.sendEmail(managerEmail, "Approval Request", "what no html?", {htmlBody: html});
}
function doGet(e){
var params = JSON.stringify(e);
return HtmlService.createHtmlOutput(params);
//added in an edit
var id = '1UzlJ6Uw12H5dGVcLz7ONp3Neehq1DL21hqZnrMx7mxs';
var ss = SpreadsheetApp.openById(id);
var sheet = ss.getActiveSheet();
var column = 12;
var row = e.parameter.row;
var approval_cell = sheet.getRange(row, column);
Logger.log(row);
Logger.log(ss);
Logger.log(sheet);
Logger.log(approval_cell);
//logger logs the proper row. SS = Spreadsheet, sheet = sheet, approval_cell = Range
var aprovalResponce = (e.parameter.approval == 'true') ? 'Approved.' : 'Sorry, you need to reschedule';
//added values after aprovalResponce, in the email, they are both undefined.
var msg = "Your manager said : " + aprovalResponce;
var replyEmail = e.parameter.reply;
//MailApp.sendEmail(replyEmail, "Approval Request", msg);
//update the approval field
//changed in edit
if (e.parameter.approval == 'true') {
approval_cell.setValue("APPROVED"+;
} else {
approval_cell.setValue("DENIED");
}
//send the actual email out
MailApp.sendEmail(replyEmail, "Approval Request", msg);
}
It looks like you're trying to change the approval value in the spreadsheet? If so, I imagine this should work:
//update the approval field
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var column = 12;
var row = e.parameter.row;
var approval_cell = sheet.getRange(row, column);
if (e.parameter.approval == 'true') {
approval_cell.setValue("APPROVED");
} else {
approval_cell.setValue("DECLINED");
}

How can I keep the leading zero's in my pdf generated documents from google spreadsheet?

I have created a google test form and test form response. In the response spreadsheet, I have written below script to capture the inputted values from the from > generate a pdf/doc > email the pdf & > save a copy of the doc in a target folder. The issue I'm running into is that the section labeled as passcode could start with a "0" or multiple "0's", which I have formatted in the script for the spreadsheet. However when it generates the PDF/DOC, the zero's are removed. Is there any way to keep the leading 0's when converted in the PDF/DOC?
function formatNumber(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var cell = sheet.getRange("D2:D");
// Always show 4 digits
cell.setNumberFormat("0000");
}
var docTemplate = "11laarf0ThJ4mANX4KzHZCblVwRgphlf-bCblaUMl4oc";
var docName = "Test Form";
function onFormSubmit(e) {
var email_address = "jimmy111#gmail.com";
var Time_Stamp = e.namedValues["Timestamp"];
var full_name = e.namedValues["Name"];
var phone = e.namedValues["Phone Number"];
var passcode = e.namedValues["Passcode"];
var price = e.namedValues["Price"];
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(full_name+' '+docName)
.getId();
var copyDoc = DocumentApp.openById(copyId);
var copyBody = copyDoc.getActiveSection();
copyBody.replaceText('keyDate', Time_Stamp);
copyBody.replaceText('keyName', full_name);
copyBody.replaceText('keyPhone', phone);
copyBody.replaceText('keyCode', passcode);
copyBody.replaceText('keyPrice', price);
copyDoc.saveAndClose();
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
var subject = "CIR Testform for "+ full_name + "";
var body = "Here is the registration form for "+ full_name +"";
MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf});
var targetFolder = DocsList.getFolderById('0B-LfisIjjXtvLW82X3o1UzNyY1U');
var file = DocsList.getFileById(copyId);
file.addToFolder(targetFolder);
file.removeFromFolder(DocsList.getRootFolder());
}
function assignEditUrls() {
var form = FormApp.openById('16zVePLm61yRsSZMaoDI5MWIeB-vGHZGEoR9J7uJ0CP8');
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Form Responses 1');
var data = sheet.getDataRange().getValues();
var urlCol = 6; // column number where URL's should be populated; A = 1, B = 2 etc
var responses = form.getResponses();
var timestamps = [], urls = [], resultUrls = [];
for (var i = 0; i < responses.length; i++) {
timestamps.push(responses[i].getTimestamp().setMilliseconds(0));
urls.push(responses[i].getEditResponseUrl());
}
for (var j = 1; j < data.length; j++) {
resultUrls.push([data[j][0]?urls[timestamps.indexOf(data[j] [0].setMilliseconds(0))]:'']);
}
sheet.getRange(2, urlCol, resultUrls.length).setValues(resultUrls);
}
I've got a workaround to this issue, it's less than ideal but it's working.
Using the Pre-Filled form feature, enter a period in each response that requires the leading zero.
So if your user had entered "0123456", the recorded response will appear as "0.123456" you can then use substring to remove the first two charecters.
e.g.
var phone = e.namedValues["Phone Number"].substring(2);
This will then give you the leading zero. The only issue is accidental deletion of the period from the pre-filled form, although you can set a validation which checks for it, and then an error asking the user to enter it if they've removed it.
Not pretty, but we're up and running with that now at least.

Error when passing a blob file to send it as e-mail attachment

I'm trying to sending a file as e-mail attachment with Google Apps Script, following this rich answer. But instead of a stand alone app, I'm trying to do so within my spreadsheet, using a function like this:
function sendAttachment(){
var activeSheet = ss.getActiveSheet();
ScriptProperties.setProperty('emailRequest', 1);
if(!person_ID) {
person_ID = getCurrentRow();
//if the current line is the Column Headers line then ask the user to specify the ID, very rare case.
if (person_ID == 1) {
var person_ID = Browser.inputBox("Select one name.", "Click in one row:", Browser.Buttons.OK_CANCEL);
}
}
var app = UiApp.createApplication().setHeight(400).setWidth(600);
var panel = app.createVerticalPanel(); // you can embed that in a form panel
var label = app.createLabel("Choose the receiver").setStyleAttribute("fontSize", 18);
app.add(label);
var currentRow = ss.getActiveSelection().getRowIndex();
var personName = activeSheet.getRange(currentRow, 1).getValue();
var personNumber = activeSheet.getRange(currentRow, 5).getValue();
var item1Panel = app.createHorizontalPanel();
var txt = app.createTextBox().setId("item1").setName("item1").setValue(personName);
item1Panel.add(app.createLabel("Person:")).add(txt);
var item2Panel = app.createHorizontalPanel();
var txt = app.createTextBox().setId("item2").setName("item2").setValue(personNumber);
item2Panel.add(app.createLabel("Num:")).add(txt);
var sheet = SpreadsheetApp.openById(letterSpreadsheetId).getSheetByName("emailsDB");
var recipientEmailArray = sheet.getRange(2, 1, sheet.getLastRow(), sheet.getLastColumn()).getValues();
var item3Panel = app.createHorizontalPanel();
item3Panel.add(app.createLabel("Receiver"));
var listBox = app.createListBox().setName('item3');
for(var i = 0; i < (recipientEmailArray.length); i++){
listBox.addItem(recipientEmailArray[i][0] + ": " + recipientEmailArray[i][2]);
}
item3Panel.add(listBox);
var handlerBut = app.createServerHandler("butSendAttachment").addCallbackElement(panel);
var but = app.createButton("submit").setId("submitButton4").addClickHandler(handlerBut);
panel.add(item1Panel)
.add(item2Panel)
.add(item3Panel)
.add(app.createFileUpload().setName('thefile'))
.add(app.createLabel().setId("answer"))
.add(but);
var scroll = app.createScrollPanel().setPixelSize(600, 400).setTitle("My title 1");
scroll.add(panel);
app.add(scroll);
ss.show(app);
// var handlerBut = app.createServerHandler("butSendAttachment").addCallbackElement(panel);
// .add(app.createFileUpload().setName('thefile'));
// var form = app.createFormPanel();
// form.add(panel);
// app.add(form);
;
}
function butSendAttachment(e){
var recipientEmail = e.parameter.item3;
var fileBlob = e.parameter.thefile;
Logger.log("file blob = " + fileBlob);
recipientEmail = recipientEmail.split(':')[1];
var sheet = ss.getActiveSheet();
var person_ID = getCurrentRow();
var columns = getRowAsArray(sheet, 1);
var personData = getRowAsArray(sheet, person_ID);
var sender = actAuthor + " \n " + position;
var name = personData[0];
var motherName = personData[1];
var title = "my title";
var message = my mesage";
var confirm = Browser.msgBox('Send email','Are you sure?', Browser.Buttons.OK_CANCEL);
if(confirm=='ok'){
// MailApp.sendEmail(recipientEmail, title, message, {attachments: [fileBlob]});
MailApp.sendEmail(recipientEmail, title, message, {attachments: [fileBlob]});
var app = UiApp.createApplication().setHeight(150).setWidth(250);
var msg = "An email was sendo to " + recipientEmail;
app.setTitle("E-mail send!");
app.add(app.createVerticalPanel().add(app.createLabel(msg)));
var doc = SpreadsheetApp.getActive();
doc.show(app);
}
else {
return;
}
}
But I get this error: Execution failed: Invalid argument: inlineImages (line 77. Line 77 is this:
MailApp.sendEmail(recipientEmail, title, message, {attachments: [fileBlob]});
I've read the documentation I tried several argument variations. I conclude that fileBlob is Null. Why? How to fix it?
the fileUpload widget works only in a form parent widget and using a doGet/doPost structure.
That's written somewhere in the doc but right now I don't remember exactly where (I'look for it later)
But actually I guess you can build such a structure from within your spreadsheet, just change the names of your functions and use a formPanel as main widget. Don't forget also that you don't need a handler anymore and must use a submitButton widget.
EDIT : how silly I am ! its written in the first line in the widget's doc !!! ;-)