Last active
February 18, 2025 08:29
-
-
Save phillypb/672d253841b7787784cf73bbffa16453 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* A number of Global Variables to speed up repetitive automation. | |
*/ | |
var theSpreadsheet = SpreadsheetApp.getActiveSpreadsheet(); | |
var timeZone = theSpreadsheet.getSpreadsheetTimeZone(); | |
var logSheet = theSpreadsheet.getSheetByName("Log"); | |
/** | |
* https://developers.google.com/apps-script/advanced/admin-sdk-license-manager | |
* | |
* Google Product and SKU IDs: https://developers.google.com/admin-sdk/licensing/v1/how-tos/products | |
* | |
* @OnlyCurrentDoc | |
*/ | |
function upgradeToEducationPlus(e) { | |
try { | |
logEvent("Starting 'upgradeToEducationPlus' Function."); | |
// get lock that prevents any user from concurrently running a section of code. | |
var lock = LockService.getScriptLock(); | |
console.log("Initial ScriptLock is: " + lock); | |
// attempt to acquire the lock, timing out after the provided number of milliseconds if it's being used elsewhere. | |
lock.tryLock(90000); // 90 seconds | |
// check if can access the lock - returns Boolean | |
if (lock.hasLock()) { | |
// we have the lock so we can run our code that we do not want running concurrently | |
logEvent("The lock is available"); | |
// get Form data | |
var formValues = e.namedValues; | |
var emailAddress = formValues['Email address'][0]; | |
logEvent("Email Address is: " + emailAddress); | |
// Google Product ID | |
var productId = "101031"; | |
// Google Workspace for Education Plus (not the Staff version) | |
var skuId = "1010310008"; | |
// check if user is an Administrator - as they shouldn't be upgraded automatically | |
var userDetails = AdminDirectory.Users.get(emailAddress); | |
if (userDetails.isAdmin) { | |
logEvent("User appears to be an Administrator."); | |
// send the user an email ***************************** | |
var subject = "Google Education Plus upgrade - Administrator account"; | |
var body = "Hi" + "<br /><br />"; | |
body += "Thank you for your Google Form submission. It appears you have tried to upgrade a Google Administrator account. Due to the nature of this account type the process cannot be automated." + "<br /><br />"; | |
body += "Kind regards"; | |
// run Function to send user email | |
sendUserEmail(subject, emailAddress, body); | |
// send the user an email ***************************** | |
} else { | |
// assign new licence | |
try { | |
var results = AdminLicenseManager.LicenseAssignments.insert( | |
{ userId: emailAddress }, | |
productId, | |
skuId | |
); | |
logEvent("Successfully assigned licence."); | |
// send the user an email ***************************** | |
var subject = "Google Education Plus upgrade successful"; | |
var body = "Hi" + "<br /><br />"; | |
body += "Thank you for your Google Form submission. Your Google Education Plus licence has been applied but may take up to 24 hours for the new features to appear on your account." + "<br /><br />"; | |
body += "Kind regards"; | |
// run Function to send user email | |
sendUserEmail(subject, emailAddress, body); | |
// send the user an email ***************************** | |
} catch (error) { | |
// convert 'catch' error message to string and perform JavaScript 'match' for keywords | |
var errorString = error.toString(); | |
var matching = errorString.match(/User already has a license for the specified product/gi); | |
// test if 'match' is true for next steps | |
if (matching) { | |
logEvent("User already has an existing licence."); | |
// send the user an email ***************************** | |
var subject = "Google Education Plus upgrade already done"; | |
var body = "Hi" + "<br /><br />"; | |
body += "Thank you for your Google Form submission. It appears your account already has a valid Google Education Plus licence. Please note it may take up to 24 hours for the new features to appear." + "<br /><br />"; | |
body += "Kind regards"; | |
// run Function to send user email | |
sendUserEmail(subject, emailAddress, body); | |
// send the user an email ***************************** | |
} else { | |
// error assigning licence | |
throw new Error("Licence assignment failed with error: " + error); | |
}; | |
}; | |
}; | |
} else { | |
// failed to get the lock | |
logEvent("Failed to get the lock."); | |
}; | |
logEvent("Completed 'upgradeToEducationPlus' Function."); | |
} catch (error) { | |
// log error | |
logEvent("Problem with 'upgradeToEducationPlus' Function: " + error.stack); | |
// send email error to account that created the Trigger **************************** | |
// get link to Google Sheet for error email | |
var sheetLink = SpreadsheetApp.getActiveSpreadsheet().getUrl(); | |
// get email address from user Trigger | |
var triggerEmailAddress = Session.getActiveUser().getEmail(); | |
// send error email | |
var subject = 'Error with Google Education Plus upgrade Form'; | |
var body = "Link to Google Sheet file: " + sheetLink + "\n\n"; | |
body += "Error message: " + error.stack; | |
MailApp.sendEmail(triggerEmailAddress, subject, body); | |
// send email error to account that created the Trigger **************************** | |
} finally { | |
// The Lock is released when the code script terminates but this is good practice to actually release it at the end so it is available asap. | |
try { | |
lock.releaseLock(); | |
logEvent("Lock has been released."); | |
} catch (error) { | |
// log but don't throw error as not necessary if fails | |
logEvent("Problem with releasing Lock in 'finally': " + error.stack); | |
}; | |
}; | |
}; | |
/** | |
* Function to send customised email to user who submitted Google Form. | |
*/ | |
function sendUserEmail(subject, emailAddress, body) { | |
try { | |
logEvent("Starting 'sendUserEmail' Function."); | |
// set additional options | |
var options = { | |
noReply: true, | |
htmlBody: body | |
}; | |
// send email | |
MailApp.sendEmail(emailAddress, subject, "", options); | |
logEvent("Completed 'sendUserEmail' Function."); | |
} catch (error) { | |
throw new Error("Problem with 'sendUserEmail' Function: " + error); | |
}; | |
}; | |
/** | |
* Function to output messages to the 'Log' sheet. | |
* Can be called anywhere else in script. | |
*/ | |
function logEvent(action) { | |
// create and format a timestamp | |
var dateTime = new Date(); | |
var niceDateTime = Utilities.formatDate(dateTime, timeZone, "dd/MM/yyyy, HH:mm:ss"); | |
// create array of data for pasting into log sheet | |
var logData = [niceDateTime, action]; | |
// append details into next row of log sheet | |
logSheet.appendRow(logData); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment