I'd appreciate if someone could cast an eye over my dodgey coding and give me some feedback.
The use / purpose of the sheet/script is to quality grade calls, emails and chats with customers. A form is filled out and then the script takes over.
We feed in a persons name, it grabs the last 9 forms for them. It sorts them in data order.
It then writes data to a blank scorecard, 0-3 Another identical sheet does a vlookup on these scores and changes the 0-3 scores into small traffic light icons.
The script then exports this sheet to a PDF, saves the PDF to a google drive folder (folder name is based on week commencing)
Finally if you have chosen to email the PDF too, it will email it.
This script produces one PDF at a time.
function getAgentName() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.getRangeByName('Header').clearContent();
ss.getRangeByName('Scores').clearContent();
ss.getRangeByName('Comments').clearContent();
var sheet = ss.getSheetByName("PDF Creator");
var range = sheet.getRange("A2")
var value = range.getValue();
if(value != 0){
getAgentData(value);
}
else
{
Browser.msgBox("You need to go to the sheet named PDF Creator and put an agent name in cell A2");
}
}
function getAgentData(value){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheet = ss.getSheetByName("Form responses 1")
var sourceRange = sourceSheet.getRange(2, 1, sourceSheet.getLastRow(), sourceSheet.getLastColumn());
var sourceValues = sourceRange.getValues();
sourceValues.sort(function(a,b) {
return b[0]-a[0]
});
var agentData = [];
var commentsData = [];
for(i=0;i<sourceValues.length;i++)
{
// Defines the data layout for PDF.
var agentName = sourceValues[i][2];
var dateTime = sourceValues[i][3];
var callType = sourceValues[i][7];
var opening = sourceValues[i][8];
var rootCause = sourceValues[i][9];
var rootFix = sourceValues[i][10];
var process = sourceValues[i][11];
var consumer = sourceValues[i][12];
var control = sourceValues[i][13];
var wrapup = sourceValues[i][14];
var dpa = sourceValues[i][15];
var score = sourceValues[i][22];
var comments = sourceValues[i][16];
var agentRow = [dateTime,callType,opening,rootCause,rootFix,process,consumer, control,wrapup,dpa,score];
var commentsRow = [dateTime,comments];
if(agentName == value && agentData.length < 9) {
agentData.push(agentRow)
commentsData.push(commentsRow)
}
}
agentData.sort(function(a,b) {
return b[0]-a[0]
});
commentsData.sort(function(a,b) {
return b[0]-a[0]
});
var destSheet = ss.getSheetByName("AgentPDF");
destSheet.getRange("A1").setValue(value + "'s Quality Score card");
var range = destSheet.getRange(6, 1, agentData.length, agentData[0].length);
range.setValues(agentData);
var commentRange = destSheet.getRange(18, 1, commentsData.length, commentsData[0].length);
commentRange.setValues(commentsData);
SpreadsheetApp.flush();
emailSpreadsheetAsPDF();
}
function emailSpreadsheetAsPDF() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("PDF Creator");
var now = new Date().toString();
var weekCommencing = sheet.getRange("C1").getValue();
var coachEmail = sheet.getRange("C4").getValue();
var coachName = sheet.getRange("A4").getValue();
var agentName = sheet.getRange("A2").getValue();
var agentEmail = sheet.getRange("C2").getValue();
var sendEmail = sheet.getRange("A6").getValue();
var subject = "Quality Scorecard for - "+agentName + " created on: "+now;
var url = ss.getUrl();
url = url.replace(/edit$/,'');
var monthNames = [
"Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct",
"Nov", "Dec"
];
var day = weekCommencing.getDate();
var monthIndex = weekCommencing.getMonth();
var year = weekCommencing.getFullYear();
var clean = day + ' ' + monthNames[monthIndex] + ' ' + year;
var bodyCoach = "Hello " + coachName + ". Please find attached "+ agentName+ "'s quality scorecard." +" Week commencing "+clean;
var bodyAgent = "Hello " + agentName + ". Please find attached your quality scorecard." +" Week commencing "+clean;
/* Specify PDF export parameters
// From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
exportFormat = pdf / csv / xls / xlsx
gridlines = true / false
printtitle = true (1) / false (0)
size = legal / letter/ A4
fzr (repeat frozen rows) = true / false
portrait = true (1) / false (0)
fitw (fit to page width) = true (1) / false (0)
add gid if to export a particular sheet - 0, 1, 2,..
*/
var url_ext = 'export?exportFormat=pdf&format=pdf' // export as pdf
+ '&size=a4' // paper size
+ '&portrait=1' // orientation, false for landscape
+ '&fitw=true&source=labnol' // fit to width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&gid=1809314965'; // the sheet's Id
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + url_ext , {
headers: {
'Authorization': 'Bearer ' + token
}
});
var file = response.getBlob().setName(agentName +"'s Quality Score Card Week Commencing: "+clean+ '.pdf');
writeFiles(file,clean);
if (coachEmail != "no email"){
GmailApp.sendEmail(coachEmail, subject, bodyCoach, {attachments:[file]});
}
if(sendEmail == "Yes"){
GmailApp.sendEmail(agentEmail, subject, bodyAgent, {attachments:[file]});
}
ss.getRangeByName('Header').clearContent();
ss.getRangeByName('Scores').clearContent();
ss.getRangeByName('Comments').clearContent();
ss.getRangeByName('AgentName').clearContent();
ss.getRangeByName('Coach').clearContent();
ss.getRangeByName('SendEmail').clearContent();
}
function writeFiles(file,clean) {
var rootFolder = DriveApp.getFolderById("ID HERE");
var subFolders = rootFolder.getFolders();
var testResult = false;
while(subFolders.hasNext()== true){
var folders = subFolders.next();
if(folders == clean) {
testResult = true;
}
}
if(testResult == false){
rootFolder.createFolder(clean);
}
var destFolder = rootFolder.getFoldersByName(clean).next();
if(destFolder.getFilesByName(file.getName()).hasNext() == false){
destFolder.createFile(file);
}
else
{
var warning = Browser.msgBox("Warning", "This PDF already exists. If you wish to overwrite this file, press OK to continue.", Browser.Buttons.OK_CANCEL);
if(warning == "ok"){
destFolder.getFilesByName(file.getName()).next().setTrashed(true);
destFolder.createFile(file);
}
}
}
After completing this script, I wrote another small script to create PDFs in bulk. It gets the list of names to create PDFs for from a cell range within my sheet. Here is the bulk creator that calls on the previous function.
function bulkCreatePDF() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Bulk PDF Creator");
var range = sheet.getRange(8,1, sheet.getLastRow(), 2)
var values = range.getValues();
var dupTest = sheet.getRange("A6").getValue();
var createCount = sheet.getRange("B4").getValue();
var created = 1;
if(dupTest != 0){
Browser.msgBox("Warning, duplicate entry found", "You have selected the same agent's name twice, please fix and then try again.", Browser.Buttons.OK);
}
else
{
for(j=0;j< values.length;j++){
var agentName = values[j][0];
var emailChoice = values[j][1];
if(agentName != ""){
ss.getRangeByName("AgentName").setValue(agentName);
ss.getRangeByName("SendEmail").setValue(emailChoice);
getAgentName();
ss.toast( "PDF Created for: " +agentName+".",created+" of "+createCount+ " PDF's created");
created = created+1;
SpreadsheetApp.flush();
}
}
}
range.clearContent();
Browser.msgBox("Task completed", "All PDF's have been created, saved to Google Drive and emailed to those you seleceted",Browser.Buttons.OK);
}
in both scripts I've tried to build in warnings, prompts and progress indicators where possible, to minimize any problems. I've also tried to build in checking for file/folder existence before it creates files and folders. This seems to work, but this is my first time using scripting to interface with Google Drive. So perhaps there are better methods.