Created
September 1, 2016 22:55
-
-
Save oloftus/c8039c5dc892cdccdb3ab5914fab562d to your computer and use it in GitHub Desktop.
One-Click Email Survey: Get.gs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ALPHA_NUM = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"; | |
var EMAIL_COL = 2; | |
var KEY_COL = 1; | |
function rowExists(sheet, startRow, numRows, col, value) { | |
var range = sheet.getRange(startRow, col, numRows).getValues(); | |
var values = range.map(function(itm) { | |
return itm[0]; | |
}); | |
var exists = values.indexOf(value) != -1; | |
return exists; | |
} | |
function keyExists(sheet, key) { | |
return rowExists(sheet, 1, sheet.getLastRow(), KEY_COL, key); | |
} | |
function emailExists(sheet, email) { | |
return rowExists(sheet, 1, sheet.getLastRow(), EMAIL_COL, email); | |
} | |
function generateKey(sheet, keyLen) { | |
var key = ""; | |
do { | |
for (i = 0; i < keyLen; i++) { | |
var ix = Math.random() * ALPHA_NUM.length; | |
key += ALPHA_NUM.substr(ix, 1); | |
} | |
} | |
while (keyExists(sheet, key)); | |
return key; | |
} | |
function doGet(e) { | |
var properties = PropertiesService.getScriptProperties(); | |
var email = e.parameter.email; | |
var resp = e.parameter.resp; | |
var html = HtmlService.createHtmlOutputFromFile("Base.html"); | |
if (typeof email == "undefined" || typeof resp == "undefined") { | |
html.append("Error: Missing parameters"); | |
return html; | |
} | |
var spreadsheetId = properties.getProperty("spreadsheetId"); | |
var responsesSheetName = properties.getProperty("form1SheetName"); | |
var keyLen = parseInt(properties.getProperty("keyLen")) | |
var surveyKeyUrlParam = properties.getProperty("surveyKeyUrlParam"); | |
var surveyBaseUrl = properties.getProperty("surveyBaseUrl"); | |
var responses = SpreadsheetApp.openById(spreadsheetId).getSheetByName(responsesSheetName); | |
if (emailExists(responses, email)) { | |
html.append("It looks like you've already completed the survey!"); | |
return html; | |
} | |
var key = generateKey(responses, keyLen); | |
responses.appendRow([key, email, resp]); | |
var link = surveyBaseUrl + surveyKeyUrlParam + "=" + key; | |
html.append("<b>Taking you to the survey...</b><br/><br/>"); | |
html.append("<script type=\"text/javascript\">window.top.location.href = \"" + link + "\";</script>"); | |
html.append("<a href=\"" + link + "\">Click here</a> if the survey doesn't appear within 5 seconds."); | |
return html; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment