(spec)
+ (spec)
Watch id:
diff --git a/forms-api/demos/AppsScriptFormsAPIWebApp/README.md b/forms-api/demos/AppsScriptFormsAPIWebApp/README.md
index 303d5cda2..71ae952cc 100644
--- a/forms-api/demos/AppsScriptFormsAPIWebApp/README.md
+++ b/forms-api/demos/AppsScriptFormsAPIWebApp/README.md
@@ -4,15 +4,15 @@ This solution demonstrates how to interact with the new Google Forms API directl
## General setup
-* Enable the Forms API for your Google Cloud project
+* Enable the Forms API for your Google Cloud project
## Web app setup
1. Create a new blank Apps Script project.
1. Click **Project Settings**, then:
- * Check **Show "appsscript.json" manifest file in editor**.
- * Enter the project number of the Google Cloud project that has the
+ * Check **Show "appsscript.json" manifest file in editor**.
+ * Enter the project number of the Google Cloud project that has the
Forms API enabled and click **Change project**.
1. Copy the contents of the Apps Script, HTML and JSON files into your
@@ -20,13 +20,13 @@ This solution demonstrates how to interact with the new Google Forms API directl
1. Edit the `FormsAPI.gs` file to customize the constants.
* `formId`: Choose a `formId` from an existing form.
- * `topicName`: Optional, if using watches (pub/sub).
+ * `topicName`: Optional, if using watches (pub/sub).
- Note: Further project setup is required to use the watch features. To
- set up pub/sub topics, see
+ Note: Further project setup is required to use the watch features. To
+ set up pub/sub topics, see
[Google Cloud Pubsub](https://cloud.google.com/pubsub/docs/building-pubsub-messaging-system)
for additional details.
-1. Deploy the project as a Web app, authorize access and click on the
+1. Deploy the project as a Web app, authorize access and click on the
deployment URL.
diff --git a/forms-api/snippets/README.md b/forms-api/snippets/README.md
index 3b4d4cca0..1a6f81ce5 100644
--- a/forms-api/snippets/README.md
+++ b/forms-api/snippets/README.md
@@ -1,6 +1,4 @@
# Forms API
-The Google Forms API is currently in Restricted Beta. To use the API and these
-samples prior to General Availability, your Google Cloud project must be
-allowlisted. To request that your project be allowlisted, complete the
-[Early Adopter Program application](https://developers.google.com/forms/api/eap).
+To run, you must set up your GCP project to use the Forms API.
+See: [Forms API](https://developers.google.com/forms/api/)
diff --git a/forms-api/snippets/retrieve_all_responses.gs b/forms-api/snippets/retrieve_all_responses.gs
index 688adecdd..78a55ceeb 100644
--- a/forms-api/snippets/retrieve_all_responses.gs
+++ b/forms-api/snippets/retrieve_all_responses.gs
@@ -1,4 +1,4 @@
-# Copyright 2021 Google LLC
+# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -14,14 +14,14 @@
# [START forms_retrieve_all_responses]
function callFormsAPI() {
- Logger.log('Calling the Forms API!');
+ console.log('Calling the Forms API!');
var formId = '';
// Get OAuth Token
var OAuthToken = ScriptApp.getOAuthToken();
- Logger.log('OAuth token is: ' + OAuthToken);
- var formsAPIUrl = 'https://forms.googleapis.com/v1beta/forms/' + formId + '/' + 'responses';
- Logger.log('formsAPIUrl is: ' + formsAPIUrl);
+ console.log('OAuth token is: ' + OAuthToken);
+ var formsAPIUrl = 'https://forms.googleapis.com/v1/forms/' + formId + '/' + 'responses';
+ console.log('formsAPIUrl is: ' + formsAPIUrl);
var options = {
'headers': {
Authorization: 'Bearer ' + OAuthToken,
@@ -30,6 +30,6 @@
'method': 'get'
};
var response = UrlFetchApp.fetch(formsAPIUrl, options);
- Logger.log('Response from forms.responses was: ' + response);
+ console.log('Response from forms.responses was: ' + response);
}
-# [END forms_retrieve_all_responses]
\ No newline at end of file
+# [END forms_retrieve_all_responses]
diff --git a/forms/notifications/notification.gs b/forms/notifications/notification.gs
index f80531c21..8a8667e91 100644
--- a/forms/notifications/notification.gs
+++ b/forms/notifications/notification.gs
@@ -59,7 +59,7 @@ function onOpen(e) {
.addToUi();
} catch (e) {
// TODO (Developer) - Handle exception
- Logger.log('Failed with error: %s', e.error);
+ console.log('Failed with error: %s', e.error);
}
}
@@ -87,7 +87,7 @@ function showSidebar() {
FormApp.getUi().showSidebar(ui);
} catch (e) {
// TODO (Developer) - Handle exception
- Logger.log('Failed with error: %s', e.error);
+ console.log('Failed with error: %s', e.error);
}
}
@@ -103,7 +103,7 @@ function showAbout() {
FormApp.getUi().showModalDialog(ui, 'About Form Notifications');
} catch (e) {
// TODO (Developer) - Handle exception
- Logger.log('Failed with error: %s', e.error);
+ console.log('Failed with error: %s', e.error);
}
}
@@ -120,7 +120,7 @@ function saveSettings(settings) {
adjustFormSubmitTrigger();
} catch (e) {
// TODO (Developer) - Handle exception
- Logger.log('Failed with error: %s', e.error);
+ console.log('Failed with error: %s', e.error);
}
}
@@ -155,7 +155,7 @@ function getSettings() {
return settings;
} catch (e) {
// TODO (Developer) - Handle exception
- Logger.log('Failed with error: %s', e.error);
+ console.log('Failed with error: %s', e.error);
}
}
@@ -190,7 +190,7 @@ function adjustFormSubmitTrigger() {
}
} catch (e) {
// TODO (Developer) - Handle exception
- Logger.log('Failed with error: %s', e.error);
+ console.log('Failed with error: %s', e.error);
}
}
@@ -238,7 +238,7 @@ function respondToFormSubmit(e) {
}
} catch (e) {
// TODO (Developer) - Handle exception
- Logger.log('Failed with error: %s', e.error);
+ console.log('Failed with error: %s', e.error);
}
}
@@ -273,7 +273,7 @@ function sendReauthorizationRequest() {
}
} catch (e) {
// TODO (Developer) - Handle exception
- Logger.log('Failed with error: %s', e.error);
+ console.log('Failed with error: %s', e.error);
}
}
@@ -316,7 +316,7 @@ function sendCreatorNotification() {
}
} catch (e) {
// TODO (Developer) - Handle exception
- Logger.log('Failed with error: %s', e.error);
+ console.log('Failed with error: %s', e.error);
}
}
@@ -349,7 +349,7 @@ function sendRespondentNotification(response) {
}
} catch (e) {
// TODO (Developer) - Handle exception
- Logger.log('Failed with error: %s', e.error);
+ console.log('Failed with error: %s', e.error);
}
}
// [END apps_script_forms_notifications_quickstart]
diff --git a/gmail/README.md b/gmail/README.md
index 0bf3903d7..9c57176f0 100644
--- a/gmail/README.md
+++ b/gmail/README.md
@@ -9,3 +9,7 @@ This tutorial shows an easy way to collect information from different users in a
## [Sending Emails](https://developers.google.com/apps-script/articles/sending_emails)
This tutorial shows how to use Spreadsheet data to send emails to different people.
+
+## [Inline Image](inlineimage/inlineimage.gs)
+
+This example shows how to send an HTML email that includes an inline image attachment.
diff --git a/gmail/inlineimage/inlineimage.gs b/gmail/inlineimage/inlineimage.gs
new file mode 100644
index 000000000..0ca113c6f
--- /dev/null
+++ b/gmail/inlineimage/inlineimage.gs
@@ -0,0 +1,36 @@
+
+/**
+ * Copyright 2022 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+function sendEmailToMyself() {
+ // You can use this method to test the welcome email.
+ sendEmailWithInlineImage(Session.getActiveUser().getEmail());
+}
+
+function sendEmailWithInlineImage(toAddress) {
+ const options = {};
+ const imageName = 'cat_emoji';
+ // The URL "cid:cat_emoji" means that the inline attachment named "cat_emoji" would be used.
+ options['htmlBody'] = 'Welcome! ';
+ options['inlineImages'] = {[imageName]: Utilities.newBlob(getImageBinary(), 'image/png', imageName)};
+ GmailApp.sendEmail(toAddress, 'Welcome!', 'Welcome!', options);
+}
+
+function getImageBinary() {
+ // Cat Face Emoji from https://github.com/googlefonts/noto-emoji/blob/main/png/32/emoji_u1f431.png, Base64 encoded.
+ const catPngBase64 = 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA+BJREFUeNrsV01ME1EQnpaltPK3iAT0oAsxMSYmlIOaGBO2etCDMTVq8CYl3jRBvehBI0YPehIPxhvFkxo1gHpQE9P15+KtROJFI6sxhEKwW6FY27o6s/vabpd9tPUn8eAkj8e+nTffzDez814B/kX5oXT4/7A9GceAk12Xg/IkThIOFUfIJb9XfgNYxCmMI8iWNLTXZNVx2zYEGTiwOUKe/wZ4xAJOIhIbXAdQuo2/dacB6i8gP7X0dA43hSsEJ+eJST9UtZv2fIdyr5d1wMyRsMkcBSd6y2WCRT5C0RrgZKN6K4C3x1FfcFw1QSFvYP4sWk4SE1F426gyRyVo/mbqzdUgiK6BoEcBkv35yAsBcEUoGRIZ8uwA+PYAQHeNgPsHzUv1MjYyfT0lwZ1S4Cz6DNNG8LoMX8+XLfz/9XZhXwUOaMUJTQJ8OYnRvSqs1VpAyCEaTu++T5p7aa7AgXGTzlfmRsq93cCKbHHE1qjt7FAAORvZidyqwm1E7BuNlORtoRoNou8iK0INi1DQ+emhWqBhpqQdm5HKK8JoWTVhB8o5wv02k+bA7moFX5ICfKmV7cQfErdDBys6MNTpLAzeS4AynirLoLagQ+jyLOw7G3PaI9lbsT0FQfuOwMkpwwmS8KkW6N1Vv6wDJ67NwfDjebPaxr9C/L5kV5GthWj/Cjrt2jlwkrGXiyUZUGPZIjYcWOgeGhrqxSHnGaAFKqVE5rq/sXqOa1ysK923pFahSF/u9Oaf3yS2wJsvm/2szhRrCuhBfjGzV6xyZ6Gr6Tm0eT8YLwYON8HAjbhhrH9/Y97Y+eE4KFEzOqlNgCvHmg2dK0ebjci1pI76DXn9d/OdkNa9sGdNOOrbOXGC1wciC1lRTus1sNIT40ZJwIHjU0VrkcE1IPu93D2f063wMbkB4ukWTU1uJAbUvr6+kAvpP44PhyllDdWfJcGVkbauepJngCehS7Mw/MgsNtnvg5GLrcumiBjwuFPgqUopq3dHAjwG6Mw/xzPStEeF8OkWCG6vNWhuP/TRmOMPJQM8x8zkrbVGWqzyNHYQ6oQELGbrFWTgKhGJDGh5LWLi5ofFbtEzC6sxej/WwZICQ6P7zsSMiNXpjAFO0nXkE/jX18DoyyTOniXgJDtb78B0ah281raNsV5DTU9xMXCR9QAl1HExbL82WT8rKr7ou7Tx3H+gASOvgqt3E8Y7azHyyge7baDUrbi8A+nXpAsdiC57IWHX8PN/ATxkB3dkoNyCrEA0Bj5a0ZUMN5ADAfsFokLgQXb+j3JxKrjnB9nvBpFTpLmjnM77ZzhG2fH+X/5t+SnAAE+HjvApIyOGAAAAAElFTkSuQmCC';
+ return Utilities.base64Decode(catPngBase64);
+}
diff --git a/gmail/mailmerge/mailmerge.gs b/gmail/mailmerge/mailmerge.gs
deleted file mode 100644
index 30cc15c0c..000000000
--- a/gmail/mailmerge/mailmerge.gs
+++ /dev/null
@@ -1,211 +0,0 @@
-/**
- * Copyright Google LLC
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * https://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// [START apps_script_gmail_mail_merge]
-/**
- * Iterates row by row in the input range and returns an array of objects.
- * Each object contains all the data for a given row, indexed by its normalized column name.
- * @param {Sheet} sheet The sheet object that contains the data to be processed
- * @param {Range} range The exact range of cells where the data is stored
- * @param {number} columnHeadersRowIndex Specifies the row number where the column names are stored.
- * This argument is optional and it defaults to the row immediately above range;
- * @return {object[]} An array of objects.
- */
-function getRowsData(sheet, range, columnHeadersRowIndex) {
- columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
- var numColumns = range.getEndColumn() - range.getColumn() + 1;
- var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
- var headers = headersRange.getValues()[0];
- return getObjects(range.getValues(), normalizeHeaders(headers));
-}
-
-/**
- * For every row of data in data, generates an object that contains the data. Names of
- * object fields are defined in keys.
- * @param {object} data JavaScript 2d array
- * @param {object} keys Array of Strings that define the property names for the objects to create
- * @return {object[]} A list of objects.
- */
-function getObjects(data, keys) {
- var objects = [];
- for (var i = 0; i < data.length; ++i) {
- var object = {};
- var hasData = false;
- for (var j = 0; j < data[i].length; ++j) {
- var cellData = data[i][j];
- if (isCellEmpty(cellData)) {
- continue;
- }
- object[keys[j]] = cellData;
- hasData = true;
- }
- if (hasData) {
- objects.push(object);
- }
- }
- return objects;
-}
-
-/**
- * Returns an array of normalized Strings.
- * @param {string[]} headers Array of strings to normalize
- * @return {string[]} An array of normalized strings.
- */
-function normalizeHeaders(headers) {
- var keys = [];
- for (var i = 0; i < headers.length; ++i) {
- var key = normalizeHeader(headers[i]);
- if (key.length > 0) {
- keys.push(key);
- }
- }
- return keys;
-}
-
-/**
- * Normalizes a string, by removing all alphanumeric characters and using mixed case
- * to separate words. The output will always start with a lower case letter.
- * This function is designed to produce JavaScript object property names.
- * @param {string} header The header to normalize.
- * @return {string} The normalized header.
- * @example "First Name" -> "firstName"
- * @example "Market Cap (millions) -> "marketCapMillions
- * @example "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
- */
-function normalizeHeader(header) {
- var key = '';
- var upperCase = false;
- for (var i = 0; i < header.length; ++i) {
- var letter = header[i];
- if (letter == ' ' && key.length > 0) {
- upperCase = true;
- continue;
- }
- if (!isAlnum(letter)) {
- continue;
- }
- if (key.length == 0 && isDigit(letter)) {
- continue; // first character must be a letter
- }
- if (upperCase) {
- upperCase = false;
- key += letter.toUpperCase();
- } else {
- key += letter.toLowerCase();
- }
- }
- return key;
-}
-
-/**
- * Returns true if the cell where cellData was read from is empty.
- * @param {string} cellData Cell data
- * @return {boolean} True if the cell is empty.
- */
-function isCellEmpty(cellData) {
- return typeof(cellData) == 'string' && cellData == '';
-}
-
-/**
- * Returns true if the character char is alphabetical, false otherwise.
- * @param {string} char The character.
- * @return {boolean} True if the char is a number.
- */
-function isAlnum(char) {
- return char >= 'A' && char <= 'Z' ||
- char >= 'a' && char <= 'z' ||
- isDigit(char);
-}
-
-/**
- * Returns true if the character char is a digit, false otherwise.
- * @param {string} char The character.
- * @return {boolean} True if the char is a digit.
- */
-function isDigit(char) {
- return char >= '0' && char <= '9';
-}
-
-/**
- * Sends emails from spreadsheet rows.
- */
-function sendEmails() {
- var ss = SpreadsheetApp.getActiveSpreadsheet();
- var dataSheet = ss.getSheets()[0];
- // [START apps_script_gmail_email_data_range]
- var dataRange = dataSheet.getRange(2, 1, dataSheet.getMaxRows() - 1, 4);
- // [END apps_script_gmail_email_data_range]
-
- // [START apps_script_gmail_email_template]
- var templateSheet = ss.getSheets()[1];
- var emailTemplate = templateSheet.getRange('A1').getValue();
- // [END apps_script_gmail_email_template]
-
- // [START apps_script_gmail_email_objects]
- // Create one JavaScript object per row of data.
- var objects = getRowsData(dataSheet, dataRange);
- // [END apps_script_gmail_email_objects]
-
- // For every row object, create a personalized email from a template and send
- // it to the appropriate person.
- for (var i = 0; i < objects.length; ++i) {
- // Get a row object
- var rowData = objects[i];
-
- // [START apps_script_gmail_email_text]
- // Generate a personalized email.
- // Given a template string, replace markers (for instance ${"First Name"}) with
- // the corresponding value in a row object (for instance rowData.firstName).
- var emailText = fillInTemplateFromObject(emailTemplate, rowData);
- // [END apps_script_gmail_email_text]
- var emailSubject = 'Tutorial: Simple Mail Merge';
-
- // [START apps_script_gmail_send_email]
- MailApp.sendEmail(rowData.emailAddress, emailSubject, emailText);
- // [END apps_script_gmail_send_email]
- }
-}
-
-/**
- * Replaces markers in a template string with values define in a JavaScript data object.
- * @param {string} template Contains markers, for instance ${"Column name"}
- * @param {object} data values to that will replace markers.
- * For instance data.columnName will replace marker ${"Column name"}
- * @return {string} A string without markers. If no data is found to replace a marker,
- * it is simply removed.
- */
-function fillInTemplateFromObject(template, data) {
- var email = template;
- // [START apps_script_gmail_template_vars]
- // Search for all the variables to be replaced, for instance ${"Column name"}
- var templateVars = template.match(/\$\{\"[^\"]+\"\}/g);
- // [END apps_script_gmail_template_vars]
-
- // Replace variables from the template with the actual values from the data object.
- // If no value is available, replace with the empty string.
- for (var i = 0; templateVars && i < templateVars.length; ++i) {
- // normalizeHeader ignores ${"} so we can call it directly here.
- // [START apps_script_gmail_template_variable_data]
- var variableData = data[normalizeHeader(templateVars[i])];
- // [END apps_script_gmail_template_variable_data]
- // [START apps_script_gmail_template_replace]
- email = email.replace(templateVars[i], variableData || '');
- // [END apps_script_gmail_template_replace]
- }
-
- return email;
-}
-// [END apps_script_gmail_mail_merge]
diff --git a/gmail/markup/Code.gs b/gmail/markup/Code.gs
index 834992e9f..d4f65f6ed 100644
--- a/gmail/markup/Code.gs
+++ b/gmail/markup/Code.gs
@@ -12,7 +12,7 @@ function testSchemas() {
htmlBody: htmlBody
});
} catch (err) {
- Logger.log(err.message);
+ console.log(err.message);
}
}
// [END gmail_send_email_with_markup]
diff --git a/gmail/markup/mail_template.html b/gmail/markup/mail_template.html
index 68f4e9f3b..f339fbc31 100644
--- a/gmail/markup/mail_template.html
+++ b/gmail/markup/mail_template.html
@@ -1,3 +1,19 @@
+
+
+
+
\ No newline at end of file
diff --git a/solutions/automations/calendar-timesheet/README.md b/solutions/automations/calendar-timesheet/README.md
new file mode 100644
index 000000000..0c90af2c2
--- /dev/null
+++ b/solutions/automations/calendar-timesheet/README.md
@@ -0,0 +1,3 @@
+# Record time and activities in Calendar and Sheets
+
+See [developers.google.com](https://developers.google.com/apps-script/samples/automations/calendar-timesheet) for additional details.
diff --git a/solutions/automations/calendar-timesheet/appsscript.json b/solutions/automations/calendar-timesheet/appsscript.json
new file mode 100644
index 000000000..3cf1d247d
--- /dev/null
+++ b/solutions/automations/calendar-timesheet/appsscript.json
@@ -0,0 +1,7 @@
+{
+ "timeZone": "America/New_York",
+ "dependencies": {
+ },
+ "exceptionLogging": "STACKDRIVER",
+ "runtimeVersion": "V8"
+}
\ No newline at end of file
diff --git a/solutions/automations/content-signup/.clasp.json b/solutions/automations/content-signup/.clasp.json
new file mode 100644
index 000000000..0543fbf7b
--- /dev/null
+++ b/solutions/automations/content-signup/.clasp.json
@@ -0,0 +1 @@
+{"scriptId": "1G8TfU6Rfcl76Uo4gKig7jFMYKai-V_fiUNbO12pAb25pA4_uyxN5PSvd"}
diff --git a/solutions/automations/content-signup/Code.js b/solutions/automations/content-signup/Code.js
new file mode 100644
index 000000000..e48e64cd7
--- /dev/null
+++ b/solutions/automations/content-signup/Code.js
@@ -0,0 +1,129 @@
+// To learn how to use this script, refer to the documentation:
+// https://developers.google.com/apps-script/samples/automations/content-signup
+
+/*
+Copyright 2022 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// To use your own template doc, update the below variable with the URL of your own Google Doc template.
+// Make sure you update the sharing settings so that 'anyone' or 'anyone in your organization' can view.
+const EMAIL_TEMPLATE_DOC_URL = 'https://docs.google.com/document/d/1enes74gWsMG3dkK3SFO08apXkr0rcYBd3JHKOb2Nksk/edit?usp=sharing';
+// Update this variable to customize the email subject.
+const EMAIL_SUBJECT = 'Hello, here is the content you requested';
+
+// Update this variable to the content titles and URLs you want to offer. Make sure you update the form so that the content titles listed here match the content titles you list in the form.
+const topicUrls = {
+ 'Google Calendar how-to videos': 'https://www.youtube.com/playlist?list=PLU8ezI8GYqs7IPb_UdmUNKyUCqjzGO9PJ',
+ 'Google Drive how-to videos': 'https://www.youtube.com/playlist?list=PLU8ezI8GYqs7Y5d1cgZm2Obq7leVtLkT4',
+ 'Google Docs how-to videos': 'https://www.youtube.com/playlist?list=PLU8ezI8GYqs4JKwZ-fpBP-zSoWPL8Sit7',
+ 'Google Sheets how-to videos': 'https://www.youtube.com/playlist?list=PLU8ezI8GYqs61ciKpXf_KkV7ZRbRHVG38',
+};
+
+/**
+ * Installs a trigger on the spreadsheet for when someone submits a form.
+ */
+function installTrigger() {
+ ScriptApp.newTrigger('onFormSubmit')
+ .forSpreadsheet(SpreadsheetApp.getActive())
+ .onFormSubmit()
+ .create();
+}
+
+/**
+ * Sends a customized email for every form response.
+ *
+ * @param {Object} event - Form submit event
+ */
+function onFormSubmit(e) {
+ let responses = e.namedValues;
+
+ // If the question title is a label, it can be accessed as an object field.
+ // If it has spaces or other characters, it can be accessed as a dictionary.
+ let timestamp = responses.Timestamp[0];
+ let email = responses['Email address'][0].trim();
+ let name = responses.Name[0].trim();
+ let topicsString = responses.Topics[0].toLowerCase();
+
+ // Parse topics of interest into a list (since there are multiple items
+ // that are saved in the row as blob of text).
+ let topics = Object.keys(topicUrls).filter(function(topic) {
+ // indexOf searches for the topic in topicsString and returns a non-negative
+ // index if the topic is found, or it will return -1 if it's not found.
+ return topicsString.indexOf(topic.toLowerCase()) != -1;
+ });
+
+ // If there is at least one topic selected, send an email to the recipient.
+ let status = '';
+ if (topics.length > 0) {
+ MailApp.sendEmail({
+ to: email,
+ subject: EMAIL_SUBJECT,
+ htmlBody: createEmailBody(name, topics),
+ });
+ status = 'Sent';
+ }
+ else {
+ status = 'No topics selected';
+ }
+
+ // Append the status on the spreadsheet to the responses' row.
+ let sheet = SpreadsheetApp.getActiveSheet();
+ let row = sheet.getActiveRange().getRow();
+ let column = e.values.length + 1;
+ sheet.getRange(row, column).setValue(status);
+
+ console.log("status=" + status + "; responses=" + JSON.stringify(responses));
+}
+
+/**
+ * Creates email body and includes the links based on topic.
+ *
+ * @param {string} recipient - The recipient's email address.
+ * @param {string[]} topics - List of topics to include in the email body.
+ * @return {string} - The email body as an HTML string.
+ */
+function createEmailBody(name, topics) {
+ let topicsHtml = topics.map(function(topic) {
+ let url = topicUrls[topic];
+ return '
';
+
+ // Make sure to update the emailTemplateDocId at the top.
+ let docId = DocumentApp.openByUrl(EMAIL_TEMPLATE_DOC_URL).getId();
+ let emailBody = docToHtml(docId);
+ emailBody = emailBody.replace(/{{NAME}}/g, name);
+ emailBody = emailBody.replace(/{{TOPICS}}/g, topicsHtml);
+ return emailBody;
+}
+
+/**
+ * Downloads a Google Doc as an HTML string.
+ *
+ * @param {string} docId - The ID of a Google Doc to fetch content from.
+ * @return {string} The Google Doc rendered as an HTML string.
+ */
+function docToHtml(docId) {
+
+ // Downloads a Google Doc as an HTML string.
+ let url = "https://docs.google.com/feeds/download/documents/export/Export?id=" +
+ docId + "&exportFormat=html";
+ let param = {
+ method: "get",
+ headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
+ muteHttpExceptions: true,
+ };
+ return UrlFetchApp.fetch(url, param).getContentText();
+}
diff --git a/solutions/automations/content-signup/README.md b/solutions/automations/content-signup/README.md
new file mode 100644
index 000000000..ac50839e6
--- /dev/null
+++ b/solutions/automations/content-signup/README.md
@@ -0,0 +1,3 @@
+# Send curated content
+
+See [developers.google.com](https://developers.google.com/apps-script/samples/automations/content-signup) for additional details.
diff --git a/solutions/automations/content-signup/appsscript.json b/solutions/automations/content-signup/appsscript.json
new file mode 100644
index 000000000..ba13ec1c1
--- /dev/null
+++ b/solutions/automations/content-signup/appsscript.json
@@ -0,0 +1,14 @@
+{
+ "timeZone": "America/Los_Angeles",
+ "dependencies": {},
+ "exceptionLogging": "STACKDRIVER",
+ "oauthScopes": [
+ "https://www.googleapis.com/auth/documents",
+ "https://www.googleapis.com/auth/drive.readonly",
+ "https://www.googleapis.com/auth/script.external_request",
+ "https://www.googleapis.com/auth/script.scriptapp",
+ "https://www.googleapis.com/auth/script.send_mail",
+ "https://www.googleapis.com/auth/spreadsheets.currentonly"
+ ],
+ "runtimeVersion": "V8"
+}
\ No newline at end of file
diff --git a/solutions/automations/course-feedback-response/.clasp.json b/solutions/automations/course-feedback-response/.clasp.json
new file mode 100644
index 000000000..ae51645f3
--- /dev/null
+++ b/solutions/automations/course-feedback-response/.clasp.json
@@ -0,0 +1 @@
+{"scriptId": "1k75E4EdC3TcJEGGIupBANjm5duvs35ORAU1Mg2_6DNXENo827dFzmFeC"}
diff --git a/solutions/automations/course-feedback-response/Code.js b/solutions/automations/course-feedback-response/Code.js
new file mode 100644
index 000000000..99dbad61f
--- /dev/null
+++ b/solutions/automations/course-feedback-response/Code.js
@@ -0,0 +1,119 @@
+// To learn how to use this script, refer to the documentation:
+// https://developers.google.com/apps-script/samples/automations/course-feedback-response
+
+/*
+Copyright 2022 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+/**
+ * Creates custom menu for user to run scripts.
+ */
+function onOpen() {
+ let ui = SpreadsheetApp.getUi();
+ ui.createMenu('Form Reply Tool')
+ .addItem('Enable auto draft replies', 'installTrigger')
+ .addToUi();
+}
+
+/**
+ * Installs a trigger on the Spreadsheet for when a Form response is submitted.
+ */
+function installTrigger() {
+ ScriptApp.newTrigger('onFormSubmit')
+ .forSpreadsheet(SpreadsheetApp.getActive())
+ .onFormSubmit()
+ .create();
+}
+
+/**
+ * Creates a draft email for every response on a form
+ *
+ * @param {Object} event - Form submit event
+ */
+function onFormSubmit(e) {
+ let responses = e.namedValues;
+
+ // parse form response data
+ let timestamp = responses.Timestamp[0];
+ let email = responses['Email address'][0].trim();
+
+ // create email body
+ let emailBody = createEmailBody(responses);
+
+ // create draft email
+ createDraft(timestamp, email, emailBody);
+}
+
+/**
+ * Creates email body and includes feedback from Google Form.
+ *
+ * @param {string} responses - The form response data
+ * @return {string} - The email body as an HTML string
+ */
+function createEmailBody(responses) {
+ // parse form response data
+ let name = responses.Name[0].trim();
+ let industry = responses['What industry do you work in?'][0];
+ let source = responses['How did you find out about this course?'][0];
+ let rating = responses['On a scale of 1 - 5 how would you rate this course?'][0];
+ let productFeedback = responses['What could be different to make it a 5 rating?'][0];
+ let otherFeedback = responses['Any other feedback?'][0];
+
+ // create email body
+ let htmlBody = 'Hi ' + name + ',
' +
+ 'Thanks for responding to our course feedback questionnaire.
' +
+ 'It\'s really useful to us to help improve this course.
+
+ See the spreadsheet to take or assign this item.
+
+
diff --git a/solutions/automations/equipment-requests/request-complete.html b/solutions/automations/equipment-requests/request-complete.html
new file mode 100644
index 000000000..ad26a7d81
--- /dev/null
+++ b/solutions/automations/equipment-requests/request-complete.html
@@ -0,0 +1,29 @@
+
+
+
+
+
+
+
+
diff --git a/solutions/automations/event-session-signup/.clasp.json b/solutions/automations/event-session-signup/.clasp.json
new file mode 100644
index 000000000..8b1357cc3
--- /dev/null
+++ b/solutions/automations/event-session-signup/.clasp.json
@@ -0,0 +1 @@
+{"scriptId": "1RTfpaBw-RYW8PTJsidiqXHRrqaKnwMWAK_nq4LnWk9xXKGJWi_bhexRj"}
diff --git a/solutions/automations/event-session-signup/Code.js b/solutions/automations/event-session-signup/Code.js
new file mode 100644
index 000000000..dda1bd589
--- /dev/null
+++ b/solutions/automations/event-session-signup/Code.js
@@ -0,0 +1,209 @@
+// To learn how to use this script, refer to the documentation:
+// https://developers.google.com/apps-script/samples/automations/event-session-signup
+
+/*
+Copyright 2022 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+/**
+ * Inserts a custom menu when the spreadsheet opens.
+ */
+function onOpen() {
+ SpreadsheetApp.getUi().createMenu('Conference')
+ .addItem('Set up conference', 'setUpConference_')
+ .addToUi();
+}
+
+/**
+ * Uses the conference data in the spreadsheet to create
+ * Google Calendar events, a Google Form, and a trigger that allows the script
+ * to react to form responses.
+ */
+function setUpConference_() {
+ let scriptProperties = PropertiesService.getScriptProperties();
+ if (scriptProperties.getProperty('calId')) {
+ Browser.msgBox('Your conference is already set up. Look in Google Drive for your'
+ + ' sign-up form!');
+ return;
+ }
+ let ss = SpreadsheetApp.getActive();
+ let sheet = ss.getSheetByName('Conference Setup');
+ let range = sheet.getDataRange();
+ let values = range.getValues();
+ setUpCalendar_(values, range);
+ setUpForm_(ss, values);
+ ScriptApp.newTrigger('onFormSubmit').forSpreadsheet(ss).onFormSubmit()
+ .create();
+}
+
+/**
+ * Creates a Google Calendar with events for each conference session in the
+ * spreadsheet, then writes the event IDs to the spreadsheet for future use.
+ * @param {Array} values Cell values for the spreadsheet range.
+ * @param {Range} range A spreadsheet range that contains conference data.
+ */
+function setUpCalendar_(values, range) {
+ let cal = CalendarApp.createCalendar('Conference Calendar');
+ // Start at 1 to skip the header row.
+ for (let i = 1; i < values.length; i++) {
+ let session = values[i];
+ let title = session[0];
+ let start = joinDateAndTime_(session[1], session[2]);
+ let end = joinDateAndTime_(session[1], session[3]);
+ let options = {location: session[4], sendInvites: true};
+ let event = cal.createEvent(title, start, end, options)
+ .setGuestsCanSeeGuests(false);
+ session[5] = event.getId();
+ }
+ range.setValues(values);
+
+ // Stores the ID for the Calendar, which is needed to retrieve events by ID.
+ let scriptProperties = PropertiesService.getScriptProperties();
+ scriptProperties.setProperty('calId', cal.getId());
+}
+
+/**
+ * Creates a single Date object from separate date and time cells.
+ *
+ * @param {Date} date A Date object from which to extract the date.
+ * @param {Date} time A Date object from which to extract the time.
+ * @return {Date} A Date object representing the combined date and time.
+ */
+function joinDateAndTime_(date, time) {
+ date = new Date(date);
+ date.setHours(time.getHours());
+ date.setMinutes(time.getMinutes());
+ return date;
+}
+
+/**
+ * Creates a Google Form that allows respondents to select which conference
+ * sessions they would like to attend, grouped by date and start time in the
+ * caller's time zone.
+ *
+ * @param {Spreadsheet} ss The spreadsheet that contains the conference data.
+ * @param {Array} values Cell values for the spreadsheet range.
+ */
+function setUpForm_(ss, values) {
+ // Group the sessions by date and time so that they can be passed to the form.
+ let schedule = {};
+ // Start at 1 to skip the header row.
+ for (let i = 1; i < values.length; i++) {
+ let session = values[i];
+ let day = session[1].toLocaleDateString();
+ let time = session[2].toLocaleTimeString();
+ if (!schedule[day]) {
+ schedule[day] = {};
+ }
+ if (!schedule[day][time]) {
+ schedule[day][time] = [];
+ }
+ schedule[day][time].push(session[0]);
+ }
+
+ // Creates the form and adds a multiple-choice question for each timeslot.
+ let form = FormApp.create('Conference Form');
+ form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());
+ form.addTextItem().setTitle('Name').setRequired(true);
+ form.addTextItem().setTitle('Email').setRequired(true);
+ Object.keys(schedule).forEach(function(day) {
+ let header = form.addSectionHeaderItem().setTitle('Sessions for ' + day);
+ Object.keys(schedule[day]).forEach(function(time) {
+ let item = form.addMultipleChoiceItem().setTitle(time + ' ' + day)
+ .setChoiceValues(schedule[day][time]);
+ });
+ });
+}
+
+/**
+ * Sends out calendar invitations and a
+ * personalized Google Docs itinerary after a user responds to the form.
+ *
+ * @param {Object} e The event parameter for form submission to a spreadsheet;
+ * see https://developers.google.com/apps-script/understanding_events
+ */
+function onFormSubmit(e) {
+ let user = {name: e.namedValues['Name'][0], email: e.namedValues['Email'][0]};
+
+ // Grab the session data again so that we can match it to the user's choices.
+ let response = [];
+ let values = SpreadsheetApp.getActive().getSheetByName('Conference Setup')
+ .getDataRange().getValues();
+ for (let i = 1; i < values.length; i++) {
+ let session = values[i];
+ let title = session[0];
+ let day = session[1].toLocaleDateString();
+ let time = session[2].toLocaleTimeString();
+ let timeslot = time + ' ' + day;
+
+ // For every selection in the response, find the matching timeslot and title
+ // in the spreadsheet and add the session data to the response array.
+ if (e.namedValues[timeslot] && e.namedValues[timeslot] == title) {
+ response.push(session);
+ }
+ }
+ sendInvites_(user, response);
+ sendDoc_(user, response);
+}
+
+/**
+ * Add the user as a guest for every session he or she selected.
+ * @param {object} user An object that contains the user's name and email.
+ * @param {Array} response An array of data for the user's session choices.
+ */
+function sendInvites_(user, response) {
+ let id = ScriptProperties.getProperty('calId');
+ let cal = CalendarApp.getCalendarById(id);
+ for (let i = 0; i < response.length; i++) {
+ cal.getEventSeriesById(response[i][5]).addGuest(user.email);
+ }
+}
+
+/**
+ * Creates and shares a personalized Google Doc that shows the user's itinerary.
+ * @param {object} user An object that contains the user's name and email.
+ * @param {Array} response An array of data for the user's session choices.
+ */
+function sendDoc_(user, response) {
+ let doc = DocumentApp.create('Conference Itinerary for ' + user.name)
+ .addEditor(user.email);
+ let body = doc.getBody();
+ let table = [['Session', 'Date', 'Time', 'Location']];
+ for (let i = 0; i < response.length; i++) {
+ table.push([response[i][0], response[i][1].toLocaleDateString(),
+ response[i][2].toLocaleTimeString(), response[i][4]]);
+ }
+ body.insertParagraph(0, doc.getName())
+ .setHeading(DocumentApp.ParagraphHeading.HEADING1);
+ table = body.appendTable(table);
+ table.getRow(0).editAsText().setBold(true);
+ doc.saveAndClose();
+
+ // Emails a link to the Doc as well as a PDF copy.
+ MailApp.sendEmail({
+ to: user.email,
+ subject: doc.getName(),
+ body: 'Thanks for registering! Here\'s your itinerary: ' + doc.getUrl(),
+ attachments: doc.getAs(MimeType.PDF),
+ });
+}
+
+/**
+ * Removes the calId script property so that the 'setUpConference_()' can be run again.
+ */
+function resetProperties(){
+ let scriptProperties = PropertiesService.getScriptProperties();
+ scriptProperties.deleteAllProperties();
+}
diff --git a/solutions/automations/event-session-signup/README.md b/solutions/automations/event-session-signup/README.md
new file mode 100644
index 000000000..cafbec79a
--- /dev/null
+++ b/solutions/automations/event-session-signup/README.md
@@ -0,0 +1,3 @@
+# Create a sign-up for sessions at a conference
+
+See [developers.google.com](https://developers.google.com/apps-script/samples/automations/event-session-signup) for additional details.
diff --git a/solutions/automations/event-session-signup/appsscript.json b/solutions/automations/event-session-signup/appsscript.json
new file mode 100644
index 000000000..3cf1d247d
--- /dev/null
+++ b/solutions/automations/event-session-signup/appsscript.json
@@ -0,0 +1,7 @@
+{
+ "timeZone": "America/New_York",
+ "dependencies": {
+ },
+ "exceptionLogging": "STACKDRIVER",
+ "runtimeVersion": "V8"
+}
\ No newline at end of file
diff --git a/solutions/automations/feedback-sentiment-analysis/.clasp.json b/solutions/automations/feedback-sentiment-analysis/.clasp.json
new file mode 100644
index 000000000..92fa17d1d
--- /dev/null
+++ b/solutions/automations/feedback-sentiment-analysis/.clasp.json
@@ -0,0 +1 @@
+{"scriptId":"1LOheMLQDlSkvmlt8EQOGGETewdt8tKWyzxspCwqzfianqxTXjBGpAc8c"}
\ No newline at end of file
diff --git a/solutions/automations/feedback-sentiment-analysis/README.md b/solutions/automations/feedback-sentiment-analysis/README.md
new file mode 100644
index 000000000..e06d1e851
--- /dev/null
+++ b/solutions/automations/feedback-sentiment-analysis/README.md
@@ -0,0 +1,3 @@
+# Analyze sentiment of open-ended feedback
+
+See [developers.google.com](https://developers.google.com/apps-script/samples/automations/feedback-sentiment-analysis) for additional details.
\ No newline at end of file
diff --git a/solutions/automations/feedback-sentiment-analysis/appsscript.json b/solutions/automations/feedback-sentiment-analysis/appsscript.json
new file mode 100644
index 000000000..cc6038b7a
--- /dev/null
+++ b/solutions/automations/feedback-sentiment-analysis/appsscript.json
@@ -0,0 +1,12 @@
+{
+ "timeZone": "America/Los_Angeles",
+ "dependencies": {
+ "libraries": [{
+ "userSymbol": "OAuth2",
+ "libraryId": "1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF",
+ "version": "24"
+ }]
+ },
+ "exceptionLogging": "STACKDRIVER",
+ "runtimeVersion": "V8"
+}
\ No newline at end of file
diff --git a/solutions/automations/feedback-sentiment-analysis/code.js b/solutions/automations/feedback-sentiment-analysis/code.js
new file mode 100644
index 000000000..b9ce619b1
--- /dev/null
+++ b/solutions/automations/feedback-sentiment-analysis/code.js
@@ -0,0 +1,133 @@
+// To learn how to use this script, refer to the documentation:
+// https://developers.google.com/apps-script/samples/automations/feedback-sentiment-analysis
+
+/*
+Copyright 2022 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Sets API key for accessing Cloud Natural Language API.
+const myApiKey = 'YOUR_API_KEY'; // Replace with your API key.
+
+// Matches column names in Review Data sheet to variables.
+let COLUMN_NAME = {
+ COMMENTS: 'comments',
+ ENTITY: 'entity_sentiment',
+ ID: 'id'
+};
+
+/**
+ * Creates a Demo menu in Google Spreadsheets.
+ */
+function onOpen() {
+ SpreadsheetApp.getUi()
+ .createMenu('Sentiment Tools')
+ .addItem('Mark entities and sentiment', 'markEntitySentiment')
+ .addToUi();
+};
+
+/**
+* Analyzes entities and sentiment for each comment in
+* Review Data sheet and copies results into the
+* Entity Sentiment Data sheet.
+*/
+function markEntitySentiment() {
+ // Sets variables for "Review Data" sheet
+ let ss = SpreadsheetApp.getActiveSpreadsheet();
+ let dataSheet = ss.getSheetByName('Review Data');
+ let rows = dataSheet.getDataRange();
+ let numRows = rows.getNumRows();
+ let values = rows.getValues();
+ let headerRow = values[0];
+
+ // Checks to see if "Entity Sentiment Data" sheet is present, and
+ // if not, creates a new sheet and sets the header row.
+ let entitySheet = ss.getSheetByName('Entity Sentiment Data');
+ if (entitySheet == null) {
+ ss.insertSheet('Entity Sentiment Data');
+ let entitySheet = ss.getSheetByName('Entity Sentiment Data');
+ let esHeaderRange = entitySheet.getRange(1,1,1,6);
+ let esHeader = [['Review ID','Entity','Salience','Sentiment Score',
+ 'Sentiment Magnitude','Number of mentions']];
+ esHeaderRange.setValues(esHeader);
+ };
+
+ // Finds the column index for comments, language_detected,
+ // and comments_english columns.
+ let textColumnIdx = headerRow.indexOf(COLUMN_NAME.COMMENTS);
+ let entityColumnIdx = headerRow.indexOf(COLUMN_NAME.ENTITY);
+ let idColumnIdx = headerRow.indexOf(COLUMN_NAME.ID);
+ if (entityColumnIdx == -1) {
+ Browser.msgBox("Error: Could not find the column named " + COLUMN_NAME.ENTITY +
+ ". Please create an empty column with header \"entity_sentiment\" on the Review Data tab.");
+ return; // bail
+ };
+
+ ss.toast("Analyzing entities and sentiment...");
+ for (let i = 0; i < numRows; ++i) {
+ let value = values[i];
+ let commentEnCellVal = value[textColumnIdx];
+ let entityCellVal = value[entityColumnIdx];
+ let reviewId = value[idColumnIdx];
+
+ // Calls retrieveEntitySentiment function for each row that has a comment
+ // and also an empty entity_sentiment cell value.
+ if(commentEnCellVal && !entityCellVal) {
+ let nlData = retrieveEntitySentiment(commentEnCellVal);
+ // Pastes each entity and sentiment score into Entity Sentiment Data sheet.
+ let newValues = []
+ for (let entity in nlData.entities) {
+ entity = nlData.entities [entity];
+ let row = [reviewId, entity.name, entity.salience, entity.sentiment.score,
+ entity.sentiment.magnitude, entity.mentions.length
+ ];
+ newValues.push(row);
+ }
+ if(newValues.length) {
+ entitySheet.getRange(entitySheet.getLastRow() + 1, 1, newValues.length, newValues[0].length).setValues(newValues);
+ }
+ // Pastes "complete" into entity_sentiment column to denote completion of NL API call.
+ dataSheet.getRange(i+1, entityColumnIdx+1).setValue("complete");
+ }
+ }
+};
+
+/**
+ * Calls the Cloud Natural Language API with a string of text to analyze
+ * entities and sentiment present in the string.
+ * @param {String} the string for entity sentiment analysis
+ * @return {Object} the entities and related sentiment present in the string
+ */
+function retrieveEntitySentiment (line) {
+ let apiKey = myApiKey;
+ let apiEndpoint = 'https://language.googleapis.com/v1/documents:analyzeEntitySentiment?key=' + apiKey;
+ // Creates a JSON request, with text string, language, type and encoding
+ let nlData = {
+ document: {
+ language: 'en-us',
+ type: 'PLAIN_TEXT',
+ content: line
+ },
+ encodingType: 'UTF8'
+ };
+ // Packages all of the options and the data together for the API call.
+ let nlOptions = {
+ method : 'post',
+ contentType: 'application/json',
+ payload : JSON.stringify(nlData)
+ };
+ // Makes the API call.
+ let response = UrlFetchApp.fetch(apiEndpoint, nlOptions);
+ return JSON.parse(response);
+};
\ No newline at end of file
diff --git a/solutions/automations/folder-creation/Code.js b/solutions/automations/folder-creation/Code.js
new file mode 100644
index 000000000..75e4b014c
--- /dev/null
+++ b/solutions/automations/folder-creation/Code.js
@@ -0,0 +1,33 @@
+/*
+Copyright 2022 Google LLC
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+ https://www.apache.org/licenses/LICENSE-2.0
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+/*
+This function will create a new folder in the defined Shard Drive.
+You define the Shared Drive by adding its ID on line number 26.
+The parameter 'project' is passed in from the AppSheet app.
+Please watch this video tutorial to see how to use this script: https://youtu.be/Utl57R7I2Cs
+*/
+
+function createNewFolder(project) {
+ const folder = Drive.Files.insert(
+ {
+ parents: [{ id: 'ADD YOUR SHARED DRIVE FOLDER ID HERE' }],
+ title: project,
+ mimeType: "application/vnd.google-apps.folder",
+ },
+ null,
+ { supportsAllDrives: true }
+ );
+
+ return folder.alternateLink;
+}
diff --git a/solutions/automations/folder-creation/README.md b/solutions/automations/folder-creation/README.md
new file mode 100644
index 000000000..f4cefdadd
--- /dev/null
+++ b/solutions/automations/folder-creation/README.md
@@ -0,0 +1,11 @@
+# Folder creation
+
+This code sample is part of a video tutorial on how to combine AppSheet and Apps Script.
+
+You can watch the video tutorial to find out how to use the sample.
+
+
+
+
+
+See the [Google Apps Script Documentation](https://developers.google.com/apps-script/advanced/drive) for additional information about the advanced Google Drive services.
diff --git a/solutions/automations/folder-creation/appscript.json b/solutions/automations/folder-creation/appscript.json
new file mode 100644
index 000000000..de9678f42
--- /dev/null
+++ b/solutions/automations/folder-creation/appscript.json
@@ -0,0 +1,14 @@
+{
+ "timeZone": "Europe/Madrid",
+ "dependencies": {
+ "enabledAdvancedServices": [
+ {
+ "userSymbol": "Drive",
+ "version": "v2",
+ "serviceId": "drive"
+ }
+ ]
+ },
+ "exceptionLogging": "STACKDRIVER",
+ "runtimeVersion": "V8"
+ }
\ No newline at end of file
diff --git a/solutions/automations/generate-pdfs/.clasp.json b/solutions/automations/generate-pdfs/.clasp.json
new file mode 100644
index 000000000..77e4f7125
--- /dev/null
+++ b/solutions/automations/generate-pdfs/.clasp.json
@@ -0,0 +1 @@
+{"scriptId": "1k9PjGdQ_G0HKEoS3np_Szfe-flmLw9gUvblQIxOfvTmS-NLeLgVUzvOa"}
diff --git a/solutions/automations/generate-pdfs/Code.js b/solutions/automations/generate-pdfs/Code.js
new file mode 100644
index 000000000..07e77a86b
--- /dev/null
+++ b/solutions/automations/generate-pdfs/Code.js
@@ -0,0 +1,263 @@
+// To learn how to use this script, refer to the documentation:
+// https://developers.google.com/apps-script/samples/automations/generate-pdfs
+
+/*
+Copyright 2022 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// TODO: To test this solution, set EMAIL_OVERRIDE to true and set EMAIL_ADDRESS_OVERRIDE to your email address.
+const EMAIL_OVERRIDE = false;
+const EMAIL_ADDRESS_OVERRIDE = 'test@example.com';
+
+// Application constants
+const APP_TITLE = 'Generate and send PDFs';
+const OUTPUT_FOLDER_NAME = "Customer PDFs";
+const DUE_DATE_NUM_DAYS = 15
+
+// Sheet name constants. Update if you change the names of the sheets.
+const CUSTOMERS_SHEET_NAME = 'Customers';
+const PRODUCTS_SHEET_NAME = 'Products';
+const TRANSACTIONS_SHEET_NAME = 'Transactions';
+const INVOICES_SHEET_NAME = 'Invoices';
+const INVOICE_TEMPLATE_SHEET_NAME = 'Invoice Template';
+
+// Email constants
+const EMAIL_SUBJECT = 'Invoice Notification';
+const EMAIL_BODY = 'Hello!\rPlease see the attached PDF document.';
+
+
+/**
+ * Iterates through the worksheet data populating the template sheet with
+ * customer data, then saves each instance as a PDF document.
+ *
+ * Called by user via custom menu item.
+ */
+function processDocuments() {
+ const ss = SpreadsheetApp.getActiveSpreadsheet();
+ const customersSheet = ss.getSheetByName(CUSTOMERS_SHEET_NAME);
+ const productsSheet = ss.getSheetByName(PRODUCTS_SHEET_NAME);
+ const transactionsSheet = ss.getSheetByName(TRANSACTIONS_SHEET_NAME);
+ const invoicesSheet = ss.getSheetByName(INVOICES_SHEET_NAME);
+ const invoiceTemplateSheet = ss.getSheetByName(INVOICE_TEMPLATE_SHEET_NAME);
+
+ // Gets data from the storage sheets as objects.
+ const customers = dataRangeToObject(customersSheet);
+ const products = dataRangeToObject(productsSheet);
+ const transactions = dataRangeToObject(transactionsSheet);
+
+ ss.toast('Creating Invoices', APP_TITLE, 1);
+ const invoices = [];
+
+ // Iterates for each customer calling createInvoiceForCustomer routine.
+ customers.forEach(function (customer) {
+ ss.toast(`Creating Invoice for ${customer.customer_name}`, APP_TITLE, 1);
+ let invoice = createInvoiceForCustomer(
+ customer, products, transactions, invoiceTemplateSheet, ss.getId());
+ invoices.push(invoice);
+ });
+ // Writes invoices data to the sheet.
+ invoicesSheet.getRange(2, 1, invoices.length, invoices[0].length).setValues(invoices);
+}
+
+/**
+ * Processes each customer instance with passed in data parameters.
+ *
+ * @param {object} customer - Object for the customer
+ * @param {object} products - Object for all the products
+ * @param {object} transactions - Object for all the transactions
+ * @param {object} invoiceTemplateSheet - Object for the invoice template sheet
+ * @param {string} ssId - Google Sheet ID
+ * Return {array} of instance customer invoice data
+ */
+function createInvoiceForCustomer(customer, products, transactions, templateSheet, ssId) {
+ let customerTransactions = transactions.filter(function (transaction) {
+ return transaction.customer_name == customer.customer_name;
+ });
+
+ // Clears existing data from the template.
+ clearTemplateSheet();
+
+ let lineItems = [];
+ let totalAmount = 0;
+ customerTransactions.forEach(function (lineItem) {
+ let lineItemProduct = products.filter(function (product) {
+ return product.sku_name == lineItem.sku;
+ })[0];
+ const qty = parseInt(lineItem.licenses);
+ const price = parseFloat(lineItemProduct.price).toFixed(2);
+ const amount = parseFloat(qty * price).toFixed(2);
+ lineItems.push([lineItemProduct.sku_name, lineItemProduct.sku_description, '', qty, price, amount]);
+ totalAmount += parseFloat(amount);
+ });
+
+ // Generates a random invoice number. You can replace with your own document ID method.
+ const invoiceNumber = Math.floor(100000 + Math.random() * 900000);
+
+ // Calulates dates.
+ const todaysDate = new Date().toDateString()
+ const dueDate = new Date(Date.now() + 1000 * 60 * 60 * 24 * DUE_DATE_NUM_DAYS).toDateString()
+
+ // Sets values in the template.
+ templateSheet.getRange('B10').setValue(customer.customer_name)
+ templateSheet.getRange('B11').setValue(customer.address)
+ templateSheet.getRange('F10').setValue(invoiceNumber)
+ templateSheet.getRange('F12').setValue(todaysDate)
+ templateSheet.getRange('F14').setValue(dueDate)
+ templateSheet.getRange(18, 2, lineItems.length, 6).setValues(lineItems);
+
+ // Cleans up and creates PDF.
+ SpreadsheetApp.flush();
+ Utilities.sleep(500); // Using to offset any potential latency in creating .pdf
+ const pdf = createPDF(ssId, templateSheet, `Invoice#${invoiceNumber}-${customer.customer_name}`);
+ return [invoiceNumber, todaysDate, customer.customer_name, customer.email, '', totalAmount, dueDate, pdf.getUrl(), 'No'];
+}
+
+/**
+* Resets the template sheet by clearing out customer data.
+* You use this to prepare for the next iteration or to view blank
+* the template for design.
+*
+* Called by createInvoiceForCustomer() or by the user via custom menu item.
+*/
+function clearTemplateSheet() {
+
+ const ss = SpreadsheetApp.getActiveSpreadsheet();
+ const templateSheet = ss.getSheetByName(INVOICE_TEMPLATE_SHEET_NAME);
+ // Clears existing data from the template.
+ const rngClear = templateSheet.getRangeList(['B10:B11', 'F10', 'F12', 'F14']).getRanges()
+ rngClear.forEach(function (cell) {
+ cell.clearContent();
+ });
+ // This sample only accounts for six rows of data 'B18:G24'. You can extend or make dynamic as necessary.
+ templateSheet.getRange(18, 2, 7, 6).clearContent();
+}
+
+/**
+ * Creates a PDF for the customer given sheet.
+ * @param {string} ssId - Id of the Google Spreadsheet
+ * @param {object} sheet - Sheet to be converted as PDF
+ * @param {string} pdfName - File name of the PDF being created
+ * @return {file object} PDF file as a blob
+ */
+function createPDF(ssId, sheet, pdfName) {
+ const fr = 0, fc = 0, lc = 9, lr = 27;
+ const url = "https://docs.google.com/spreadsheets/d/" + ssId + "/export" +
+ "?format=pdf&" +
+ "size=7&" +
+ "fzr=true&" +
+ "portrait=true&" +
+ "fitw=true&" +
+ "gridlines=false&" +
+ "printtitle=false&" +
+ "top_margin=0.5&" +
+ "bottom_margin=0.25&" +
+ "left_margin=0.5&" +
+ "right_margin=0.5&" +
+ "sheetnames=false&" +
+ "pagenum=UNDEFINED&" +
+ "attachment=true&" +
+ "gid=" + sheet.getSheetId() + '&' +
+ "r1=" + fr + "&c1=" + fc + "&r2=" + lr + "&c2=" + lc;
+
+ const params = { method: "GET", headers: { "authorization": "Bearer " + ScriptApp.getOAuthToken() } };
+ const blob = UrlFetchApp.fetch(url, params).getBlob().setName(pdfName + '.pdf');
+
+ // Gets the folder in Drive where the PDFs are stored.
+ const folder = getFolderByName_(OUTPUT_FOLDER_NAME);
+
+ const pdfFile = folder.createFile(blob);
+ return pdfFile;
+}
+
+
+/**
+ * Sends emails with PDF as an attachment.
+ * Checks/Sets 'Email Sent' column to 'Yes' to avoid resending.
+ *
+ * Called by user via custom menu item.
+ */
+function sendEmails() {
+ const ss = SpreadsheetApp.getActiveSpreadsheet();
+ const invoicesSheet = ss.getSheetByName(INVOICES_SHEET_NAME);
+ const invoicesData = invoicesSheet.getRange(1, 1, invoicesSheet.getLastRow(), invoicesSheet.getLastColumn()).getValues();
+ const keysI = invoicesData.splice(0, 1)[0];
+ const invoices = getObjects(invoicesData, createObjectKeys(keysI));
+ ss.toast('Emailing Invoices', APP_TITLE, 1);
+ invoices.forEach(function (invoice, index) {
+
+ if (invoice.email_sent != 'Yes') {
+ ss.toast(`Emailing Invoice for ${invoice.customer}`, APP_TITLE, 1);
+
+ const fileId = invoice.invoice_link.match(/[-\w]{25,}(?!.*[-\w]{25,})/)
+ const attachment = DriveApp.getFileById(fileId);
+
+ let recipient = invoice.email;
+ if (EMAIL_OVERRIDE) {
+ recipient = EMAIL_ADDRESS_OVERRIDE
+ }
+
+ GmailApp.sendEmail(recipient, EMAIL_SUBJECT, EMAIL_BODY, {
+ attachments: [attachment.getAs(MimeType.PDF)],
+ name: APP_TITLE
+ });
+ invoicesSheet.getRange(index + 2, 9).setValue('Yes');
+ }
+ });
+}
+
+/**
+ * Helper function that turns sheet data range into an object.
+ *
+ * @param {SpreadsheetApp.Sheet} sheet - Sheet to process
+ * Return {object} of a sheet's datarange as an object
+ */
+function dataRangeToObject(sheet) {
+ const dataRange = sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn()).getValues();
+ const keys = dataRange.splice(0, 1)[0];
+ return getObjects(dataRange, createObjectKeys(keys));
+}
+
+/**
+ * Utility function for mapping sheet data to objects.
+ */
+function getObjects(data, keys) {
+ let objects = [];
+ for (let i = 0; i < data.length; ++i) {
+ let object = {};
+ let hasData = false;
+ for (let j = 0; j < data[i].length; ++j) {
+ let cellData = data[i][j];
+ if (isCellEmpty(cellData)) {
+ continue;
+ }
+ object[keys[j]] = cellData;
+ hasData = true;
+ }
+ if (hasData) {
+ objects.push(object);
+ }
+ }
+ return objects;
+}
+// Creates object keys for column headers.
+function createObjectKeys(keys) {
+ return keys.map(function (key) {
+ return key.replace(/\W+/g, '_').toLowerCase();
+ });
+}
+// Returns true if the cell where cellData was read from is empty.
+function isCellEmpty(cellData) {
+ return typeof (cellData) == "string" && cellData == "";
+}
diff --git a/solutions/automations/generate-pdfs/Menu.js b/solutions/automations/generate-pdfs/Menu.js
new file mode 100644
index 000000000..00fad4705
--- /dev/null
+++ b/solutions/automations/generate-pdfs/Menu.js
@@ -0,0 +1,40 @@
+/**
+ * Copyright 2022 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @OnlyCurrentDoc
+ *
+ * The above comment specifies that this automation will only
+ * attempt to read or modify the spreadsheet this script is bound to.
+ * The authorization request message presented to users reflects the
+ * limited scope.
+ */
+
+/**
+ * Creates a custom menu in the Google Sheets UI when the document is opened.
+ *
+ * @param {object} e The event parameter for a simple onOpen trigger.
+ */
+function onOpen(e) {
+
+const menu = SpreadsheetApp.getUi().createMenu(APP_TITLE)
+ menu
+ .addItem('Process invoices', 'processDocuments')
+ .addItem('Send emails', 'sendEmails')
+ .addSeparator()
+ .addItem('Reset template', 'clearTemplateSheet')
+ .addToUi();
+}
\ No newline at end of file
diff --git a/solutions/automations/generate-pdfs/README.md b/solutions/automations/generate-pdfs/README.md
new file mode 100644
index 000000000..b259bedf7
--- /dev/null
+++ b/solutions/automations/generate-pdfs/README.md
@@ -0,0 +1,3 @@
+# Generate and send PDFs from Google Sheets
+
+See [developers.google.com](https://developers.google.com/apps-script/samples/automations/generate-pdfs) for additional details.
diff --git a/solutions/automations/generate-pdfs/Utilities.js b/solutions/automations/generate-pdfs/Utilities.js
new file mode 100644
index 000000000..4e7e60908
--- /dev/null
+++ b/solutions/automations/generate-pdfs/Utilities.js
@@ -0,0 +1,60 @@
+/**
+ * Copyright 2022 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Returns a Google Drive folder in the same location
+ * in Drive where the spreadsheet is located. First, it checks if the folder
+ * already exists and returns that folder. If the folder doesn't already
+ * exist, the script creates a new one. The folder's name is set by the
+ * "OUTPUT_FOLDER_NAME" variable from the Code.gs file.
+ *
+ * @param {string} folderName - Name of the Drive folder.
+ * @return {object} Google Drive Folder
+ */
+function getFolderByName_(folderName) {
+
+ // Gets the Drive Folder of where the current spreadsheet is located.
+ const ssId = SpreadsheetApp.getActiveSpreadsheet().getId();
+ const parentFolder = DriveApp.getFileById(ssId).getParents().next();
+
+ // Iterates the subfolders to check if the PDF folder already exists.
+ const subFolders = parentFolder.getFolders();
+ while (subFolders.hasNext()) {
+ let folder = subFolders.next();
+
+ // Returns the existing folder if found.
+ if (folder.getName() === folderName) {
+ return folder;
+ }
+ }
+ // Creates a new folder if one does not already exist.
+ return parentFolder.createFolder(folderName)
+ .setDescription(`Created by ${APP_TITLE} application to store PDF output files`);
+}
+
+/**
+ * Test function to run getFolderByName_.
+ * @prints a Google Drive FolderId.
+ */
+function test_getFolderByName() {
+
+ // Gets the PDF folder in Drive.
+ const folder = getFolderByName_(OUTPUT_FOLDER_NAME);
+
+ console.log(`Name: ${folder.getName()}\rID: ${folder.getId()}\rDescription: ${folder.getDescription()}`)
+ // To automatically delete test folder, uncomment the following code:
+ // folder.setTrashed(true);
+}
\ No newline at end of file
diff --git a/solutions/automations/generate-pdfs/appsscript.json b/solutions/automations/generate-pdfs/appsscript.json
new file mode 100644
index 000000000..3cf1d247d
--- /dev/null
+++ b/solutions/automations/generate-pdfs/appsscript.json
@@ -0,0 +1,7 @@
+{
+ "timeZone": "America/New_York",
+ "dependencies": {
+ },
+ "exceptionLogging": "STACKDRIVER",
+ "runtimeVersion": "V8"
+}
\ No newline at end of file
diff --git a/solutions/automations/import-csv-sheets/.clasp.json b/solutions/automations/import-csv-sheets/.clasp.json
new file mode 100644
index 000000000..f6b8887eb
--- /dev/null
+++ b/solutions/automations/import-csv-sheets/.clasp.json
@@ -0,0 +1 @@
+{"scriptId": "1ANsCqbcTeepCzPpAKRUSxavm-2bTtKhp6I-G530ddH315H-59LGofc6m"}
diff --git a/solutions/automations/import-csv-sheets/Code.js b/solutions/automations/import-csv-sheets/Code.js
new file mode 100644
index 000000000..2b89d8253
--- /dev/null
+++ b/solutions/automations/import-csv-sheets/Code.js
@@ -0,0 +1,191 @@
+// To learn more about this script, refer to the documentation:
+// https://developers.google.com/apps-script/samples/automations/import-csv-sheets
+
+/*
+Copyright 2022 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+/**
+ * This file contains the main functions that import data from CSV files into a Google Spreadsheet.
+ */
+
+// Application constants
+const APP_TITLE = 'Trigger-driven CSV import [App Script Sample]'; // Application name
+const APP_FOLDER = '[App Script sample] Import CSVs'; // Application primary folder
+const SOURCE_FOLDER = 'Inbound CSV Files'; // Folder for the update files.
+const PROCESSED_FOLDER = 'Processed CSV Files'; // Folder to hold processed files.
+const SHEET_REPORT_NAME = 'Import CSVs'; // Name of destination spreadsheet.
+
+// Application settings
+const CSV_HEADER_EXIST = true; // Set to true if CSV files have a header row, false if not.
+const HANDLER_FUNCTION = 'updateApplicationSheet'; // Function called by installable trigger to run data processing.
+
+/**
+ * Installs a time-driven trigger that runs daily to import CSVs into the main application spreadsheet.
+ * Prior to creating a new instance, removes any existing triggers to avoid duplication.
+ *
+ * Called by setupSample() or run directly setting up the application.
+ */
+function installTrigger() {
+
+ // Checks for an existing trigger to avoid creating duplicate instances.
+ // Removes existing if found.
+ const projectTriggers = ScriptApp.getProjectTriggers();
+ for (var i = 0; i < projectTriggers.length; i++) {
+ if (projectTriggers[i].getHandlerFunction() == HANDLER_FUNCTION) {
+ console.log(`Existing trigger with Handler Function of '${HANDLER_FUNCTION}' removed.`);
+ ScriptApp.deleteTrigger(projectTriggers[i]);
+ }
+ }
+ // Creates the new trigger.
+ let newTrigger = ScriptApp.newTrigger(HANDLER_FUNCTION)
+ .timeBased()
+ .atHour(23) // Runs at 11 PM in the time zone of this script.
+ .everyDays(1) // Runs once per day.
+ .create();
+ console.log(`New trigger with Handler Function of '${HANDLER_FUNCTION}' created.`);
+}
+
+/**
+ * Handler function called by the trigger created with the "installTrigger" function.
+ * Run this directly to execute the entire automation process of the application with a trigger.
+ *
+ * Process: Iterates through CSV files located in the source folder (SOURCE_FOLDER),
+ * and appends them to the end of destination spreadsheet (SHEET_REPORT_NAME).
+ * Successfully processed CSV files are moved to the processed folder (PROCESSED_FOLDER) to avoid duplication.
+ * Sends summary email with status of the import.
+ */
+function updateApplicationSheet() {
+
+ // Gets application & supporting folders.
+ const folderAppPrimary = getApplicationFolder_(APP_FOLDER);
+ const folderSource = getFolder_(SOURCE_FOLDER);
+ const folderProcessed = getFolder_(PROCESSED_FOLDER);
+
+ // Gets the application's destination spreadsheet {Spreadsheet object}
+ let objSpreadSheet = getSpreadSheet_(SHEET_REPORT_NAME, folderAppPrimary)
+
+ // Creates arrays to track every CSV file, categorized as processed sucessfully or not.
+ let filesProcessed = [];
+ let filesNotProcessed = [];
+
+ // Gets all CSV files found in the source folder.
+ let cvsFiles = folderSource.getFilesByType(MimeType.CSV);
+
+ // Iterates through each CSV file.
+ while (cvsFiles.hasNext()) {
+
+ let csvFile = cvsFiles.next();
+ let isSuccess;
+
+ // Appends the unprocessed CSV data into the Google Sheets spreadsheet.
+ isSuccess = processCsv_(objSpreadSheet, csvFile);
+
+ if (isSuccess) {
+ // Moves the processed file to the processed folder to prevent future duplicate data imports.
+ csvFile.moveTo(folderProcessed);
+ // Logs the successfully processed file to the filesProcessed array.
+ filesProcessed.push(csvFile.getName());
+ console.log(`Successfully processed: ${csvFile.getName()}`);
+
+ } else if (!isSuccess) {
+ // Doesn't move the unsuccesfully processed file so that it can be corrected and reprocessed later.
+ // Logs the unsuccessfully processed file to the filesNotProcessed array.
+ filesNotProcessed.push(csvFile.getName());
+ console.log(`Not processed: ${csvFile.getName()}`);
+ }
+ }
+
+ // Prepares summary email.
+ // Gets variables to link to this Apps Script project.
+ const scriptId = ScriptApp.getScriptId();
+ const scriptUrl = DriveApp.getFileById(scriptId).getUrl();
+ const scriptName = DriveApp.getFileById(scriptId).getName();
+
+ // Gets variables to link to the main application spreadsheet.
+ const sheetUrl = objSpreadSheet.getUrl()
+ const sheetName = objSpreadSheet.getName()
+
+ // Gets user email and timestamp.
+ const emailTo = Session.getEffectiveUser().getEmail();
+ const timestamp = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyy-MM-dd HH:mm:ss zzzz");
+
+ // Prepares lists and counts of processed CSV files.
+ let processedList = "";
+ const processedCount = filesProcessed.length
+ for (const processed of filesProcessed) {
+ processedList += processed + ' '
+ };
+
+ const unProcessedCount = filesNotProcessed.length
+ let unProcessedList = "";
+ for (const unProcessed of filesNotProcessed) {
+ unProcessedList += unProcessed + '\n'
+ };
+
+ // Assembles email body as html.
+ const eMailBody = `${APP_TITLE} ran an automated process at ${timestamp}.
` +
+ `Files successfully updated: ${processedCount} ` +
+ `${processedList} ` +
+ `Files not updated: ${unProcessedCount} ` +
+ `${unProcessedList} ` +
+ ` View all updates in the Google Sheets spreadsheet ` +
+ `${sheetName}. ` +
+ ` ************* ` +
+ ` This email was generated by Google Apps Script. ` +
+ `To learn more about this application or make changes, open the script project below: ` +
+ `${scriptName}`
+
+ MailApp.sendEmail({
+ to: emailTo,
+ subject: `Automated email from ${APP_TITLE}`,
+ htmlBody: eMailBody
+ });
+ console.log(`Email sent to ${emailTo}`);
+}
+
+/**
+ * Parses CSV data into an array and appends it after the last row in the destination spreadsheet.
+ *
+ * @return {boolean} true if the update is successful, false if unexpected errors occur.
+ */
+function processCsv_(objSpreadSheet, csvFile) {
+
+ try {
+ // Gets the first sheet of the destination spreadsheet.
+ let sheet = objSpreadSheet.getSheets()[0];
+
+ // Parses CSV file into data array.
+ let data = Utilities.parseCsv(csvFile.getBlob().getDataAsString());
+
+ // Omits header row if application variable CSV_HEADER_EXIST is set to 'true'.
+ if (CSV_HEADER_EXIST) {
+ data.splice(0, 1);
+ }
+ // Gets the row and column coordinates for next available range in the spreadsheet.
+ let startRow = sheet.getLastRow() + 1;
+ let startCol = 1;
+ // Determines the incoming data size.
+ let numRows = data.length;
+ let numColumns = data[0].length;
+
+ // Appends data into the sheet.
+ sheet.getRange(startRow, startCol, numRows, numColumns).setValues(data);
+ return true; // Success.
+
+ } catch {
+ return false; // Failure. Checks for CSV data file error.
+ }
+}
diff --git a/solutions/automations/import-csv-sheets/README.md b/solutions/automations/import-csv-sheets/README.md
new file mode 100644
index 000000000..1334e63f2
--- /dev/null
+++ b/solutions/automations/import-csv-sheets/README.md
@@ -0,0 +1,3 @@
+# Import CSV data to a spreadsheet
+
+See [developers.google.com](https://developers.google.com/apps-script/samples/automations/import-csv-sheets) for additional details.
diff --git a/solutions/automations/import-csv-sheets/SampleData.js b/solutions/automations/import-csv-sheets/SampleData.js
new file mode 100644
index 000000000..4fb3afec1
--- /dev/null
+++ b/solutions/automations/import-csv-sheets/SampleData.js
@@ -0,0 +1,190 @@
+/**
+ * Copyright 2022 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This file contains functions to access headings and data for sample files.
+ *
+ * Sample data is stored in the variable SAMPLE_DATA.
+ */
+
+// Fictitious sample data.
+const SAMPLE_DATA = {
+ "headings": [
+ "PropertyName",
+ "LeaseID",
+ "LeaseLocation",
+ "OwnerName",
+ "SquareFootage",
+ "RenewDate",
+ "LastAmount",
+ "LastPaymentDate",
+ "Revenue"
+ ],
+ "csvFiles": [
+ {
+ "name": "Sample One.CSV",
+ "rows": [
+ {
+ "PropertyName": "The Modern Building",
+ "LeaseID": "271312",
+ "LeaseLocation": "Mountain View CA 94045",
+ "OwnerName": "Yuri",
+ "SquareFootage": "17500",
+ "RenewDate": "12/15/2022",
+ "LastAmount": "100000",
+ "LastPaymentDate": "3/01/2022",
+ "Revenue": "12000"
+ },
+ {
+ "PropertyName": "Garage @ 45",
+ "LeaseID": "271320",
+ "LeaseLocation": "Mountain View CA 94045",
+ "OwnerName": "Luka",
+ "SquareFootage": "1000",
+ "RenewDate": "6/2/2022",
+ "LastAmount": "50000",
+ "LastPaymentDate": "4/01/2022",
+ "Revenue": "20000"
+ },
+ {
+ "PropertyName": "Office Park Deluxe",
+ "LeaseID": "271301",
+ "LeaseLocation": "Mountain View CA 94045",
+ "OwnerName": "Sasha",
+ "SquareFootage": "5000",
+ "RenewDate": "6/2/2022",
+ "LastAmount": "25000",
+ "LastPaymentDate": "4/01/2022",
+ "Revenue": "1200"
+ }
+ ]
+ },
+ {
+ "name": "Sample Two.CSV",
+ "rows": [
+ {
+ "PropertyName": "Tours Jumelles Minuscules",
+ "LeaseID": "271260",
+ "LeaseLocation": "8 Rue du Nom Fictif 341 Paris",
+ "OwnerName": "Lucian",
+ "SquareFootage": "1000000",
+ "RenewDate": "7/14/2022",
+ "LastAmount": "1250000",
+ "LastPaymentDate": "5/01/2022",
+ "Revenue": "77777"
+ },
+ {
+ "PropertyName": "Barraca da Praia",
+ "LeaseID": "271281",
+ "LeaseLocation": "Avenida da Pastelaria 1903 Lisbon 1229-076",
+ "OwnerName": "Raha",
+ "SquareFootage": "1000",
+ "RenewDate": "6/2/2022",
+ "LastAmount": "50000",
+ "LastPaymentDate": "4/01/2022",
+ "Revenue": "20000"
+ }
+ ]
+ },
+ {
+ "name": "Sample Three.CSV",
+ "rows": [
+ {
+ "PropertyName": "Round Building in the Square",
+ "LeaseID": "371260",
+ "LeaseLocation": "8 Rue du Nom Fictif 341 Paris",
+ "OwnerName": "Charlie",
+ "SquareFootage": "75000",
+ "RenewDate": "8/1/2022",
+ "LastAmount": "250000",
+ "LastPaymentDate": "6/01/2022",
+ "Revenue": "22222"
+ },
+ {
+ "PropertyName": "Square Building in the Round",
+ "LeaseID": "371281",
+ "LeaseLocation": "Avenida da Pastelaria 1903 Lisbon 1229-076",
+ "OwnerName": "Lee",
+ "SquareFootage": "10000",
+ "RenewDate": "6/2/2022",
+ "LastAmount": "5000",
+ "LastPaymentDate": "4/01/2022",
+ "Revenue": "1800"
+ }
+ ]
+ }
+ ]
+}
+
+
+/**
+ * Returns headings for use in destination spreadsheet and CSV files.
+ * @return {string[][]} array of each column heading as string.
+ */
+function getHeadings() {
+ let headings = [[]];
+ for (let i in SAMPLE_DATA.headings)
+ headings[0].push(SAMPLE_DATA.headings[i]);
+ return (headings)
+}
+
+/**
+ * Returns CSV file names and content to create sample CSV files.
+ * @return {object[]} {"file": ["name","csv"]}
+ */
+function getCSVFilesData() {
+
+ let files = [];
+
+ // Gets headings once - same for all files/rows.
+ let csvHeadings = "";
+ for (let i in SAMPLE_DATA.headings)
+ csvHeadings += (SAMPLE_DATA.headings[i] + ',');
+
+ // Gets data for each file by rows.
+ for (let i in SAMPLE_DATA.csvFiles) {
+ let sampleCSV = "";
+ sampleCSV += csvHeadings;
+ let fileName = SAMPLE_DATA.csvFiles[i].name
+ for (let j in SAMPLE_DATA.csvFiles[i].rows) {
+ sampleCSV += '\n'
+ for (let k in SAMPLE_DATA.csvFiles[i].rows[j]) {
+ sampleCSV += SAMPLE_DATA.csvFiles[i].rows[j][k] + ','
+ }
+ }
+ files.push({ name: fileName, csv: sampleCSV })
+ }
+ return (files)
+}
+
+/*
+ * Checks data functions are working as necessary.
+ */
+function test_getHeadings() {
+ let h = getHeadings()
+ console.log(h);
+ console.log(h[0].length);
+}
+
+function test_getCSVFilesData() {
+ const csvFiles = getCSVFilesData();
+ console.log(csvFiles)
+
+ for (const file of csvFiles) {
+ console.log(file.name)
+ console.log(file.csv)
+ }
+}
\ No newline at end of file
diff --git a/solutions/automations/import-csv-sheets/SetupSample.js b/solutions/automations/import-csv-sheets/SetupSample.js
new file mode 100644
index 000000000..f7670293e
--- /dev/null
+++ b/solutions/automations/import-csv-sheets/SetupSample.js
@@ -0,0 +1,111 @@
+/**
+ * Copyright 2022 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This file contains functions that set up the folders and sample files used to demo the application.
+ *
+ * Sample data for the application is stored in the SampleData.gs file.
+ */
+
+// Global variables for sample setup.
+const INCLUDE_SAMPLE_DATA_FILES = true; // Set to true to create sample data files, false to skip.
+
+/**
+ * Runs the setup for the sample.
+ * 1) Creates the application folder and subfolders for unprocessed/processed CSV files.
+ * from global variables APP_FOLDER | SOURCE_FOLDER | PROCESSED_FOLDER
+ * 2) Creates the sample Sheets spreadsheet in the application folder.
+ * from global variable SHEET_REPORT_NAME
+ * 3) Creates CSV files from sample data in the unprocessed files folder.
+ * from variable SAMPLE_DATA in SampleData.gs.
+ * 4) Creates an installable trigger to run process automatically at a specified time interval.
+ */
+function setupSample() {
+
+ console.log(`Application setup for: ${APP_TITLE}`)
+
+ // Creates application folder.
+ const folderAppPrimary = getApplicationFolder_(APP_FOLDER);
+ // Creates supporting folders.
+ const folderSource = getFolder_(SOURCE_FOLDER);
+ const folderProcessed = getFolder_(PROCESSED_FOLDER);
+
+ console.log(`Application folders: ${folderAppPrimary.getName()}, ${folderSource.getName()}, ${folderProcessed.getName()}`)
+
+ if (INCLUDE_SAMPLE_DATA_FILES) {
+
+ // Sets up primary destination spreadsheet
+ const sheet = setupPrimarySpreadsheet_(folderAppPrimary);
+
+ // Gets the CSV files data - refer to the SampleData.gs file to view.
+ const csvFiles = getCSVFilesData();
+
+ // Processes each CSV file.
+ for (const file of csvFiles) {
+ // Creates CSV file in source folder if it doesn't exist.
+ if (!fileExists_(file.name, folderSource)) {
+ let csvFileId = DriveApp.createFile(file.name, file.csv, MimeType.CSV);
+ console.log(`Created Sample CSV: ${file.name}`)
+ csvFileId.moveTo(folderSource);
+ }
+ }
+ }
+ // Installs (or recreates) project trigger
+ installTrigger()
+
+ console.log(`Setup completed for: ${APP_TITLE}`)
+}
+
+/**
+ *
+ */
+function setupPrimarySpreadsheet_(folderAppPrimary) {
+
+ // Creates the report destination spreadsheet if doesn't exist.
+ if (!fileExists_(SHEET_REPORT_NAME, folderAppPrimary)) {
+
+ // Creates new destination spreadsheet (report) with cell size of 20 x 10.
+ const sheet = SpreadsheetApp.create(SHEET_REPORT_NAME, 20, 10);
+
+ // Adds the sample data headings.
+ let sheetHeadings = getHeadings();
+ sheet.getSheets()[0].getRange(1, 1, 1, sheetHeadings[0].length).setValues(sheetHeadings);
+ SpreadsheetApp.flush();
+ // Moves to primary application root folder.
+ DriveApp.getFileById(sheet.getId()).moveTo(folderAppPrimary)
+
+ console.log(`Created file: ${SHEET_REPORT_NAME} In folder: ${folderAppPrimary.getName()}.`)
+ return sheet;
+ }
+}
+
+/**
+ * Moves sample content to Drive trash & uninstalls trigger.
+ * This function removes all folders and content related to this application.
+ */
+function removeSample() {
+ getApplicationFolder_(APP_FOLDER).setTrashed(true);
+ console.log(`'${APP_FOLDER}' contents have been moved to Drive Trash folder.`)
+
+ // Removes existing trigger if found.
+ const projectTriggers = ScriptApp.getProjectTriggers();
+ for (var i = 0; i < projectTriggers.length; i++) {
+ if (projectTriggers[i].getHandlerFunction() == HANDLER_FUNCTION) {
+ console.log(`Existing trigger with handler function of '${HANDLER_FUNCTION}' removed.`);
+ ScriptApp.deleteTrigger(projectTriggers[i]);
+ }
+ }
+}
\ No newline at end of file
diff --git a/solutions/automations/import-csv-sheets/Utilities.js b/solutions/automations/import-csv-sheets/Utilities.js
new file mode 100644
index 000000000..f37b81a20
--- /dev/null
+++ b/solutions/automations/import-csv-sheets/Utilities.js
@@ -0,0 +1,142 @@
+/**
+ * Copyright 2022 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * This file contains utility functions that work with application's folder and files.
+ */
+
+/**
+ * Gets application destination spreadsheet from a given folder
+ * Returns new sample version if orignal is not found.
+ *
+ * @param {string} fileName - Name of the file to test for.
+ * @param {object} objFolder - Folder object in which to search.
+ * @return {object} Spreadsheet object.
+ */
+function getSpreadSheet_(fileName, objFolder) {
+
+ let files = objFolder.getFilesByName(fileName);
+
+ while (files.hasNext()) {
+ let file = files.next();
+ let fileId = file.getId();
+
+ const existingSpreadsheet = SpreadsheetApp.openById(fileId);
+ return existingSpreadsheet;
+ }
+
+ // If application destination spreadsheet is missing, creates a new sample version.
+ const folderAppPrimary = getApplicationFolder_(APP_FOLDER);
+ const sampleSheet = setupPrimarySpreadsheet_(folderAppPrimary);
+ return sampleSheet;
+}
+
+/**
+ * Tests if a file exists within a given folder.
+ *
+ * @param {string} fileName - Name of the file to test for.
+ * @param {object} objFolder - Folder object in which to search.
+ * @return {boolean} true if found in folder, false if not.
+ */
+function fileExists_(fileName, objFolder) {
+
+ let files = objFolder.getFilesByName(fileName);
+
+ while (files.hasNext()) {
+ let file = files.next();
+ console.log(`${file.getName()} already exists.`)
+ return true;
+ }
+ return false;
+}
+
+/**
+ * Returns folder named in folderName parameter.
+ * Checks if folder already exists, creates it if it doesn't.
+ *
+ * @param {string} folderName - Name of the Drive folder.
+ * @return {object} Google Drive Folder
+ */
+function getFolder_(folderName) {
+
+ // Gets the primary folder for the application.
+ const parentFolder = getApplicationFolder_();
+
+ // Iterates subfolders to check if folder already exists.
+ const subFolders = parentFolder.getFolders();
+ while (subFolders.hasNext()) {
+ let folder = subFolders.next();
+
+ // Returns the existing folder if found.
+ if (folder.getName() === folderName) {
+ return folder;
+ }
+ }
+ // Creates a new folder if one doesn't already exist.
+ return parentFolder.createFolder(folderName)
+ .setDescription(`Supporting folder created by ${APP_TITLE}.`);
+}
+
+/**
+ * Returns the primary folder as named by the APP_FOLDER variable in the Code.gs file.
+ * Checks if folder already exists to avoid duplication.
+ * Creates new instance if existing folder not found.
+ *
+ * @return {object} Google Drive Folder
+ */
+function getApplicationFolder_() {
+
+ // Gets root folder, currently set to 'My Drive'
+ const parentFolder = DriveApp.getRootFolder();
+
+ // Iterates through the subfolders to check if folder already exists.
+ const subFolders = parentFolder.getFolders();
+ while (subFolders.hasNext()) {
+ let folder = subFolders.next();
+
+ // Returns the existing folder if found.
+ if (folder.getName() === APP_FOLDER) {
+ return folder;
+ }
+ }
+ // Creates a new folder if one doesn't already exist.
+ return parentFolder.createFolder(APP_FOLDER)
+ .setDescription(`Main application folder created by ${APP_TITLE}.`);
+}
+
+/**
+ * Tests getApplicationFolder_ and getFolder_
+ * @logs details of created Google Drive folder.
+ */
+function test_getFolderByName() {
+
+ let folder = getApplicationFolder_()
+ console.log(`Name: ${folder.getName()}\rID: ${folder.getId()}\rURL:${folder.getUrl()}\rDescription: ${folder.getDescription()}`)
+ // Uncomment the following to automatically delete test folder.
+ // folder.setTrashed(true);
+
+ folder = getFolder_(SOURCE_FOLDER);
+ console.log(`Name: ${folder.getName()}\rID: ${folder.getId()}\rURL:${folder.getUrl()}\rDescription: ${folder.getDescription()}`)
+ // Uncomment the following to automatically delete test folder.
+ // folder.setTrashed(true);
+
+ folder = getFolder_(PROCESSED_FOLDER);
+ console.log(`Name: ${folder.getName()}\rID: ${folder.getId()}\rURL:${folder.getUrl()}\rDescription: ${folder.getDescription()}`)
+ // Uncomment the following to automatically delete test folder.
+ // folder.setTrashed(true);
+
+
+}
\ No newline at end of file
diff --git a/solutions/automations/import-csv-sheets/appsscript.json b/solutions/automations/import-csv-sheets/appsscript.json
new file mode 100644
index 000000000..3cf1d247d
--- /dev/null
+++ b/solutions/automations/import-csv-sheets/appsscript.json
@@ -0,0 +1,7 @@
+{
+ "timeZone": "America/New_York",
+ "dependencies": {
+ },
+ "exceptionLogging": "STACKDRIVER",
+ "runtimeVersion": "V8"
+}
\ No newline at end of file
diff --git a/solutions/automations/mail-merge/.clasp.json b/solutions/automations/mail-merge/.clasp.json
new file mode 100644
index 000000000..7f25c6014
--- /dev/null
+++ b/solutions/automations/mail-merge/.clasp.json
@@ -0,0 +1 @@
+{"scriptId": "1evL25lW9fLN43j6gGBJWtLq4GncLkdgoxxSVCawc8dWNoLoravNebAih"}
diff --git a/solutions/automations/mail-merge/Code.js b/solutions/automations/mail-merge/Code.js
new file mode 100644
index 000000000..7784dd31f
--- /dev/null
+++ b/solutions/automations/mail-merge/Code.js
@@ -0,0 +1,210 @@
+// To learn how to use this script, refer to the documentation:
+// https://developers.google.com/apps-script/samples/automations/mail-merge
+
+/*
+Copyright 2022 Martin Hawksey
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+/**
+ * @OnlyCurrentDoc
+*/
+
+/**
+ * Change these to match the column names you are using for email
+ * recipient addresses and email sent column.
+*/
+const RECIPIENT_COL = "Recipient";
+const EMAIL_SENT_COL = "Email Sent";
+
+/**
+ * Creates the menu item "Mail Merge" for user to run scripts on drop-down.
+ */
+function onOpen() {
+ const ui = SpreadsheetApp.getUi();
+ ui.createMenu('Mail Merge')
+ .addItem('Send Emails', 'sendEmails')
+ .addToUi();
+}
+
+/**
+ * Sends emails from sheet data.
+ * @param {string} subjectLine (optional) for the email draft message
+ * @param {Sheet} sheet to read data from
+*/
+function sendEmails(subjectLine, sheet=SpreadsheetApp.getActiveSheet()) {
+ // option to skip browser prompt if you want to use this code in other projects
+ if (!subjectLine){
+ subjectLine = Browser.inputBox("Mail Merge",
+ "Type or copy/paste the subject line of the Gmail " +
+ "draft message you would like to mail merge with:",
+ Browser.Buttons.OK_CANCEL);
+
+ if (subjectLine === "cancel" || subjectLine == ""){
+ // If no subject line, finishes up
+ return;
+ }
+ }
+
+ // Gets the draft Gmail message to use as a template
+ const emailTemplate = getGmailTemplateFromDrafts_(subjectLine);
+
+ // Gets the data from the passed sheet
+ const dataRange = sheet.getDataRange();
+ // Fetches displayed values for each row in the Range HT Andrew Roberts
+ // https://mashe.hawksey.info/2020/04/a-bulk-email-mail-merge-with-gmail-and-google-sheets-solution-evolution-using-v8/#comment-187490
+ // @see https://developers.google.com/apps-script/reference/spreadsheet/range#getdisplayvalues
+ const data = dataRange.getDisplayValues();
+
+ // Assumes row 1 contains our column headings
+ const heads = data.shift();
+
+ // Gets the index of the column named 'Email Status' (Assumes header names are unique)
+ // @see http://ramblings.mcpher.com/Home/excelquirks/gooscript/arrayfunctions
+ const emailSentColIdx = heads.indexOf(EMAIL_SENT_COL);
+
+ // Converts 2d array into an object array
+ // See https://stackoverflow.com/a/22917499/1027723
+ // For a pretty version, see https://mashe.hawksey.info/?p=17869/#comment-184945
+ const obj = data.map(r => (heads.reduce((o, k, i) => (o[k] = r[i] || '', o), {})));
+
+ // Creates an array to record sent emails
+ const out = [];
+
+ // Loops through all the rows of data
+ obj.forEach(function(row, rowIdx){
+ // Only sends emails if email_sent cell is blank and not hidden by a filter
+ if (row[EMAIL_SENT_COL] == ''){
+ try {
+ const msgObj = fillInTemplateFromObject_(emailTemplate.message, row);
+
+ // See https://developers.google.com/apps-script/reference/gmail/gmail-app#sendEmail(String,String,String,Object)
+ // If you need to send emails with unicode/emoji characters change GmailApp for MailApp
+ // Uncomment advanced parameters as needed (see docs for limitations)
+ GmailApp.sendEmail(row[RECIPIENT_COL], msgObj.subject, msgObj.text, {
+ htmlBody: msgObj.html,
+ // bcc: 'a.bcc@email.com',
+ // cc: 'a.cc@email.com',
+ // from: 'an.alias@email.com',
+ // name: 'name of the sender',
+ // replyTo: 'a.reply@email.com',
+ // noReply: true, // if the email should be sent from a generic no-reply email address (not available to gmail.com users)
+ attachments: emailTemplate.attachments,
+ inlineImages: emailTemplate.inlineImages
+ });
+ // Edits cell to record email sent date
+ out.push([new Date()]);
+ } catch(e) {
+ // modify cell to record error
+ out.push([e.message]);
+ }
+ } else {
+ out.push([row[EMAIL_SENT_COL]]);
+ }
+ });
+
+ // Updates the sheet with new data
+ sheet.getRange(2, emailSentColIdx+1, out.length).setValues(out);
+
+ /**
+ * Get a Gmail draft message by matching the subject line.
+ * @param {string} subject_line to search for draft message
+ * @return {object} containing the subject, plain and html message body and attachments
+ */
+ function getGmailTemplateFromDrafts_(subject_line){
+ try {
+ // get drafts
+ const drafts = GmailApp.getDrafts();
+ // filter the drafts that match subject line
+ const draft = drafts.filter(subjectFilter_(subject_line))[0];
+ // get the message object
+ const msg = draft.getMessage();
+
+ // Handles inline images and attachments so they can be included in the merge
+ // Based on https://stackoverflow.com/a/65813881/1027723
+ // Gets all attachments and inline image attachments
+ const allInlineImages = draft.getMessage().getAttachments({includeInlineImages: true,includeAttachments:false});
+ const attachments = draft.getMessage().getAttachments({includeInlineImages: false});
+ const htmlBody = msg.getBody();
+
+ // Creates an inline image object with the image name as key
+ // (can't rely on image index as array based on insert order)
+ const img_obj = allInlineImages.reduce((obj, i) => (obj[i.getName()] = i, obj) ,{});
+
+ //Regexp searches for all img string positions with cid
+ const imgexp = RegExp(']+>', 'g');
+ const matches = [...htmlBody.matchAll(imgexp)];
+
+ //Initiates the allInlineImages object
+ const inlineImagesObj = {};
+ // built an inlineImagesObj from inline image matches
+ matches.forEach(match => inlineImagesObj[match[1]] = img_obj[match[2]]);
+
+ return {message: {subject: subject_line, text: msg.getPlainBody(), html:htmlBody},
+ attachments: attachments, inlineImages: inlineImagesObj };
+ } catch(e) {
+ throw new Error("Oops - can't find Gmail draft");
+ }
+
+ /**
+ * Filter draft objects with the matching subject linemessage by matching the subject line.
+ * @param {string} subject_line to search for draft message
+ * @return {object} GmailDraft object
+ */
+ function subjectFilter_(subject_line){
+ return function(element) {
+ if (element.getMessage().getSubject() === subject_line) {
+ return element;
+ }
+ }
+ }
+ }
+
+ /**
+ * Fill template string with data object
+ * @see https://stackoverflow.com/a/378000/1027723
+ * @param {string} template string containing {{}} markers which are replaced with data
+ * @param {object} data object used to replace {{}} markers
+ * @return {object} message replaced with data
+ */
+ function fillInTemplateFromObject_(template, data) {
+ // We have two templates one for plain text and the html body
+ // Stringifing the object means we can do a global replace
+ let template_string = JSON.stringify(template);
+
+ // Token replacement
+ template_string = template_string.replace(/{{[^{}]+}}/g, key => {
+ return escapeData_(data[key.replace(/[{}]+/g, "")] || "");
+ });
+ return JSON.parse(template_string);
+ }
+
+ /**
+ * Escape cell data to make JSON safe
+ * @see https://stackoverflow.com/a/9204218/1027723
+ * @param {string} str to escape JSON special characters from
+ * @return {string} escaped string
+ */
+ function escapeData_(str) {
+ return str
+ .replace(/[\\]/g, '\\\\')
+ .replace(/[\"]/g, '\\\"')
+ .replace(/[\/]/g, '\\/')
+ .replace(/[\b]/g, '\\b')
+ .replace(/[\f]/g, '\\f')
+ .replace(/[\n]/g, '\\n')
+ .replace(/[\r]/g, '\\r')
+ .replace(/[\t]/g, '\\t');
+ };
+}
diff --git a/solutions/automations/mail-merge/README.md b/solutions/automations/mail-merge/README.md
new file mode 100644
index 000000000..82e2b8f98
--- /dev/null
+++ b/solutions/automations/mail-merge/README.md
@@ -0,0 +1,3 @@
+# Create a mail merge with Gmail & Google Sheets
+
+See [developers.google.com](https://developers.google.com/apps-script/samples/automations/mail-merge) for additional details.
diff --git a/solutions/automations/mail-merge/appsscript.json b/solutions/automations/mail-merge/appsscript.json
new file mode 100644
index 000000000..3cf1d247d
--- /dev/null
+++ b/solutions/automations/mail-merge/appsscript.json
@@ -0,0 +1,7 @@
+{
+ "timeZone": "America/New_York",
+ "dependencies": {
+ },
+ "exceptionLogging": "STACKDRIVER",
+ "runtimeVersion": "V8"
+}
\ No newline at end of file
diff --git a/solutions/automations/news-sentiment/.clasp.json b/solutions/automations/news-sentiment/.clasp.json
new file mode 100644
index 000000000..80b47c971
--- /dev/null
+++ b/solutions/automations/news-sentiment/.clasp.json
@@ -0,0 +1 @@
+{"scriptId":"1KHPvTOwE2pd2myZmvX0mbsp8SPlhJBFotNCwflZiP01xmTasNfibG4zl"}
\ No newline at end of file
diff --git a/solutions/automations/news-sentiment/Code.js b/solutions/automations/news-sentiment/Code.js
new file mode 100644
index 000000000..7d084f907
--- /dev/null
+++ b/solutions/automations/news-sentiment/Code.js
@@ -0,0 +1,256 @@
+// To learn how to use this script, refer to the documentation:
+// https://developers.google.com/apps-script/samples/automations/news-sentiment
+
+/*
+Copyright 2022 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Global variables
+const googleAPIKey = 'YOUR_GOOGLE_API_KEY';
+const newsApiKey = 'YOUR_NEWS_API_KEY';
+const apiEndPointHdr = 'https://newsapi.org/v2/everything?q=';
+const happyFace =
+ '=IMAGE(\"https://cdn.pixabay.com/photo/2016/09/01/08/24/smiley-1635449_1280.png\")';
+const mehFace =
+ '=IMAGE(\"https://cdn.pixabay.com/photo/2016/09/01/08/24/smiley-1635450_1280.png\")';
+const sadFace =
+ '=IMAGE(\"https://cdn.pixabay.com/photo/2016/09/01/08/25/smiley-1635454_1280.png\")';
+const happyColor = '#44f83d';
+const mehColor = '#f7f6cc';
+const sadColor = '#ff3c3d';
+const fullsheet = 'A2:D25';
+const sentimentCols = 'B2:D25';
+const articleMax = 20;
+const threshold = 0.3;
+
+let headlines = [];
+let rows = null;
+let rowValues = null;
+let topic = null;
+let bottomRow = 0;
+let ds = null;
+let ss = null;
+let headerRow = null;
+let sentimentCol = null;
+let headlineCol = null;
+let scoreCol = null;
+
+/**
+ * Creates menu in the Google Sheets spreadsheet when the spreadsheet is opened.
+ *
+ */
+function onOpen() {
+ let ui = SpreadsheetApp.getUi();
+ ui.createMenu('News Headlines Sentiments')
+ .addItem('Analyze News Headlines...', 'showNewsPrompt')
+ .addToUi();
+}
+
+/**
+ * Prompts user to enter a new headline topic.
+ * Calls main function AnalyzeHeadlines with entered topic.
+ */
+function showNewsPrompt() {
+ //Initializes global variables
+ ss = SpreadsheetApp.getActiveSpreadsheet();
+ ds = ss.getSheetByName('Sheet1');
+ headerRow = ds.getDataRange().getValues()[0];
+ sentimentCol = headerRow.indexOf('Sentiment');
+ headlineCol = headerRow.indexOf('Headlines');
+ scoreCol = headerRow.indexOf('Score');
+
+ // Builds Menu
+ let ui = SpreadsheetApp.getUi();
+ let result = ui.prompt(
+ 'Enter news topic:',
+ ui.ButtonSet.OK_CANCEL);
+
+ // Processes the user's response.
+ let button = result.getSelectedButton();
+ topic = result.getResponseText();
+ if (button == ui.Button.OK) {
+ analyzeNewsHeadlines();
+ } else if (button == ui.Button.CANCEL) {
+ // Shows alert if user clicked "Cancel."
+ ui.alert('News topic not selected!');
+ }
+}
+
+/**
+ * For each headline cell, calls the Natural Language API to get general sentiment and then updates
+ * the sentiment response column.
+ */
+function analyzeNewsHeadlines() {
+ // Clears and reformats the sheet
+ reformatSheet();
+
+ // Gets the headlines array
+ headlines = getHeadlinesArray();
+
+ // Syncs the headlines array to the sheet using a single setValues call
+ if (headlines.length > 0){
+ ds.getRange(2, 1, headlines.length, headlineCol+1).setValues(headlines);
+ // Set global rowValues
+ rows = ds.getDataRange();
+ rowValues = rows.getValues();
+ getSentiments();
+ } else {
+ ss.toast("No headlines returned for topic: " + topic + '!');
+ }
+}
+
+/**
+ * Fetches current headlines from the Free News API
+ */
+function getHeadlinesArray() {
+ // Fetches headlines for a given topic
+ let hdlnsResp = [];
+ let encodedtopic = encodeURIComponent(topic);
+ ss.toast("Getting headlines for: " + topic);
+ let response = UrlFetchApp.fetch(apiEndPointHdr + encodedtopic + '&apiKey=' +
+ newsApiKey);
+ let results = JSON.parse(response);
+ let articles = results["articles"];
+
+ for (let i = 0; i < articles.length && i < articleMax; i++) {
+ let newsStory = articles[i]['title'];
+ if (articles[i]['description'] !== null) {
+ newsStory += ': ' + articles[i]['description'];
+ }
+ // Scrubs newsStory of invalid characters
+ newsStory = scrub(newsStory);
+
+ // Constructs hdlnsResp as a 2d array. This simplifies syncing to the sheet.
+ hdlnsResp.push(new Array(newsStory));
+ }
+
+ return hdlnsResp;
+}
+
+/**
+ * For each article cell, calls the Natural Language API to get general sentiment and then updates
+ * the sentiment response columns.
+ */
+function getSentiments() {
+ ss.toast('Analyzing the headline sentiments...');
+
+ let articleCount = rows.getNumRows() - 1;
+ let avg = 0;
+
+ // Gets sentiment for each row
+ for (let i = 1; i <= articleCount; i++) {
+ let headlineCell = rowValues[i][headlineCol];
+ if (headlineCell) {
+ let sentimentData = retrieveSentiment(headlineCell);
+ let result = sentimentData['documentSentiment']['score'];
+ avg += result;
+ ds.getRange(i + 1, sentimentCol + 1).setBackgroundColor(getColor(result));
+ ds.getRange(i + 1, sentimentCol + 1).setValue(getFace(result));
+ ds.getRange(i + 1, scoreCol + 1).setValue(result);
+ }
+ }
+ let avgDecimal = (avg / articleCount).toFixed(2);
+
+ // Shows news topic and average face, color and sentiment value.
+ bottomRow = articleCount + 3;
+ ds.getRange(bottomRow, 1, headlines.length, scoreCol+1).setFontWeight('bold');
+ ds.getRange(bottomRow, headlineCol + 1).setValue('Topic: \"' + topic + '\"');
+ ds.getRange(bottomRow, headlineCol + 2).setValue('Avg:');
+ ds.getRange(bottomRow, sentimentCol + 1).setValue(getFace(avgDecimal));
+ ds.getRange(bottomRow, sentimentCol + 1).setBackgroundColor(getColor(avgDecimal));
+ ds.getRange(bottomRow, scoreCol + 1).setValue(avgDecimal);
+ ss.toast("Done!!");
+}
+
+/**
+ * Calls the Natureal Language API to get sentiment response for headline.
+ *
+ * Important note: Not all languages are supported by Google document
+ * sentiment analysis.
+ * Unsupported languages generate a "400" response: "INVALID_ARGUMENT".
+ */
+function retrieveSentiment(text) {
+ // Sets REST call options
+ let apiEndPoint =
+ 'https://language.googleapis.com/v1/documents:analyzeSentiment?key=' +
+ googleAPIKey;
+ let jsonReq = JSON.stringify({
+ document: {
+ type: "PLAIN_TEXT",
+ content: text
+ },
+ encodingType: "UTF8"
+ });
+
+ let options = {
+ 'method': 'post',
+ 'contentType': 'application/json',
+ 'payload': jsonReq
+ }
+
+ // Makes the REST call
+ let response = UrlFetchApp.fetch(apiEndPoint, options);
+ let responseData = JSON.parse(response);
+ return responseData;
+}
+
+// Helper Functions
+
+/**
+ * Removes old headlines, sentiments and reset formatting
+ */
+function reformatSheet() {
+ let range = ds.getRange(fullsheet);
+ range.clearContent();
+ range.clearFormat();
+ range.setWrapStrategy(SpreadsheetApp.WrapStrategy.CLIP);
+
+ range = ds.getRange(sentimentCols); // Center the sentiment cols only
+ range.setHorizontalAlignment("center");
+}
+
+/**
+ * Returns a corresponding face based on numeric value.
+ */
+function getFace(value){
+ if (value >= threshold) {
+ return happyFace;
+ } else if (value < threshold && value > -threshold){
+ return mehFace;
+ } else if (value <= -threshold) {
+ return sadFace;
+ }
+}
+
+/**
+ * Returns a corresponding color based on numeric value.
+ */
+function getColor(value){
+ if (value >= threshold) {
+ return happyColor;
+ } else if (value < threshold && value > -threshold){
+ return mehColor;
+ } else if (value <= -threshold) {
+ return sadColor;
+ }
+}
+
+/**
+ * Scrubs invalid characters out of headline text.
+ * Can be expanded if needed.
+ */
+function scrub(text) {
+ return text.replace(/[\‘\,\“\”\"\'\’\-\n\â\]/g, ' ');
+}
\ No newline at end of file
diff --git a/solutions/automations/news-sentiment/README.md b/solutions/automations/news-sentiment/README.md
new file mode 100644
index 000000000..14e247a6c
--- /dev/null
+++ b/solutions/automations/news-sentiment/README.md
@@ -0,0 +1,3 @@
+# Connect to an external API: Analyze news headlines
+
+See [developers.google.com](https://developers.google.com/apps-script/samples/automations/news-sentiment) for additional details.
\ No newline at end of file
diff --git a/solutions/automations/news-sentiment/appsscript.json b/solutions/automations/news-sentiment/appsscript.json
new file mode 100644
index 000000000..3cf1d247d
--- /dev/null
+++ b/solutions/automations/news-sentiment/appsscript.json
@@ -0,0 +1,7 @@
+{
+ "timeZone": "America/New_York",
+ "dependencies": {
+ },
+ "exceptionLogging": "STACKDRIVER",
+ "runtimeVersion": "V8"
+}
\ No newline at end of file
diff --git a/solutions/automations/offsite-activity-signup/.clasp.json b/solutions/automations/offsite-activity-signup/.clasp.json
new file mode 100644
index 000000000..55715ed13
--- /dev/null
+++ b/solutions/automations/offsite-activity-signup/.clasp.json
@@ -0,0 +1 @@
+{"scriptId": "10clpAH4ojSXvTlZaE74rhJ6dDwwkfvi24L_AilGROca5Nds2Jy2oZmvY"}
diff --git a/solutions/automations/offsite-activity-signup/Code.js b/solutions/automations/offsite-activity-signup/Code.js
new file mode 100644
index 000000000..5cac3f583
--- /dev/null
+++ b/solutions/automations/offsite-activity-signup/Code.js
@@ -0,0 +1,458 @@
+// To learn how to use this script, refer to the documentation:
+// https://developers.google.com/apps-script/samples/automations/offsite-activity-signup
+
+/*
+Copyright 2022 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+const NUM_ITEMS_TO_RANK = 5;
+const ACTIVITIES_PER_PERSON = 2;
+const NUM_TEST_USERS = 150;
+
+/**
+ * Adds custom menu items when opening the sheet.
+ */
+function onOpen() {
+ let menu = SpreadsheetApp.getUi().createMenu('Activities')
+ .addItem('Create form', 'buildForm_')
+ .addItem('Generate test data', 'generateTestData_')
+ .addItem('Assign activities', 'assignActivities_')
+ .addToUi();
+}
+
+/**
+ * Builds a form based on the "Activity Schedule" sheet. The form asks attendees to rank their top
+ * N choices of activities, where N is defined by NUM_ITEMS_TO_RANK.
+ */
+function buildForm_() {
+ let ss = SpreadsheetApp.getActiveSpreadsheet();
+ if (ss.getFormUrl()) {
+ let msg = 'Form already exists. Unlink the form and try again.';
+ SpreadsheetApp.getUi().alert(msg);
+ return;
+ }
+ let form = FormApp.create('Activity Signup')
+ .setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId())
+ .setAllowResponseEdits(true)
+ .setLimitOneResponsePerUser(true)
+ .setCollectEmail(true);
+ let sectionHelpText = Utilities.formatString('Please choose your top %d activities',
+ NUM_ITEMS_TO_RANK);
+ form.addSectionHeaderItem()
+ .setTitle('Activity choices')
+ .setHelpText(sectionHelpText);
+
+ // Presents activity ranking as a form grid with each activity as a row and rank as a column.
+ let rows = loadActivitySchedule_(ss).map(function(activity) {
+ return activity.description;
+ });
+ let columns = range_(1, NUM_ITEMS_TO_RANK).map(function(value) {
+ return Utilities.formatString('%s', toOrdinal_(value));
+ });
+ let gridValidation = FormApp.createGridValidation()
+ .setHelpText('Select one item per column.')
+ .requireLimitOneResponsePerColumn()
+ .build();
+ form.addGridItem()
+ .setColumns(columns)
+ .setRows(rows)
+ .setValidation(gridValidation);
+
+ form.addListItem()
+ .setTitle('Assign other activities if choices are not available?')
+ .setChoiceValues(['Yes', 'No']);
+}
+
+/**
+ * Assigns activities using a random priority/random serial dictatorship approach. The results
+ * are then populated into two new sheets, one listing activities per person, the other listing
+ * the rosters for each activity.
+ *
+ * See https://en.wikipedia.org/wiki/Random_serial_dictatorship for additional information.
+ */
+function assignActivities_() {
+ let ss = SpreadsheetApp.getActiveSpreadsheet();
+ let activities = loadActivitySchedule_(ss);
+ let activityIds = activities.map(function(activity) {
+ return activity.id;
+ });
+ let attendees = loadAttendeeResponses_(ss, activityIds);
+ assignWithRandomPriority_(attendees, activities, 2);
+ writeAttendeeAssignments_(ss, attendees);
+ writeActivityRosters_(ss, activities);
+}
+
+/**
+ * Selects activities via random priority.
+ *
+ * @param {object[]} attendees - Array of attendees to assign activities to
+ * @param {object[]} activities - Array of all available activities
+ * @param {number} numActivitiesPerPerson - Maximum number of activities to assign
+ */
+function assignWithRandomPriority_(attendees, activities, numActivitiesPerPerson) {
+ let activitiesById = activities.reduce(function(obj, activity) {
+ obj[activity.id] = activity;
+ return obj;
+ }, {});
+ for (let i = 0; i < numActivitiesPerPerson; ++i) {
+ let randomizedAttendees = shuffleArray_(attendees);
+ randomizedAttendees.forEach(function(attendee) {
+ makeChoice_(attendee, activitiesById);
+ });
+ }
+}
+
+/**
+ * Attempts to assign an activity for an attendee based on their preferences and current schedule.
+ *
+ * @param {object} attendee - Attendee looking to join an activity
+ * @param {object} activitiesById - Map of all available activities
+ */
+function makeChoice_(attendee, activitiesById) {
+ for (let i = 0; i < attendee.preferences.length; ++i) {
+ let activity = activitiesById[attendee.preferences[i]];
+ if (!activity) {
+ continue;
+ }
+ let canJoin = checkAvailability_(attendee, activity);
+ if (canJoin) {
+ attendee.assigned.push(activity);
+ activity.roster.push(attendee);
+ break;
+ }
+ }
+}
+
+/**
+ * Checks that an activity has capacity and doesn't conflict with previously assigned
+ * activities.
+ *
+ * @param {object} attendee - Attendee looking to join the activity
+ * @param {object} activity - Proposed activity
+ * @return {boolean} - True if attendee can join the activity
+ */
+function checkAvailability_(attendee, activity) {
+ if (activity.capacity <= activity.roster.length) {
+ return false;
+ }
+ let timesConflict = attendee.assigned.some(function(assignedActivity) {
+ return !(assignedActivity.startAt.getTime() > activity.endAt.getTime() ||
+ activity.startAt.getTime() > assignedActivity.endAt.getTime());
+ });
+ return !timesConflict;
+};
+
+/**
+ * Populates a sheet with the assigned activities for each attendee.
+ *
+ * @param {Spreadsheet} ss - Spreadsheet to write to.
+ * @param {object[]} attendees - Array of attendees with their activity assignments
+ */
+function writeAttendeeAssignments_(ss, attendees) {
+ let sheet = findOrCreateSheetByName_(ss, 'Activities by person');
+ sheet.clear();
+ sheet.appendRow(['Email address', 'Activities']);
+ sheet.getRange('B1:1').merge();
+ let rows = attendees.map(function(attendee) {
+ // Prefill row to ensure consistent length otherwise
+ // can't bulk update the sheet with range.setValues()
+ let row = fillArray_([], ACTIVITIES_PER_PERSON + 1, '');
+ row[0] = attendee.email;
+ attendee.assigned.forEach(function(activity, index) {
+ row[index + 1] = activity.description;
+ });
+ return row;
+ });
+ bulkAppendRows_(sheet, rows);
+ sheet.setFrozenRows(1);
+ sheet.getRange('1:1').setFontWeight('bold');
+ sheet.autoResizeColumns(1, sheet.getLastColumn());
+}
+
+/**
+ * Populates a sheet with the rosters for each activity.
+ *
+ * @param {Spreadsheet} ss - Spreadsheet to write to.
+ * @param {object[]} activities - Array of activities with their rosters
+ */
+function writeActivityRosters_(ss, activities) {
+ let sheet = findOrCreateSheetByName_(ss, 'Activity rosters');
+ sheet.clear();
+ var rows = [];
+ var rows = activities.map(function(activity) {
+ let roster = activity.roster.map(function(attendee) {
+ return attendee.email;
+ });
+ return [activity.description].concat(roster);
+ });
+ // Transpose the data so each activity is a column
+ rows = transpose_(rows, '');
+ bulkAppendRows_(sheet, rows);
+ sheet.setFrozenRows(1);
+ sheet.getRange('1:1').setFontWeight('bold');
+ sheet.autoResizeColumns(1, sheet.getLastColumn());
+}
+
+/**
+ * Loads the activity schedule.
+ *
+ * @param {Spreadsheet} ss - Spreadsheet to load from
+ * @return {object[]} Array of available activities.
+ */
+function loadActivitySchedule_(ss) {
+ let timeZone = ss.getSpreadsheetTimeZone();
+ let sheet = ss.getSheetByName('Activity Schedule');
+ let rows = sheet.getSheetValues(
+ sheet.getFrozenRows() + 1, 1,
+ sheet.getLastRow() - 1, sheet.getLastRow());
+ let activities = rows.map(function(row, index) {
+ let name = row[0];
+ let startAt = new Date(row[1]);
+ let endAt = new Date(row[2]);
+ let capacity = parseInt(row[3]);
+ let formattedStartAt= Utilities.formatDate(startAt, timeZone, 'EEE hh:mm a');
+ let formattedEndAt = Utilities.formatDate(endAt, timeZone, 'hh:mm a');
+ let description = Utilities.formatString('%s (%s-%s)', name, formattedStartAt, formattedEndAt);
+ return {
+ id: index,
+ name: name,
+ description: description,
+ capacity: capacity,
+ startAt: startAt,
+ endAt: endAt,
+ roster: [],
+ };
+ });
+ return activities;
+}
+
+/**
+ * Loads the attendeee response data.
+ *
+ * @param {Spreadsheet} ss - Spreadsheet to load from
+ * @param {number[]} allActivityIds - Full set of available activity IDs
+ * @return {object[]} Array of parsed attendee respones.
+ */
+function loadAttendeeResponses_(ss, allActivityIds) {
+ let sheet = findResponseSheetForForm_(ss);
+
+ if (!sheet || sheet.getLastRow() == 1) {
+ return undefined;
+ }
+
+ let rows = sheet.getSheetValues(
+ sheet.getFrozenRows() + 1, 1,
+ sheet.getLastRow() - 1, sheet.getLastRow());
+ let attendees = rows.map(function(row) {
+ let _ = row.shift(); // Ignore timestamp
+ let email = row.shift();
+ let autoAssign = row.pop();
+ // Find ranked items in the response data.
+ let preferences = row.reduce(function(prefs, value, index) {
+ let match = value.match(/(\d+).*/);
+ if (!match) {
+ return prefs;
+ }
+ let rank = parseInt(match[1]) - 1; // Convert ordinal to array index
+ prefs[rank] = index;
+ return prefs;
+ }, []);
+ if (autoAssign == 'Yes') {
+ // If auto assigning additional activites, append a randomized list of all the activities.
+ // These will then be considered as if the attendee ranked them.
+ let additionalChoices = shuffleArray_(allActivityIds);
+ preferences = preferences.concat(additionalChoices);
+ }
+ return {
+ email: email,
+ preferences: preferences,
+ assigned: [],
+ };
+ });
+ return attendees;
+}
+
+/**
+ * Simulates a large number of users responding to the form. This enables users to quickly
+ * experience the full solution without having to collect sufficient form responses
+ * through other means.
+ */
+function generateTestData_() {
+ let ss = SpreadsheetApp.getActiveSpreadsheet();
+ let sheet = findResponseSheetForForm_(ss);
+ if (!sheet) {
+ let msg = 'No response sheet found. Create the form and try again.';
+ SpreadsheetApp.getUi().alert(msg);
+ }
+ if (sheet.getLastRow() > 1) {
+ let msg = 'Response sheet is not empty, can not generate test data. ' +
+ 'Remove responses and try again.';
+ SpreadsheetApp.getUi().alert(msg);
+ return;
+ }
+
+ let activities = loadActivitySchedule_(ss);
+ let choices = fillArray_([], activities.length, '');
+ range_(1, 5).forEach(function(value) {
+ choices[value] = toOrdinal_(value);
+ });
+
+ let rows = range_(1, NUM_TEST_USERS).map(function(value) {
+ let randomizedChoices = shuffleArray_(choices);
+ let email = Utilities.formatString('person%d@example.com', value);
+ return [new Date(), email].concat(randomizedChoices).concat(['Yes']);
+ });
+ bulkAppendRows_(sheet, rows);
+}
+
+/**
+ * Retrieves a sheet by name, creating it if it doesn't yet exist.
+ *
+ * @param {Spreadsheet} ss - Containing spreadsheet
+ * @Param {string} name - Name of sheet to return
+ * @return {Sheet} Sheet instance
+ */
+function findOrCreateSheetByName_(ss, name) {
+ let sheet = ss.getSheetByName(name);
+ if (sheet) {
+ return sheet;
+ }
+ return ss.insertSheet(name);
+}
+
+/**
+ * Faster version of appending multiple rows via ranges. Requires all rows are equal length.
+ *
+ * @param {Sheet} sheet - Sheet to append to
+ * @param {Array>} rows - Rows to append
+ */
+function bulkAppendRows_(sheet, rows) {
+ let startRow = sheet.getLastRow() + 1;
+ let startColumn = 1;
+ let numRows = rows.length;
+ let numColumns = rows[0].length;
+ sheet.getRange(startRow, startColumn, numRows, numColumns).setValues(rows);
+}
+
+/**
+ * Copies and randomizes an array.
+ *
+ * @param {object[]} array - Array to shuffle
+ * @return {object[]} randomized copy of the array
+ */
+function shuffleArray_(array) {
+ let clone = array.slice(0);
+ for (let i = clone.length - 1; i > 0; i--) {
+ let j = Math.floor(Math.random() * (i + 1));
+ let temp = clone[i];
+ clone[i] = clone[j];
+ clone[j] = temp;
+ }
+ return clone;
+}
+
+/**
+ * Formats an number as an ordinal.
+ *
+ * See: https://stackoverflow.com/questions/13627308/add-st-nd-rd-and-th-ordinal-suffix-to-a-number/13627586
+ *
+ * @param {number} i - Number to format
+ * @return {string} Formatted string
+ */
+function toOrdinal_(i) {
+ let j = i % 10;
+ let k = i % 100;
+ if (j == 1 && k != 11) {
+ return i + 'st';
+ }
+ if (j == 2 && k != 12) {
+ return i + 'nd';
+ }
+ if (j == 3 && k != 13) {
+ return i + 'rd';
+ }
+ return i + 'th';
+}
+
+/**
+ * Locates the sheet containing the form responses.
+ *
+ * @param {Spreadsheet} ss - Spreadsheet instance to search
+ * @return {Sheet} Sheet with form responses, undefined if not found.
+ */
+function findResponseSheetForForm_(ss) {
+ let formUrl = ss.getFormUrl();
+ if (!ss || !formUrl) {
+ return undefined;
+ }
+ let sheets = ss.getSheets();
+ for (let i in sheets) {
+ if (sheets[i].getFormUrl() === formUrl) {
+ return sheets[i];
+ }
+ }
+ return undefined;
+}
+
+/**
+ * Fills an array with a value ([].fill() not supported in Apps Script).
+ *
+ * @param {object[]} arr - Array to fill
+ * @param {number} length - Number of items to fill.
+ * @param {object} value - Value to place at each index.
+ * @return {object[]} the array, for chaining purposes
+ */
+function fillArray_(arr, length, value) {
+ for (let i = 0; i < length; ++i) {
+ arr[i] = value;
+ }
+ return arr;
+}
+
+/**
+ * Creates and fills an array with numbers in the range [start, end].
+ *
+ * @param {number} start - First value in the range, inclusive
+ * @param {number} end - Last value in the range, inclusive
+ * @return {number[]} Array of values representing the range
+ */
+function range_(start, end) {
+ let arr = [start];
+ let i = start;
+ while (i < end) {
+ arr.push(i += 1);
+ }
+ return arr;
+}
+
+/**
+ * Transposes a matrix/2d array. For cases where the rows are not the same length,
+ * `fillValue` is used where no other value would otherwise be present.
+ *
+ * @param {Array>} arr - 2D array to transpose
+ * @param {object} fillValue - Placeholder for undefined values created as a result
+ * of the transpose. Only required if rows aren't all of equal length.
+ * @return {Array>} New transposed array
+ */
+function transpose_(arr, fillValue) {
+ let transposed = [];
+ arr.forEach(function(row, rowIndex) {
+ row.forEach(function(col, colIndex) {
+ transposed[colIndex] = transposed[colIndex] || fillArray_([], arr.length, fillValue);
+ transposed[colIndex][rowIndex] = row[colIndex];
+ });
+ });
+ return transposed;
+}
diff --git a/solutions/automations/offsite-activity-signup/README.md b/solutions/automations/offsite-activity-signup/README.md
new file mode 100644
index 000000000..06e8debc0
--- /dev/null
+++ b/solutions/automations/offsite-activity-signup/README.md
@@ -0,0 +1,3 @@
+# Create a sign-up for an offsite
+
+See [developers.google.com](https://developers.google.com/apps-script/samples/automations/offsite-activity-signup) for additional details.
diff --git a/solutions/automations/offsite-activity-signup/appsscript.json b/solutions/automations/offsite-activity-signup/appsscript.json
new file mode 100644
index 000000000..3cf1d247d
--- /dev/null
+++ b/solutions/automations/offsite-activity-signup/appsscript.json
@@ -0,0 +1,7 @@
+{
+ "timeZone": "America/New_York",
+ "dependencies": {
+ },
+ "exceptionLogging": "STACKDRIVER",
+ "runtimeVersion": "V8"
+}
\ No newline at end of file
diff --git a/solutions/automations/tax-loss-harvest-alerts/.clasp.json b/solutions/automations/tax-loss-harvest-alerts/.clasp.json
new file mode 100644
index 000000000..b9dffc2b6
--- /dev/null
+++ b/solutions/automations/tax-loss-harvest-alerts/.clasp.json
@@ -0,0 +1 @@
+{"scriptId":"1SVf_XAGJiwksNTMnAwtlIvkKaDou4RLsmwGTa9ipVHKgwITgwXWqMixB"}
\ No newline at end of file
diff --git a/solutions/automations/tax-loss-harvest-alerts/Code.js b/solutions/automations/tax-loss-harvest-alerts/Code.js
new file mode 100644
index 000000000..e25098b87
--- /dev/null
+++ b/solutions/automations/tax-loss-harvest-alerts/Code.js
@@ -0,0 +1,72 @@
+// To learn how to use this script, refer to the documentation:
+// https://developers.google.com/apps-script/samples/automations/tax-loss-harvest-alerts
+
+/*
+Copyright 2022 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+/**
+* Checks for losses in the sheet.
+*/
+function checkLosses() {
+ // Pulls data from the spreadsheet
+ let sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(
+ "Calculations"
+ );
+ let source = sheet.getRange("A:G");
+ let data = source.getValues();
+
+ //Prepares the email alert content
+ let message = "Stocks:
";
+
+ let send_message = false;
+
+ console.log("starting loop");
+
+ //Loops through the cells in the spreadsheet to find cells where the stock fell below purchase price
+ let n = 0;
+ for (let i in data) {
+ //Skips the first row
+ if (n++ == 0) continue;
+
+ //Loads the current row
+ let row = data[i];
+
+ console.log(row[1]);
+ console.log(row[6]);
+
+ //Once at the end of the list, exits the loop
+ if (row[1] == "") break;
+
+ //If value is below purchase price, adds stock ticker and difference to list of tax loss opportunities
+ if (row[6] < 0) {
+ message +=
+ row[1] +
+ ": " +
+ (parseFloat(row[6].toString()) * 100).toFixed(2).toString() +
+ "% ";
+ send_message = true;
+ }
+ }
+ if (!send_message) return;
+
+ MailApp.sendEmail({
+ to: SpreadsheetApp.getActiveSpreadsheet().getOwner().getEmail(),
+ subject: "Tax-loss harvest",
+ htmlBody: message,
+
+ });
+}
+
diff --git a/solutions/automations/tax-loss-harvest-alerts/README.md b/solutions/automations/tax-loss-harvest-alerts/README.md
new file mode 100644
index 000000000..8143e4c2f
--- /dev/null
+++ b/solutions/automations/tax-loss-harvest-alerts/README.md
@@ -0,0 +1,3 @@
+# Get stock price drop alerts
+
+See [developers.google.com](https://developers.google.com/apps-script/samples/automations/tax-loss-harvest-alerts) for additional details.
\ No newline at end of file
diff --git a/solutions/automations/tax-loss-harvest-alerts/appsscript.json b/solutions/automations/tax-loss-harvest-alerts/appsscript.json
new file mode 100644
index 000000000..3cf1d247d
--- /dev/null
+++ b/solutions/automations/tax-loss-harvest-alerts/appsscript.json
@@ -0,0 +1,7 @@
+{
+ "timeZone": "America/New_York",
+ "dependencies": {
+ },
+ "exceptionLogging": "STACKDRIVER",
+ "runtimeVersion": "V8"
+}
\ No newline at end of file
diff --git a/solutions/automations/timesheets/.clasp.json b/solutions/automations/timesheets/.clasp.json
new file mode 100644
index 000000000..5f0ff403b
--- /dev/null
+++ b/solutions/automations/timesheets/.clasp.json
@@ -0,0 +1 @@
+{"scriptId": "1uzOldn2RjqdrbDJwxuPlcsb7twKLdW59YPS02rbEg_ajAG9XzrYF1-fH"}
diff --git a/solutions/automations/timesheets/Code.js b/solutions/automations/timesheets/Code.js
new file mode 100644
index 000000000..bad03efdc
--- /dev/null
+++ b/solutions/automations/timesheets/Code.js
@@ -0,0 +1,264 @@
+// To learn how to use this script, refer to the documentation:
+// https://developers.google.com/apps-script/samples/automations/timesheets
+
+/*
+Copyright 2022 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Global variables representing the index of certain columns.
+let COLUMN_NUMBER = {
+ EMAIL: 2,
+ HOURS_START: 4,
+ HOURS_END: 8,
+ HOURLY_PAY: 9,
+ TOTAL_HOURS: 10,
+ CALC_PAY: 11,
+ APPROVAL: 12,
+ NOTIFY: 13,
+};
+
+// Global variables:
+let APPROVED_EMAIL_SUBJECT = 'Weekly Timesheet APPROVED';
+let REJECTED_EMAIL_SUBJECT = 'Weekly Timesheet NOT APPROVED';
+let APPROVED_EMAIL_MESSAGE = 'Your timesheet has been approved.';
+let REJECTED_EMAIL_MESSAGE = 'Your timesheet has not been approved.';
+
+/**
+ * Creates the menu item "Timesheets" for user to run scripts on drop-down.
+ */
+function onOpen() {
+ let ui = SpreadsheetApp.getUi();
+ ui.createMenu('Timesheets')
+ .addItem('Form setup', 'setUpForm')
+ .addItem('Column setup', 'columnSetup')
+ .addItem('Notify employees', 'checkApprovedStatusToNotify')
+ .addToUi();
+}
+
+/**
+ * Adds "WEEKLY PAY" column with calculated values using array formulas.
+ * Adds an "APPROVAL" column at the end of the sheet, containing
+ * drop-down menus to either approve/disapprove employee timesheets.
+ * Adds a "NOTIFIED STATUS" column indicating whether or not an
+ * employee has yet been e mailed.
+ */
+function columnSetup() {
+ let sheet = SpreadsheetApp.getActiveSheet();
+ let lastCol = sheet.getLastColumn();
+ let lastRow = sheet.getLastRow();
+ let frozenRows = sheet.getFrozenRows();
+ let beginningRow = frozenRows + 1;
+ let numRows = lastRow - frozenRows;
+
+ // Calls helper functions to add new columns.
+ addCalculatePayColumn(sheet, beginningRow);
+ addApprovalColumn(sheet, beginningRow, numRows);
+ addNotifiedColumn(sheet, beginningRow, numRows);
+}
+
+/**
+ * Adds TOTAL HOURS and CALCULATE PAY columns and automatically calculates
+ * every employee's weekly pay.
+ *
+ * @param {Object} sheet Spreadsheet object of current sheet.
+ * @param {Integer} beginningRow Index of beginning row.
+ */
+function addCalculatePayColumn(sheet, beginningRow) {
+ sheet.insertColumnAfter(COLUMN_NUMBER.HOURLY_PAY);
+ sheet.getRange(1, COLUMN_NUMBER.TOTAL_HOURS).setValue('TOTAL HOURS');
+ sheet.getRange(1, COLUMN_NUMBER.CALC_PAY).setValue('WEEKLY PAY');
+
+ // Calculates weekly total hours.
+ sheet.getRange(beginningRow, COLUMN_NUMBER.TOTAL_HOURS)
+ .setFormula('=ArrayFormula(D2:D+E2:E+F2:F+G2:G+H2:H)');
+ // Calculates weekly pay.
+ sheet.getRange(beginningRow, COLUMN_NUMBER.CALC_PAY)
+ .setFormula('=ArrayFormula(I2:I * J2:J)');
+}
+
+/**
+ * Adds an APPROVAL column allowing managers to approve/
+ * disapprove of each employee's timesheet.
+ *
+ * @param {Object} sheet Spreadsheet object of current sheet.
+ * @param {Integer} beginningRow Index of beginning row.
+ * @param {Integer} numRows Number of rows currently in use.
+ */
+function addApprovalColumn(sheet, beginningRow, numRows) {
+ sheet.insertColumnAfter(COLUMN_NUMBER.CALC_PAY);
+ sheet.getRange(1, COLUMN_NUMBER.APPROVAL).setValue('APPROVAL');
+
+ // Make sure approval column is all drop-down menus.
+ let approvalColumnRange = sheet.getRange(beginningRow, COLUMN_NUMBER.APPROVAL,
+ numRows, 1);
+ let dropdownValues = ['APPROVED', 'NOT APPROVED', 'IN PROGRESS'];
+ let rule = SpreadsheetApp.newDataValidation().requireValueInList(dropdownValues)
+ .build();
+ approvalColumnRange.setDataValidation(rule);
+ approvalColumnRange.setValue('IN PROGRESS');
+}
+
+/**
+ * Adds a NOTIFIED column allowing managers to see which employees
+ * have/have not yet been notified of their approval status.
+ *
+ * @param {Object} sheet Spreadsheet object of current sheet.
+ * @param {Integer} beginningRow Index of beginning row.
+ * @param {Integer} numRows Number of rows currently in use.
+ */
+function addNotifiedColumn(sheet, beginningRow, numRows) {
+ sheet.insertColumnAfter(COLUMN_NUMBER.APPROVAL); // global
+ sheet.getRange(1, COLUMN_NUMBER.APPROVAL + 1).setValue('NOTIFIED STATUS');
+
+ // Make sure notified column is all drop-down menus.
+ let notifiedColumnRange = sheet.getRange(beginningRow, COLUMN_NUMBER.APPROVAL
+ + 1, numRows, 1);
+ dropdownValues = ['NOTIFIED', 'PENDING'];
+ rule = SpreadsheetApp.newDataValidation().requireValueInList(dropdownValues)
+ .build();
+ notifiedColumnRange.setDataValidation(rule);
+ notifiedColumnRange.setValue('PENDING');
+}
+
+/**
+ * Sets the notification status to NOTIFIED for employees
+ * who have received a notification email.
+ *
+ * @param {Object} sheet Current Spreadsheet.
+ * @param {Object} notifiedValues Array of notified values.
+ * @param {Integer} i Current status in the for loop.
+ * @parma {Integer} beginningRow Row where iterations began.
+ */
+function updateNotifiedStatus(sheet, notifiedValues, i, beginningRow) {
+ // Update notification status.
+ notifiedValues[i][0] = 'NOTIFIED';
+ sheet.getRange(i + beginningRow, COLUMN_NUMBER.NOTIFY).setValue('NOTIFIED');
+}
+
+/**
+ * Checks the approval status of every employee, and calls helper functions
+ * to notify employees via email & update their notification status.
+ */
+function checkApprovedStatusToNotify() {
+ let sheet = SpreadsheetApp.getActiveSheet();
+ let lastRow = sheet.getLastRow();
+ let lastCol = sheet.getLastColumn();
+ // lastCol here is the NOTIFIED column.
+ let frozenRows = sheet.getFrozenRows();
+ let beginningRow = frozenRows + 1;
+ let numRows = lastRow - frozenRows;
+
+ // Gets ranges of email, approval, and notified values for every employee.
+ let emailValues = sheet.getRange(beginningRow, COLUMN_NUMBER.EMAIL, numRows, 1).getValues();
+ let approvalValues = sheet.getRange(beginningRow, COLUMN_NUMBER.APPROVAL,
+ lastRow - frozenRows, 1).getValues();
+ let notifiedValues = sheet.getRange(beginningRow, COLUMN_NUMBER.NOTIFY, numRows,
+ 1).getValues();
+
+ // Traverses through employee's row.
+ for (let i = 0; i < numRows; i++) {
+ // Do not notify twice.
+ if (notifiedValues[i][0] == 'NOTIFIED') {
+ continue;
+ }
+ let emailAddress = emailValues[i][0];
+ let approvalValue = approvalValues[i][0];
+
+ // Sends notifying emails & update status.
+ if (approvalValue == 'IN PROGRESS') {
+ continue;
+ } else if (approvalValue == 'APPROVED') {
+ MailApp.sendEmail(emailAddress, APPROVED_EMAIL_SUBJECT, APPROVED_EMAIL_MESSAGE);
+ updateNotifiedStatus(sheet, notifiedValues, i, beginningRow);
+ } else if (approvalValue == 'NOT APPROVED') {
+ MailApp.sendEmail(emailAddress,REJECTED_EMAIL_SUBJECT, REJECTED_EMAIL_MESSAGE);
+ updateNotifiedStatus(sheet, notifiedValues, i, beginningRow);
+ }
+ }
+}
+
+/**
+ * Set up the Timesheets Responses form, & link the form's trigger to
+ * send manager an email when a new request is submitted.
+ */
+function setUpForm() {
+ let sheet = SpreadsheetApp.getActiveSpreadsheet();
+ if (sheet.getFormUrl()) {
+ let msg = 'Form already exists. Unlink the form and try again.';
+ SpreadsheetApp.getUi().alert(msg);
+ return;
+ }
+
+ // Create the form.
+ let form = FormApp.create('Weekly Timesheets')
+ .setCollectEmail(true)
+ .setDestination(FormApp.DestinationType.SPREADSHEET, sheet.getId())
+ .setLimitOneResponsePerUser(false);
+ form.addTextItem().setTitle('Employee Name:').setRequired(true);
+ form.addTextItem().setTitle('Monday Hours:').setRequired(true);
+ form.addTextItem().setTitle('Tuesday Hours:').setRequired(true);
+ form.addTextItem().setTitle('Wednesday Hours:').setRequired(true);
+ form.addTextItem().setTitle('Thursday Hours:').setRequired(true);
+ form.addTextItem().setTitle('Friday Hours:').setRequired(true);
+ form.addTextItem().setTitle('HourlyWage:').setRequired(true);
+
+ // Set up on form submit trigger.
+ ScriptApp.newTrigger('onFormSubmit')
+ .forForm(form)
+ .onFormSubmit()
+ .create();
+}
+
+/**
+ * Handle new form submissions to trigger the workflow.
+ *
+ * @param {Object} event Form submit event
+ */
+function onFormSubmit(event) {
+ let response = getResponsesByName(event.response);
+
+ // Load form responses into a new row.
+ let row = ['New',
+ '',
+ response['Emoloyee Email:'],
+ response['Employee Name:'],
+ response['Monday Hours:'],
+ response['Tuesday Hours:'],
+ response['Wednesday Hours:'],
+ response['Thursday Hours:'],
+ response['Friday Hours:'],
+ response['Hourly Wage:']];
+ let sheet = SpreadsheetApp.getActiveSpreadsheet();
+ sheet.appendRow(row);
+}
+
+/**
+ * Converts a form response to an object keyed by the item titles. Allows easier
+ * access to response values.
+ *
+ * @param {FormResponse} response
+ * @return {Object} Form values keyed by question title
+ */
+function getResponsesByName(response) {
+ let initialValue = {
+ email: response.getRespondentEmail(),
+ timestamp: response.getTimestamp(),
+ };
+ return response.getItemResponses().reduce(function(obj, itemResponse) {
+ let key = itemResponse.getItem().getTitle();
+ obj[key] = itemResponse.getResponse();
+ return obj;
+ }, initialValue);
+}
\ No newline at end of file
diff --git a/solutions/automations/timesheets/README.md b/solutions/automations/timesheets/README.md
new file mode 100644
index 000000000..100b7ea38
--- /dev/null
+++ b/solutions/automations/timesheets/README.md
@@ -0,0 +1,3 @@
+# Collect and review timesheets from employees
+
+See [developers.google.com](https://developers.google.com/apps-script/samples/automations/timesheets) for additional details.
diff --git a/solutions/automations/timesheets/appsscript.json b/solutions/automations/timesheets/appsscript.json
new file mode 100644
index 000000000..3cf1d247d
--- /dev/null
+++ b/solutions/automations/timesheets/appsscript.json
@@ -0,0 +1,7 @@
+{
+ "timeZone": "America/New_York",
+ "dependencies": {
+ },
+ "exceptionLogging": "STACKDRIVER",
+ "runtimeVersion": "V8"
+}
\ No newline at end of file
diff --git a/solutions/automations/upload-files/Code.js b/solutions/automations/upload-files/Code.js
new file mode 100644
index 000000000..50e523954
--- /dev/null
+++ b/solutions/automations/upload-files/Code.js
@@ -0,0 +1,111 @@
+// To learn how to use this script, refer to the documentation:
+// https://developers.google.com/apps-script/samples/automations/upload-files
+
+/*
+Copyright 2022 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// [START apps_script_upload_files]
+// TODO Before you start using this sample, you must run the setUp()
+// function in the Setup.gs file.
+
+// Application constants
+const APP_TITLE = "Upload files to Drive from Forms";
+const APP_FOLDER_NAME = "Upload files to Drive (File responses)";
+
+// Identifies the subfolder form item
+const APP_SUBFOLDER_ITEM = "Subfolder";
+const APP_SUBFOLDER_NONE = "";
+
+
+/**
+ * Gets the file uploads from a form response and moves files to the corresponding subfolder.
+ *
+ * @param {object} event - Form submit.
+ */
+function onFormSubmit(e) {
+ try {
+ // Gets the application root folder.
+ var destFolder = getFolder_(APP_FOLDER_NAME);
+
+ // Gets all form responses.
+ let itemResponses = e.response.getItemResponses();
+
+ // Determines the subfolder to route the file to, if any.
+ var subFolderName;
+ let dest = itemResponses.filter((itemResponse) =>
+ itemResponse.getItem().getTitle().toString() === APP_SUBFOLDER_ITEM);
+
+ // Gets the destination subfolder name, but ignores if APP_SUBFOLDER_NONE was selected;
+ if (dest.length > 0) {
+ if (dest[0].getResponse() != APP_SUBFOLDER_NONE) {
+ subFolderName = dest[0].getResponse();
+ }
+ }
+ // Gets the subfolder or creates it if it doesn't exist.
+ if (subFolderName != undefined) {
+ destFolder = getSubFolder_(destFolder, subFolderName)
+ }
+ console.log(`Destination folder to use:
+ Name: ${destFolder.getName()}
+ ID: ${destFolder.getId()}
+ URL: ${destFolder.getUrl()}`)
+
+ // Gets the file upload response as an array to allow for multiple files.
+ let fileUploads = itemResponses.filter((itemResponse) => itemResponse.getItem().getType().toString() === "FILE_UPLOAD")
+ .map((itemResponse) => itemResponse.getResponse())
+ .reduce((a, b) => [...a, ...b], []);
+
+ // Moves the files to the destination folder.
+ if (fileUploads.length > 0) {
+ fileUploads.forEach((fileId) => {
+ DriveApp.getFileById(fileId).moveTo(destFolder);
+ console.log(`File Copied: ${fileId}`)
+ });
+ }
+ }
+ catch (err) {
+ console.log(err);
+ }
+}
+
+
+/**
+ * Returns a Drive folder under the passed in objParentFolder parent
+ * folder. Checks if folder of same name exists before creating, returning
+ * the existing folder or the newly created one if not found.
+ *
+ * @param {object} objParentFolder - Drive folder as an object.
+ * @param {string} subFolderName - Name of subfolder to create/return.
+ * @return {object} Drive folder
+ */
+function getSubFolder_(objParentFolder, subFolderName) {
+
+ // Iterates subfolders of parent folder to check if folder already exists.
+ const subFolders = objParentFolder.getFolders();
+ while (subFolders.hasNext()) {
+ let folder = subFolders.next();
+
+ // Returns the existing folder if found.
+ if (folder.getName() === subFolderName) {
+ return folder;
+ }
+ }
+ // Creates a new folder if one doesn't already exist.
+ return objParentFolder.createFolder(subFolderName)
+ .setDescription(`Created by ${APP_TITLE} application to store uploaded Forms files.`);
+}
+
+// [END apps_script_upload_files]
diff --git a/solutions/automations/upload-files/README.md b/solutions/automations/upload-files/README.md
new file mode 100644
index 000000000..975bc219b
--- /dev/null
+++ b/solutions/automations/upload-files/README.md
@@ -0,0 +1,3 @@
+# Upload files to Google Drive from Google Forms
+
+See [developers.google.com](https://developers.google.com/apps-script/samples/automations/upload-files) for additional details.
diff --git a/solutions/automations/upload-files/Setup.js b/solutions/automations/upload-files/Setup.js
new file mode 100644
index 000000000..2ad4ef5cf
--- /dev/null
+++ b/solutions/automations/upload-files/Setup.js
@@ -0,0 +1,119 @@
+/**
+ * Copyright 2022 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// [START apps_script_upload_files_setup]
+// TODO You must run the setUp() function before you start using this sample.
+
+/**
+ * The setUp() function performs the following:
+ * - Creates a Google Drive folder named by the APP_FOLDER_NAME
+ * variable in the Code.gs file.
+ * - Creates a trigger to handle onFormSubmit events.
+ */
+function setUp() {
+ // Ensures the root destination folder exists.
+ const appFolder = getFolder_(APP_FOLDER_NAME);
+ if (appFolder !== null) {
+ console.log(`Application folder setup.
+ Name: ${appFolder.getName()}
+ ID: ${appFolder.getId()}
+ URL: ${appFolder.getUrl()}`)
+ }
+ else {
+ console.log(`Could not setup application folder.`)
+ }
+ // Calls the function that creates the Forms onSubmit trigger.
+ installTrigger_();
+}
+
+/**
+ * Returns a folder to store uploaded files in the same location
+ * in Drive where the form is located. First, it checks if the folder
+ * already exists, and creates it if it doesn't.
+ *
+ * @param {string} folderName - Name of the Drive folder.
+ * @return {object} Google Drive Folder
+ */
+function getFolder_(folderName) {
+
+ // Gets the Drive folder where the form is located.
+ const ssId = FormApp.getActiveForm().getId();
+ const parentFolder = DriveApp.getFileById(ssId).getParents().next();
+
+ // Iterates through the subfolders to check if folder already exists.
+ // The script checks for the folder name specified in the APP_FOLDER_NAME variable.
+ const subFolders = parentFolder.getFolders();
+ while (subFolders.hasNext()) {
+ let folder = subFolders.next();
+
+ // Returns the existing folder if found.
+ if (folder.getName() === folderName) {
+ return folder;
+ }
+ }
+ // Creates a new folder if one doesn't already exist.
+ return parentFolder.createFolder(folderName)
+ .setDescription(`Created by ${APP_TITLE} application to store uploaded files.`);
+}
+
+/**
+ * Installs trigger to capture onFormSubmit event when a form is submitted.
+ * Ensures that the trigger is only installed once.
+ * Called by setup().
+ */
+function installTrigger_() {
+ // Ensures existing trigger doesn't already exist.
+ let propTriggerId = PropertiesService.getScriptProperties().getProperty('triggerUniqueId')
+ if (propTriggerId !== null) {
+ const triggers = ScriptApp.getProjectTriggers();
+ for (let t in triggers) {
+ if (triggers[t].getUniqueId() === propTriggerId) {
+ console.log(`Trigger with the following unique ID already exists: ${propTriggerId}`);
+ return;
+ }
+ }
+ }
+ // Creates the trigger if one doesn't exist.
+ let triggerUniqueId = ScriptApp.newTrigger('onFormSubmit')
+ .forForm(FormApp.getActiveForm())
+ .onFormSubmit()
+ .create()
+ .getUniqueId();
+ PropertiesService.getScriptProperties().setProperty('triggerUniqueId', triggerUniqueId);
+ console.log(`Trigger with the following unique ID was created: ${triggerUniqueId}`);
+}
+
+/**
+ * Removes all script properties and triggers for the project.
+ * Use primarily to test setup routines.
+ */
+function removeTriggersAndScriptProperties() {
+ PropertiesService.getScriptProperties().deleteAllProperties();
+ // Removes all triggers associated with project.
+ const triggers = ScriptApp.getProjectTriggers();
+ for (let t in triggers) {
+ ScriptApp.deleteTrigger(triggers[t]);
+ }
+}
+
+/**
+ * Removes all form responses to reset the form.
+ */
+function deleteAllResponses() {
+ FormApp.getActiveForm().deleteAllResponses();
+}
+
+// [END apps_script_upload_files_setup]
diff --git a/solutions/automations/upload-files/appsscript.json b/solutions/automations/upload-files/appsscript.json
new file mode 100644
index 000000000..3cf1d247d
--- /dev/null
+++ b/solutions/automations/upload-files/appsscript.json
@@ -0,0 +1,7 @@
+{
+ "timeZone": "America/New_York",
+ "dependencies": {
+ },
+ "exceptionLogging": "STACKDRIVER",
+ "runtimeVersion": "V8"
+}
\ No newline at end of file
diff --git a/solutions/automations/vacation-calendar/.clasp.json b/solutions/automations/vacation-calendar/.clasp.json
new file mode 100644
index 000000000..b9162a3b0
--- /dev/null
+++ b/solutions/automations/vacation-calendar/.clasp.json
@@ -0,0 +1 @@
+{"scriptId":"1jvPSSwJcuLzlDLDy2dr-qorjihiTNAW2H6B5k-dJxHjEPX6hMcNghzSh"}
diff --git a/solutions/automations/vacation-calendar/Code.js b/solutions/automations/vacation-calendar/Code.js
new file mode 100644
index 000000000..ef0078a20
--- /dev/null
+++ b/solutions/automations/vacation-calendar/Code.js
@@ -0,0 +1,241 @@
+// To learn how to use this script, refer to the documentation:
+// https://developers.google.com/apps-script/samples/automations/vacation-calendar
+
+/*
+Copyright 2022 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Set the ID of the team calendar to add events to. You can find the calendar's
+// ID on the settings page.
+let TEAM_CALENDAR_ID = 'ENTER_TEAM_CALENDAR_ID_HERE';
+// Set the email address of the Google Group that contains everyone in the team.
+// Ensure the group has less than 500 members to avoid timeouts.
+// Change to an array in order to add indirect members frrm multiple groups, for example:
+// let GROUP_EMAIL = ['ENTER_GOOGLE_GROUP_EMAIL_HERE', 'ENTER_ANOTHER_GOOGLE_GROUP_EMAIL_HERE'];
+let GROUP_EMAIL = 'ENTER_GOOGLE_GROUP_EMAIL_HERE';
+
+let ONLY_DIRECT_MEMBERS = false;
+
+let KEYWORDS = ['vacation', 'ooo', 'out of office', 'offline'];
+let MONTHS_IN_ADVANCE = 3;
+
+/**
+ * Sets up the script to run automatically every hour.
+ */
+function setup() {
+ let triggers = ScriptApp.getProjectTriggers();
+ if (triggers.length > 0) {
+ throw new Error('Triggers are already setup.');
+ }
+ ScriptApp.newTrigger('sync').timeBased().everyHours(1).create();
+ // Runs the first sync immediately.
+ sync();
+}
+
+/**
+ * Looks through the group members' public calendars and adds any
+ * 'vacation' or 'out of office' events to the team calendar.
+ */
+function sync() {
+ // Defines the calendar event date range to search.
+ let today = new Date();
+ let maxDate = new Date();
+ maxDate.setMonth(maxDate.getMonth() + MONTHS_IN_ADVANCE);
+
+ // Determines the time the the script was last run.
+ let lastRun = PropertiesService.getScriptProperties().getProperty('lastRun');
+ lastRun = lastRun ? new Date(lastRun) : null;
+
+ // Gets the list of users in the Google Group.
+ let users = getAllMembers(GROUP_EMAIL);
+ if (ONLY_DIRECT_MEMBERS){
+ users = GroupsApp.getGroupByEmail(GROUP_EMAIL).getUsers();
+ } else if (Array.isArray(GROUP_EMAIL)) {
+ users = getUsersFromGroups(GROUP_EMAIL);
+ }
+
+ // For each user, finds events having one or more of the keywords in the event
+ // summary in the specified date range. Imports each of those to the team
+ // calendar.
+ let count = 0;
+ users.forEach(function(user) {
+ let username = user.getEmail().split('@')[0];
+ KEYWORDS.forEach(function(keyword) {
+ let events = findEvents(user, keyword, today, maxDate, lastRun);
+ events.forEach(function(event) {
+ importEvent(username, event);
+ count++;
+ }); // End foreach event.
+ }); // End foreach keyword.
+ }); // End foreach user.
+
+ PropertiesService.getScriptProperties().setProperty('lastRun', today);
+ console.log('Imported ' + count + ' events');
+}
+
+/**
+ * Imports the given event from the user's calendar into the shared team
+ * calendar.
+ * @param {string} username The team member that is attending the event.
+ * @param {Calendar.Event} event The event to import.
+ */
+function importEvent(username, event) {
+ event.summary = '[' + username + '] ' + event.summary;
+ event.organizer = {
+ id: TEAM_CALENDAR_ID,
+ };
+ event.attendees = [];
+
+ // If the event is not of type 'default', it can't be imported, so it needs
+ // to be changed.
+ if (event.eventType != 'default') {
+ event.eventType = 'default';
+ delete event.outOfOfficeProperties;
+ delete event.focusTimeProperties;
+ }
+
+ console.log('Importing: %s', event.summary);
+ try {
+ Calendar.Events.import(event, TEAM_CALENDAR_ID);
+ } catch (e) {
+ console.error('Error attempting to import event: %s. Skipping.',
+ e.toString());
+ }
+}
+
+/**
+ * In a given user's calendar, looks for occurrences of the given keyword
+ * in events within the specified date range and returns any such events
+ * found.
+ * @param {Session.User} user The user to retrieve events for.
+ * @param {string} keyword The keyword to look for.
+ * @param {Date} start The starting date of the range to examine.
+ * @param {Date} end The ending date of the range to examine.
+ * @param {Date} optSince A date indicating the last time this script was run.
+ * @return {Calendar.Event[]} An array of calendar events.
+ */
+function findEvents(user, keyword, start, end, optSince) {
+ let params = {
+ q: keyword,
+ timeMin: formatDateAsRFC3339(start),
+ timeMax: formatDateAsRFC3339(end),
+ showDeleted: true,
+ };
+ if (optSince) {
+ // This prevents the script from examining events that have not been
+ // modified since the specified date (that is, the last time the
+ // script was run).
+ params.updatedMin = formatDateAsRFC3339(optSince);
+ }
+ let pageToken = null;
+ let events = [];
+ do {
+ params.pageToken = pageToken;
+ let response;
+ try {
+ response = Calendar.Events.list(user.getEmail(), params);
+ } catch (e) {
+ console.error('Error retriving events for %s, %s: %s; skipping',
+ user, keyword, e.toString());
+ continue;
+ }
+ events = events.concat(response.items.filter(function(item) {
+ return shouldImportEvent(user, keyword, item);
+ }));
+ pageToken = response.nextPageToken;
+ } while (pageToken);
+ return events;
+}
+
+/**
+ * Determines if the given event should be imported into the shared team
+ * calendar.
+ * @param {Session.User} user The user that is attending the event.
+ * @param {string} keyword The keyword being searched for.
+ * @param {Calendar.Event} event The event being considered.
+ * @return {boolean} True if the event should be imported.
+ */
+function shouldImportEvent(user, keyword, event) {
+ // Filters out events where the keyword did not appear in the summary
+ // (that is, the keyword appeared in a different field, and are thus
+ // is not likely to be relevant).
+ if (event.summary.toLowerCase().indexOf(keyword) < 0) {
+ return false;
+ }
+ if (!event.organizer || event.organizer.email == user.getEmail()) {
+ // If the user is the creator of the event, always imports it.
+ return true;
+ }
+ // Only imports events the user has accepted.
+ if (!event.attendees) return false;
+ let matching = event.attendees.filter(function(attendee) {
+ return attendee.self;
+ });
+ return matching.length > 0 && matching[0].responseStatus == 'accepted';
+}
+
+/**
+ * Returns an RFC3339 formated date String corresponding to the given
+ * Date object.
+ * @param {Date} date a Date.
+ * @return {string} a formatted date string.
+ */
+function formatDateAsRFC3339(date) {
+ return Utilities.formatDate(date, 'UTC', 'yyyy-MM-dd\'T\'HH:mm:ssZ');
+}
+
+/**
+* Get both direct and indirect members (and delete duplicates).
+* @param {string} the e-mail address of the group.
+* @return {object} direct and indirect members.
+*/
+function getAllMembers(groupEmail) {
+ var group = GroupsApp.getGroupByEmail(groupEmail);
+ var users = group.getUsers();
+ var childGroups = group.getGroups();
+ for (var i = 0; i < childGroups.length; i++) {
+ var childGroup = childGroups[i];
+ users = users.concat(getAllMembers(childGroup.getEmail()));
+ }
+ // Remove duplicate members
+ var uniqueUsers = [];
+ var userEmails = {};
+ for (var i = 0; i < users.length; i++) {
+ var user = users[i];
+ if (!userEmails[user.getEmail()]) {
+ uniqueUsers.push(user);
+ userEmails[user.getEmail()] = true;
+ }
+ }
+ return uniqueUsers;
+}
+
+/**
+* Get indirect members from multiple groups (and delete duplicates).
+* @param {array} the e-mail addresses of multiple groups.
+* @return {object} indirect members of multiple groups.
+*/
+function getUsersFromGroups(groupEmails) {
+ let users = [];
+ for (let groupEmail of groupEmails) {
+ let groupUsers = GroupsApp.getGroupByEmail(groupEmail).getUsers();
+ for (let user of groupUsers) {
+ if (!users.some(u => u.getEmail() === user.getEmail())) {
+ users.push(user);
+ }
+ }
+ }
+ return users;
+}
diff --git a/solutions/automations/vacation-calendar/README.md b/solutions/automations/vacation-calendar/README.md
new file mode 100644
index 000000000..012f9e3e0
--- /dev/null
+++ b/solutions/automations/vacation-calendar/README.md
@@ -0,0 +1,3 @@
+# Populate a team vacation calendar
+
+See [developers.google.com](https://developers.google.com/apps-script/samples/automations/vacation-calendar) for additional details.
\ No newline at end of file
diff --git a/solutions/automations/vacation-calendar/appsscript.json b/solutions/automations/vacation-calendar/appsscript.json
new file mode 100644
index 000000000..3cf1d247d
--- /dev/null
+++ b/solutions/automations/vacation-calendar/appsscript.json
@@ -0,0 +1,7 @@
+{
+ "timeZone": "America/New_York",
+ "dependencies": {
+ },
+ "exceptionLogging": "STACKDRIVER",
+ "runtimeVersion": "V8"
+}
\ No newline at end of file
diff --git a/solutions/automations/youtube-tracker/.clasp.json b/solutions/automations/youtube-tracker/.clasp.json
new file mode 100644
index 000000000..3e74246bd
--- /dev/null
+++ b/solutions/automations/youtube-tracker/.clasp.json
@@ -0,0 +1 @@
+{"scriptId":"15WP4FukVYk_4zy21j0_13GftPH7J8lpdtemYcy_168TYKsAQ4x-pAeQz"}
\ No newline at end of file
diff --git a/solutions/automations/youtube-tracker/Code.js b/solutions/automations/youtube-tracker/Code.js
new file mode 100644
index 000000000..b99827d4d
--- /dev/null
+++ b/solutions/automations/youtube-tracker/Code.js
@@ -0,0 +1,126 @@
+// To learn how to use this script, refer to the documentation:
+// https://developers.google.com/apps-script/samples/automations/youtube-tracker
+
+/*
+Copyright 2022 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Sets preferences for email notification. Choose 'Y' to send emails, 'N' to skip emails.
+const EMAIL_ON = 'Y';
+
+// Matches column names in Video sheet to variables. If the column names change, update these variables.
+const COLUMN_NAME = {
+ VIDEO: 'Video Link',
+ TITLE: 'Video Title',
+};
+
+/**
+ * Gets YouTube video details and statistics for all
+ * video URLs listed in 'Video Link' column in each
+ * sheet. Sends email summary, based on preferences above,
+ * when videos have new comments or replies.
+ */
+function markVideos() {
+ let ss = SpreadsheetApp.getActiveSpreadsheet();
+ let sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
+
+ // Runs through process for each tab in Spreadsheet.
+ sheets.forEach(function(dataSheet) {
+ let tabName = dataSheet.getName();
+ let range = dataSheet.getDataRange();
+ let numRows = range.getNumRows();
+ let rows = range.getValues();
+ let headerRow = rows[0];
+
+ // Finds the column indices.
+ let videoColumnIdx = headerRow.indexOf(COLUMN_NAME.VIDEO);
+ let titleColumnIdx = headerRow.indexOf(COLUMN_NAME.TITLE);
+
+ // Creates empty array to collect data for email table.
+ let emailContent = [];
+
+ // Processes each row in spreadsheet.
+ for (let i = 1; i < numRows; ++i) {
+ let row = rows[i];
+ // Extracts video ID.
+ let videoId = extractVideoIdFromUrl(row[videoColumnIdx])
+ // Processes each row that contains a video ID.
+ if(!videoId) {
+ continue;
+ }
+ // Calls getVideoDetails function and extracts target data for the video.
+ let detailsResponse = getVideoDetails(videoId);
+ let title = detailsResponse.items[0].snippet.title;
+ let publishDate = detailsResponse.items[0].snippet.publishedAt;
+ let publishDateFormatted = new Date(publishDate);
+ let views = detailsResponse.items[0].statistics.viewCount;
+ let likes = detailsResponse.items[0].statistics.likeCount;
+ let comments = detailsResponse.items[0].statistics.commentCount;
+ let channel = detailsResponse.items[0].snippet.channelTitle;
+
+ // Collects title, publish date, channel, views, comments, likes details and pastes into tab.
+ let detailsRow = [title,publishDateFormatted,channel,views,comments,likes];
+ dataSheet.getRange(i+1,titleColumnIdx+1,1,6).setValues([detailsRow]);
+
+ // Determines if new count of comments/replies is greater than old count of comments/replies.
+ let addlCommentCount = comments - row[titleColumnIdx+4];
+
+ // Adds video title, link, and additional comment count to table if new counts > old counts.
+ if (addlCommentCount > 0) {
+ let emailRow = [title,row[videoColumnIdx],addlCommentCount]
+ emailContent.push(emailRow);
+ }
+ }
+ // Sends notification email if Content is not empty.
+ if (emailContent.length > 0 && EMAIL_ON == 'Y') {
+ sendEmailNotificationTemplate(emailContent, tabName);
+ }
+ });
+}
+
+/**
+ * Gets video details for YouTube videos
+ * using YouTube advanced service.
+ */
+function getVideoDetails(videoId) {
+ let part = "snippet,statistics";
+ let response = YouTube.Videos.list(part,
+ {'id': videoId});
+ return response;
+}
+
+/**
+ * Extracts YouTube video ID from url.
+ * (h/t https://stackoverflow.com/a/3452617)
+ */
+function extractVideoIdFromUrl(url) {
+ let videoId = url.split('v=')[1];
+ let ampersandPosition = videoId.indexOf('&');
+ if (ampersandPosition != -1) {
+ videoId = videoId.substring(0, ampersandPosition);
+ }
+ return videoId;
+}
+
+/**
+ * Assembles notification email with table of video details.
+ * (h/t https://stackoverflow.com/questions/37863392/making-table-in-google-apps-script-from-array)
+ */
+function sendEmailNotificationTemplate(content, emailAddress) {
+ let template = HtmlService.createTemplateFromFile('email');
+ template.content = content;
+ let msg = template.evaluate();
+ MailApp.sendEmail(emailAddress,'New comments or replies on YouTube',msg.getContent(),{htmlBody:msg.getContent()});
+}
\ No newline at end of file
diff --git a/solutions/automations/youtube-tracker/README.md b/solutions/automations/youtube-tracker/README.md
new file mode 100644
index 000000000..7c80c2ad0
--- /dev/null
+++ b/solutions/automations/youtube-tracker/README.md
@@ -0,0 +1,3 @@
+# Track YouTube video views and comments
+
+See [developers.google.com](https://developers.google.com/apps-script/samples/automations/youtube-tracker) for additional details.
\ No newline at end of file
diff --git a/solutions/automations/youtube-tracker/appsscript.json b/solutions/automations/youtube-tracker/appsscript.json
new file mode 100644
index 000000000..3cf1d247d
--- /dev/null
+++ b/solutions/automations/youtube-tracker/appsscript.json
@@ -0,0 +1,7 @@
+{
+ "timeZone": "America/New_York",
+ "dependencies": {
+ },
+ "exceptionLogging": "STACKDRIVER",
+ "runtimeVersion": "V8"
+}
\ No newline at end of file
diff --git a/solutions/automations/youtube-tracker/email.html b/solutions/automations/youtube-tracker/email.html
new file mode 100644
index 000000000..7d21a7a40
--- /dev/null
+++ b/solutions/automations/youtube-tracker/email.html
@@ -0,0 +1,36 @@
+
+
+
+
+ Hello,
+
+
+
diff --git a/solutions/chat-bots/schedule-meetings/.clasp.json b/solutions/chat-bots/schedule-meetings/.clasp.json
new file mode 100644
index 000000000..34c4cfc7f
--- /dev/null
+++ b/solutions/chat-bots/schedule-meetings/.clasp.json
@@ -0,0 +1 @@
+{"scriptId": "1NdhQ_nXfEUUhWcWKiY6WJjeunY70a1W9vnFdS7BCLPMFreSaHaOS3ucM"}
diff --git a/solutions/chat-bots/schedule-meetings/Code.js b/solutions/chat-bots/schedule-meetings/Code.js
new file mode 100644
index 000000000..42b7f3f45
--- /dev/null
+++ b/solutions/chat-bots/schedule-meetings/Code.js
@@ -0,0 +1,190 @@
+// To learn how to use this script, refer to the documentation:
+// https://developers.google.com/apps-script/samples/chat-bots/schedule-meetings
+
+/*
+Copyright 2022 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Application constants
+const BOTNAME = 'Chat Meeting Scheduler';
+const SLASHCOMMAND = {
+ HELP: 1, // /help
+ DIALOG: 2, // /schedule_Meeting
+};
+
+/**
+ * Responds to an ADDED_TO_SPACE event in Google Chat.
+ * Called when the bot is added to a space. The bot can either be directly added to the space
+ * or added by a @mention. If the bot is added by a @mention, the event object includes a message property.
+ * Returns a Message object, which is usually a welcome message informing users about the bot.
+ *
+ * @param {Object} event The event object from Google Chat
+ */
+function onAddToSpace(event) {
+ let message = '';
+
+ // Personalizes the message depending on how the bot is called.
+ if (event.space.singleUserBotDm) {
+ message = `Hi ${event.user.displayName}!`;
+ } else {
+ const spaceName = event.space.displayName ? event.space.displayName : "this chat";
+ message = `Hi! Thank you for adding me to ${spaceName}`;
+ }
+
+ // Lets users know what they can do and how they can get help.
+ message = message + '/nI can quickly schedule a meeting for you with just a few clicks.' +
+ 'Try me out by typing */schedule_Meeting*. ' +
+ '/nTo learn what else I can do, type */help*.'
+
+ return { "text": message };
+}
+
+/**
+ * Responds to a MESSAGE event triggered in Chat.
+ * Called when the bot is already in the space and the user invokes it via @mention or / command.
+ * Returns a message object containing the bot's response. For this bot, the response is either the
+ * help text or the dialog to schedule a meeting.
+ *
+ * @param {object} event The event object from Google Chat
+ * @return {object} JSON-formatted response as text or Card message
+ */
+function onMessage(event) {
+
+ // Handles regular onMessage logic.
+ // Evaluates if and handles for all slash commands.
+ if (event.message.slashCommand) {
+ switch (event.message.slashCommand.commandId) {
+
+ case SLASHCOMMAND.DIALOG: // Displays meeting dialog for /schedule_Meeting.
+
+ // TODO update this with your own logic to set meeting recipients, subjects, etc (e.g. a group email).
+ return getInputFormAsDialog_({
+ invitee: '',
+ startTime: getTopOfHourDateString_(),
+ duration: 30,
+ subject: 'Status Stand-up',
+ body: 'Scheduling a quick status stand-up meeting.'
+ });
+
+ case SLASHCOMMAND.HELP: // Responds with help text for /help.
+ return getHelpTextResponse_();
+
+ /* TODO Add other use cases here. E.g:
+ case SLASHCOMMAND.NEW_FEATURE: // Your Feature Here
+ getDialogForAddContact(message);
+ */
+
+ }
+ }
+ else {
+ // Returns text if users didn't invoke a slash command.
+ return { text: 'No action taken - use Slash Commands.' }
+ }
+}
+
+/**
+ * Responds to a CARD_CLICKED event triggered in Chat.
+ * @param {object} event the event object from Chat
+ * @return {object} JSON-formatted response
+ * @see https://developers.google.com/chat/api/guides/message-formats/events
+ */
+function onCardClick(event) {
+ if (event.action.actionMethodName === 'handleFormSubmit') {
+ const recipients = getFieldValue_(event.common.formInputs, 'email');
+ const subject = getFieldValue_(event.common.formInputs, 'subject');
+ const body = getFieldValue_(event.common.formInputs, 'body');
+
+ // Assumes dialog card inputs for date and times are in the correct format. mm/dd/yyy HH:MM
+ const dateTimeInput = getFieldValue_(event.common.formInputs, 'date');
+ const startTime = getStartTimeAsDateObject_(dateTimeInput);
+ const duration = Number(getFieldValue_(event.common.formInputs, 'duration'));
+
+ // Handles instances of missing or invalid input parameters.
+ const errors = [];
+
+ if (!recipients) {
+ errors.push('Missing or invalid recipient email address.');
+ }
+ if (!subject) {
+ errors.push('Missing subject line.');
+ }
+ if (!body) {
+ errors.push('Missing event description.');
+ }
+ if (!startTime) {
+ errors.push('Missing or invalid start time.');
+ }
+ if (!duration || isNaN(duration)) {
+ errors.push('Missing or invalid duration');
+ }
+ if (errors.length) {
+ // Redisplays the form if missing or invalid inputs exist.
+ return getInputFormAsDialog_({
+ errors,
+ invitee: recipients,
+ startTime: dateTimeInput,
+ duration,
+ subject,
+ body
+ });
+ }
+
+ // Calculates the end time via duration.
+ const endTime = new Date(startTime.valueOf());
+ endTime.setMinutes(endTime.getMinutes() + duration);
+
+ // Creates calendar event with notification.
+ const calendar = CalendarApp.getDefaultCalendar()
+ const scheduledEvent = calendar.createEvent(subject,
+ startTime,
+ endTime,
+ {
+ guests: recipients,
+ sendInvites: true,
+ description: body + '\nThis meeting scheduled by a Google Chat App!'
+ });
+
+ // Gets a link to the Calendar event.
+ const url = getCalendarEventURL_(scheduledEvent, calendar)
+
+ return getConfirmationDialog_(url);
+
+ } else if (event.action.actionMethodName === 'closeDialog') {
+
+ // Returns this dialog as success.
+ return {
+ actionResponse: {
+ type: 'DIALOG',
+ dialog_action: {
+ actionStatus: 'OK'
+ }
+ }
+ }
+ }
+}
+
+/**
+ * Responds with help text about this chat bot.
+ * @return {string} The help text as seen below
+ */
+function getHelpTextResponse_() {
+ const help = `*${BOTNAME}* lets you quickly create meetings from Google Chat. Here\'s a list of all its commands:
+ \`/schedule_Meeting\` Opens a dialog with editable, preset parameters to create a meeting event
+ \`/help\` Displays this help message
+
+ Learn more about creating Google Chat bots at https://developers.google.com/chat.`
+
+ return { 'text': help }
+}
diff --git a/solutions/chat-bots/schedule-meetings/Dialog.js b/solutions/chat-bots/schedule-meetings/Dialog.js
new file mode 100644
index 000000000..c7731683e
--- /dev/null
+++ b/solutions/chat-bots/schedule-meetings/Dialog.js
@@ -0,0 +1,210 @@
+/**
+ * Copyright 2022 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+* Form input dialog as JSON.
+* @return {object} JSON-formatted cards for the dialog.
+*/
+function getInputFormAsDialog_(options) {
+ const form = getForm_(options);
+ return {
+ 'actionResponse': {
+ 'type': 'DIALOG',
+ 'dialogAction': {
+ 'dialog': {
+ 'body': form
+ }
+ }
+ }
+ };
+}
+
+/**
+* Form JSON to collect inputs regarding the meeting.
+* @return {object} JSON-formatted cards.
+*/
+function getForm_(options) {
+ const sections = [];
+
+ // If errors present, display additional section with validation messages.
+ if (options.errors && options.errors.length) {
+ let errors = options.errors.reduce((str, err) => `${str}• ${err} `, '');
+ errors = `Errors: ${errors}`;
+ const errorSection = {
+ 'widgets': [
+ {
+ textParagraph: {
+ text: errors
+ }
+ }
+ ]
+ }
+ sections.push(errorSection);
+ }
+ let formSection = {
+ 'header': 'Schedule meeting and send email to invited participants',
+ 'widgets': [
+ {
+ 'textInput': {
+ 'label': 'Event Title',
+ 'type': 'SINGLE_LINE',
+ 'name': 'subject',
+ 'value': options.subject
+ }
+ },
+ {
+ 'textInput': {
+ 'label': 'Invitee Email Address',
+ 'type': 'SINGLE_LINE',
+ 'name': 'email',
+ 'value': options.invitee,
+ 'hintText': 'Add team group email'
+ }
+ },
+ {
+ 'textInput': {
+ 'label': 'Description',
+ 'type': 'MULTIPLE_LINE',
+ 'name': 'body',
+ 'value': options.body
+ }
+ },
+ {
+ 'textInput': {
+ 'label': 'Meeting start date & time',
+ 'type': 'SINGLE_LINE',
+ 'name': 'date',
+ 'value': options.startTime,
+ 'hintText': 'mm/dd/yyyy H:MM'
+ }
+ },
+ {
+ 'selectionInput': {
+ 'type': 'DROPDOWN',
+ 'label': 'Meeting Duration',
+ 'name': 'duration',
+ 'items': [
+ {
+ 'text': '15 minutes',
+ 'value': '15',
+ 'selected': options.duration === 15
+ },
+ {
+ 'text': '30 minutes',
+ 'value': '30',
+ 'selected': options.duration === 30
+ },
+ {
+ 'text': '45 minutes',
+ 'value': '45',
+ 'selected': options.duration === 45
+ },
+ {
+ 'text': '1 Hour',
+ 'value': '60',
+ 'selected': options.duration === 60
+ },
+ {
+ 'text': '1.5 Hours',
+ 'value': '90',
+ 'selected': options.duration === 90
+ },
+ {
+ 'text': '2 Hours',
+ 'value': '120',
+ 'selected': options.duration === 120
+ }
+ ]
+ }
+ }
+ ],
+ 'collapsible': false
+ };
+ sections.push(formSection);
+ const card = {
+ 'sections': sections,
+ 'name': 'Google Chat Scheduled Meeting',
+ 'fixedFooter': {
+ 'primaryButton': {
+ 'text': 'Submit',
+ 'onClick': {
+ 'action': {
+ 'function': 'handleFormSubmit'
+ }
+ },
+ 'altText': 'Submit'
+ }
+ }
+ };
+ return card;
+}
+
+/**
+* Confirmation dialog after a calendar event is created successfully.
+* @param {string} url The Google Calendar Event url for link button
+* @return {object} JSON-formatted cards for the dialog
+*/
+function getConfirmationDialog_(url) {
+ return {
+ 'actionResponse': {
+ 'type': 'DIALOG',
+ 'dialogAction': {
+ 'dialog': {
+ 'body': {
+ 'sections': [
+ {
+ 'widgets': [
+ {
+ 'textParagraph': {
+ 'text': 'Meeting created successfully!'
+ },
+ 'horizontalAlignment': 'CENTER'
+ },
+ {
+ 'buttonList': {
+ 'buttons': [
+ {
+ 'text': 'Open Calendar Event',
+ 'onClick': {
+ 'openLink': {
+ 'url': url
+ }
+ }
+ }
+
+ ]
+ },
+ 'horizontalAlignment': 'CENTER'
+ }
+ ]
+ }
+ ],
+ 'fixedFooter': {
+ 'primaryButton': {
+ 'text': 'OK',
+ 'onClick': {
+ 'action': {
+ 'function': 'closeDialog'
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/solutions/chat-bots/schedule-meetings/README.md b/solutions/chat-bots/schedule-meetings/README.md
new file mode 100644
index 000000000..000aed7af
--- /dev/null
+++ b/solutions/chat-bots/schedule-meetings/README.md
@@ -0,0 +1,4 @@
+# Schedule meetings from Google Chat
+
+See [developers.google.com](https://developers.google.com/apps-script/samples/chat-apps/schedule-meetings) for additional details.
+
diff --git a/solutions/chat-bots/schedule-meetings/Utilities.js b/solutions/chat-bots/schedule-meetings/Utilities.js
new file mode 100644
index 000000000..dd08ea31b
--- /dev/null
+++ b/solutions/chat-bots/schedule-meetings/Utilities.js
@@ -0,0 +1,74 @@
+/**
+ * Copyright 2022 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+* Helper function that gets the field value from the given form input.
+* @return {string}
+*/
+function getFieldValue_(formInputs, fieldName) {
+ return formInputs[fieldName][''].stringInputs.value[0];
+}
+
+// Regular expression to validate the date/time input.
+const DATE_TIME_PATTERN = /\d{1,2}\/\d{1,2}\/\d{4}\s+\d{1,2}:\d\d/;
+
+/**
+* Casts date and time from string to Date object.
+* @return {date}
+*/
+function getStartTimeAsDateObject_(dateTimeStr) {
+ if (!dateTimeStr || !dateTimeStr.match(DATE_TIME_PATTERN)) {
+ return null;
+ }
+
+ const parts = dateTimeStr.split(' ');
+ const [month, day, year] = parts[0].split('/').map(Number);
+ const [hour, minute] = parts[1].split(':').map(Number);
+
+
+ Session.getScriptTimeZone()
+
+ return new Date(year, month - 1, day, hour, minute)
+}
+
+/**
+* Gets the current date and time for the upcoming top of the hour (e.g. 01/25/2022 18:00).
+* @return {string} date/time in mm/dd/yyy HH:MM format needed for use by Calendar
+*/
+function getTopOfHourDateString_() {
+ const date = new Date();
+ date.setHours(date.getHours() + 1);
+ date.setMinutes(0, 0, 0);
+ // Adding the date as string might lead to an incorrect response due to time zone adjustments.
+ return Utilities.formatDate(date, Session.getScriptTimeZone(), 'MM/dd/yyyy H:mm');
+}
+
+
+/**
+* Creates the URL for the Google Calendar event.
+*
+* @param {object} event The Google Calendar Event instance
+* @param {object} cal The associated Google Calendar
+* @return {string} URL in the form of 'https://www.google.com/calendar/event?eid={event-id}'
+*/
+function getCalendarEventURL_(event, cal) {
+ const baseCalUrl = 'https://www.google.com/calendar';
+ // Joins Calendar Event Id with Calendar Id, then base64 encode to derive the event URL.
+ let encodedId = Utilities.base64Encode(event.getId().split('@')[0] + " " + cal.getId()).replace(/\=/g, '');
+ encodedId = `/event?eid=${encodedId}`;
+ return (baseCalUrl + encodedId);
+
+}
\ No newline at end of file
diff --git a/solutions/chat-bots/schedule-meetings/appsscript.json b/solutions/chat-bots/schedule-meetings/appsscript.json
new file mode 100644
index 000000000..40869f567
--- /dev/null
+++ b/solutions/chat-bots/schedule-meetings/appsscript.json
@@ -0,0 +1,8 @@
+{
+ "timeZone": "America/Los_Angeles",
+ "exceptionLogging": "STACKDRIVER",
+ "runtimeVersion": "V8",
+ "chat": {
+ "addToSpaceFallbackMessage": "Thank you for adding this Chat Bot!"
+ }
+}
\ No newline at end of file
diff --git a/solutions/custom-functions/calculate-driving-distance/.clasp.json b/solutions/custom-functions/calculate-driving-distance/.clasp.json
new file mode 100644
index 000000000..6fb6a8c9b
--- /dev/null
+++ b/solutions/custom-functions/calculate-driving-distance/.clasp.json
@@ -0,0 +1 @@
+{"scriptId": "1_cfhZv-VJBekzu1V4mFD1C5ggRaUumWw9rUz0NaLED6XD4_yHB-eJ01a"}
diff --git a/solutions/custom-functions/calculate-driving-distance/Code.js b/solutions/custom-functions/calculate-driving-distance/Code.js
new file mode 100644
index 000000000..aaf9ceebd
--- /dev/null
+++ b/solutions/custom-functions/calculate-driving-distance/Code.js
@@ -0,0 +1,223 @@
+// To learn how to use this script, refer to the documentation:
+// https://developers.google.com/apps-script/samples/custom-functions/calculate-driving-distance
+
+/*
+Copyright 2022 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+/**
+ * @OnlyCurrentDoc Limits the script to only accessing the current sheet.
+ */
+
+/**
+ * A special function that runs when the spreadsheet is open, used to add a
+ * custom menu to the spreadsheet.
+ */
+function onOpen() {
+ try {
+ const spreadsheet = SpreadsheetApp.getActive();
+ const menuItems = [
+ {name: 'Prepare sheet...', functionName: 'prepareSheet_'},
+ {name: 'Generate step-by-step...', functionName: 'generateStepByStep_'}
+ ];
+ spreadsheet.addMenu('Directions', menuItems);
+ } catch (e) {
+ // TODO (Developer) - Handle Exception
+ console.log('Failed with error: %s' + e.error);
+ }
+}
+
+/**
+ * A custom function that converts meters to miles.
+ *
+ * @param {Number} meters The distance in meters.
+ * @return {Number} The distance in miles.
+ */
+function metersToMiles(meters) {
+ if (typeof meters !== 'number') {
+ return null;
+ }
+ return meters / 1000 * 0.621371;
+}
+
+/**
+ * A custom function that gets the driving distance between two addresses.
+ *
+ * @param {String} origin The starting address.
+ * @param {String} destination The ending address.
+ * @return {Number} The distance in meters.
+ */
+function drivingDistance(origin, destination) {
+ const directions = getDirections_(origin, destination);
+ return directions.routes[0].legs[0].distance.value;
+}
+
+/**
+ * A function that adds headers and some initial data to the spreadsheet.
+ */
+function prepareSheet_() {
+ try {
+ const sheet = SpreadsheetApp.getActiveSheet().setName('Settings');
+ const headers = [
+ 'Start Address',
+ 'End Address',
+ 'Driving Distance (meters)',
+ 'Driving Distance (miles)'];
+ const initialData = [
+ '350 5th Ave, New York, NY 10118',
+ '405 Lexington Ave, New York, NY 10174'];
+ sheet.getRange('A1:D1').setValues([headers]).setFontWeight('bold');
+ sheet.getRange('A2:B2').setValues([initialData]);
+ sheet.setFrozenRows(1);
+ sheet.autoResizeColumns(1, 4);
+ } catch (e) {
+ // TODO (Developer) - Handle Exception
+ console.log('Failed with error: %s' + e.error);
+ }
+}
+
+/**
+ * Creates a new sheet containing step-by-step directions between the two
+ * addresses on the "Settings" sheet that the user selected.
+ */
+function generateStepByStep_() {
+ try {
+ const spreadsheet = SpreadsheetApp.getActive();
+ const settingsSheet = spreadsheet.getSheetByName('Settings');
+ settingsSheet.activate();
+
+ // Prompt the user for a row number.
+ const selectedRow = Browser
+ .inputBox('Generate step-by-step', 'Please enter the row number of' +
+ ' the' + ' addresses to use' + ' (for example, "2"):',
+ Browser.Buttons.OK_CANCEL);
+ if (selectedRow === 'cancel') {
+ return;
+ }
+ const rowNumber = Number(selectedRow);
+ if (isNaN(rowNumber) || rowNumber < 2 ||
+ rowNumber > settingsSheet.getLastRow()) {
+ Browser.msgBox('Error',
+ Utilities.formatString('Row "%s" is not valid.', selectedRow),
+ Browser.Buttons.OK);
+ return;
+ }
+
+
+ // Retrieve the addresses in that row.
+ const row = settingsSheet.getRange(rowNumber, 1, 1, 2);
+ const rowValues = row.getValues();
+ const origin = rowValues[0][0];
+ const destination = rowValues[0][1];
+ if (!origin || !destination) {
+ Browser.msgBox('Error', 'Row does not contain two addresses.',
+ Browser.Buttons.OK);
+ return;
+ }
+
+ // Get the raw directions information.
+ const directions = getDirections_(origin, destination);
+
+ // Create a new sheet and append the steps in the directions.
+ const sheetName = 'Driving Directions for Row ' + rowNumber;
+ let directionsSheet = spreadsheet.getSheetByName(sheetName);
+ if (directionsSheet) {
+ directionsSheet.clear();
+ directionsSheet.activate();
+ } else {
+ directionsSheet =
+ spreadsheet.insertSheet(sheetName, spreadsheet.getNumSheets());
+ }
+ const sheetTitle = Utilities
+ .formatString('Driving Directions from %s to %s', origin, destination);
+ const headers = [
+ [sheetTitle, '', ''],
+ ['Step', 'Distance (Meters)', 'Distance (Miles)']
+ ];
+ const newRows = [];
+ for (const step of directions.routes[0].legs[0].steps) {
+ // Remove HTML tags from the instructions.
+ const instructions = step.html_instructions
+ .replace(/ |/g, '\n').replace(/<.*?>/g, '');
+ newRows.push([
+ instructions,
+ step.distance.value
+ ]);
+ }
+ directionsSheet.getRange(1, 1, headers.length, 3).setValues(headers);
+ directionsSheet.getRange(headers.length + 1, 1, newRows.length, 2)
+ .setValues(newRows);
+ directionsSheet.getRange(headers.length + 1, 3, newRows.length, 1)
+ .setFormulaR1C1('=METERSTOMILES(R[0]C[-1])');
+
+ // Format the new sheet.
+ directionsSheet.getRange('A1:C1').merge().setBackground('#ddddee');
+ directionsSheet.getRange('A1:2').setFontWeight('bold');
+ directionsSheet.setColumnWidth(1, 500);
+ directionsSheet.getRange('B2:C').setVerticalAlignment('top');
+ directionsSheet.getRange('C2:C').setNumberFormat('0.00');
+ const stepsRange = directionsSheet.getDataRange()
+ .offset(2, 0, directionsSheet.getLastRow() - 2);
+ setAlternatingRowBackgroundColors_(stepsRange, '#ffffff', '#eeeeee');
+ directionsSheet.setFrozenRows(2);
+ SpreadsheetApp.flush();
+ } catch (e) {
+ // TODO (Developer) - Handle Exception
+ console.log('Failed with error: %s' + e.error);
+ }
+}
+
+/**
+ * Sets the background colors for alternating rows within the range.
+ * @param {Range} range The range to change the background colors of.
+ * @param {string} oddColor The color to apply to odd rows (relative to the
+ * start of the range).
+ * @param {string} evenColor The color to apply to even rows (relative to the
+ * start of the range).
+ */
+function setAlternatingRowBackgroundColors_(range, oddColor, evenColor) {
+ const backgrounds = [];
+ for (let row = 1; row <= range.getNumRows(); row++) {
+ const rowBackgrounds = [];
+ for (let column = 1; column <= range.getNumColumns(); column++) {
+ if (row % 2 === 0) {
+ rowBackgrounds.push(evenColor);
+ } else {
+ rowBackgrounds.push(oddColor);
+ }
+ }
+ backgrounds.push(rowBackgrounds);
+ }
+ range.setBackgrounds(backgrounds);
+}
+
+/**
+ * A shared helper function used to obtain the full set of directions
+ * information between two addresses. Uses the Apps Script Maps Service.
+ *
+ * @param {String} origin The starting address.
+ * @param {String} destination The ending address.
+ * @return {Object} The directions response object.
+ */
+function getDirections_(origin, destination) {
+ const directionFinder = Maps.newDirectionFinder();
+ directionFinder.setOrigin(origin);
+ directionFinder.setDestination(destination);
+ const directions = directionFinder.getDirections();
+ if (directions.status !== 'OK') {
+ throw directions.error_message;
+ }
+ return directions;
+}
diff --git a/solutions/custom-functions/calculate-driving-distance/README.md b/solutions/custom-functions/calculate-driving-distance/README.md
new file mode 100644
index 000000000..3648623a0
--- /dev/null
+++ b/solutions/custom-functions/calculate-driving-distance/README.md
@@ -0,0 +1,4 @@
+# Calculate driving distance & convert meters to miles
+
+See [developers.google.com](https://developers.google.com/apps-script/samples/custom-functions/calculate-driving-distance) for additional details.
+
diff --git a/solutions/custom-functions/calculate-driving-distance/appsscript.json b/solutions/custom-functions/calculate-driving-distance/appsscript.json
new file mode 100644
index 000000000..3cf1d247d
--- /dev/null
+++ b/solutions/custom-functions/calculate-driving-distance/appsscript.json
@@ -0,0 +1,7 @@
+{
+ "timeZone": "America/New_York",
+ "dependencies": {
+ },
+ "exceptionLogging": "STACKDRIVER",
+ "runtimeVersion": "V8"
+}
\ No newline at end of file
diff --git a/solutions/custom-functions/summarize-sheets-data/.clasp.json b/solutions/custom-functions/summarize-sheets-data/.clasp.json
new file mode 100644
index 000000000..a53755e8a
--- /dev/null
+++ b/solutions/custom-functions/summarize-sheets-data/.clasp.json
@@ -0,0 +1 @@
+{"scriptId": "1NN-ROSZO3ZsfiVUlCdmNqggpCQuGNtgO_r0nehV0s5mkZJN2bcMTri-7"}
diff --git a/solutions/custom-functions/summarize-sheets-data/Code.js b/solutions/custom-functions/summarize-sheets-data/Code.js
new file mode 100644
index 000000000..70ac671bc
--- /dev/null
+++ b/solutions/custom-functions/summarize-sheets-data/Code.js
@@ -0,0 +1,83 @@
+// To learn how to use this script, refer to the documentation:
+// https://developers.google.com/apps-script/samples/custom-functions/summarize-sheets-data
+
+/*
+Copyright 2022 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+/**
+ * Gets summary data from other sheets. The sheets you want to summarize must have columns with headers that match the names of the columns this function summarizes data from.
+ *
+ * @return {string} Summary data from other sheets.
+ * @customfunction
+ */
+
+// The following sheets are ignored. Add additional constants for other sheets that should be ignored.
+const READ_ME_SHEET_NAME = "ReadMe";
+const PM_SHEET_NAME = "Summary";
+
+/**
+ * Reads data ranges for each sheet. Filters and counts based on 'Status' columns. To improve performance, the script uses arrays
+ * until all summary data is gathered. Then the script writes the summary array starting at the cell of the custom function.
+ */
+function getSheetsData() {
+ let ss = SpreadsheetApp.getActiveSpreadsheet();
+ let sheets = ss.getSheets();
+ let outputArr = [];
+
+ // For each sheet, summarizes the data and pushes to a temporary array.
+ for (let s in sheets) {
+ // Gets sheet name.
+ let sheetNm = sheets[s].getName();
+ // Skips ReadMe and Summary sheets.
+ if (sheetNm === READ_ME_SHEET_NAME || sheetNm === PM_SHEET_NAME) { continue; }
+ // Gets sheets data.
+ let values = sheets[s].getDataRange().getValues();
+ // Gets the first row of the sheet which is the header row.
+ let headerRowValues = values[0];
+ // Finds the columns with the heading names 'Owner Name' and 'Status' and gets the index value of each.
+ // Using 'indexOf()' to get the position of each column prevents the script from breaking if the columns change positions in a sheet.
+ let columnOwner = headerRowValues.indexOf("Owner Name");
+ let columnStatus = headerRowValues.indexOf("Status");
+ // Removes header row.
+ values.splice(0,1);
+ // Gets the 'Owner Name' column value by retrieving the first data row in the array.
+ let owner = values[0][columnOwner];
+ // Counts the total number of tasks.
+ let taskCnt = values.length;
+ // Counts the number of tasks that have the 'Complete' status.
+ // If the options you want to count in your spreadsheet differ, update the strings below to match the text of each option.
+ // To add more options, copy the line below and update the string to the new text.
+ let completeCnt = filterByPosition(values,'Complete', columnStatus).length;
+ // Counts the number of tasks that have the 'In-Progress' status.
+ let inProgressCnt = filterByPosition(values,'In-Progress', columnStatus).length;
+ // Counts the number of tasks that have the 'Scheduled' status.
+ let scheduledCnt = filterByPosition(values,'Scheduled', columnStatus).length;
+ // Counts the number of tasks that have the 'Overdue' status.
+ let overdueCnt = filterByPosition(values,'Overdue', columnStatus).length;
+ // Builds the output array.
+ outputArr.push([owner,taskCnt,completeCnt,inProgressCnt,scheduledCnt,overdueCnt,sheetNm]);
+ }
+ // Writes the output array.
+ return outputArr;
+}
+
+/**
+ * Below is a helper function that filters a 2-dimenstional array.
+ */
+function filterByPosition(array, find, position) {
+ return array.filter(innerArray => innerArray[position] === find);
+}
+
diff --git a/solutions/custom-functions/summarize-sheets-data/README.md b/solutions/custom-functions/summarize-sheets-data/README.md
new file mode 100644
index 000000000..4ae6b97ac
--- /dev/null
+++ b/solutions/custom-functions/summarize-sheets-data/README.md
@@ -0,0 +1,4 @@
+# Summarize data from multiple sheets
+
+See [developers.google.com](https://developers.google.com/apps-script/samples/custom-functions/summarize-sheets-data) for additional details.
+
diff --git a/solutions/custom-functions/summarize-sheets-data/appsscript.json b/solutions/custom-functions/summarize-sheets-data/appsscript.json
new file mode 100644
index 000000000..3cf1d247d
--- /dev/null
+++ b/solutions/custom-functions/summarize-sheets-data/appsscript.json
@@ -0,0 +1,7 @@
+{
+ "timeZone": "America/New_York",
+ "dependencies": {
+ },
+ "exceptionLogging": "STACKDRIVER",
+ "runtimeVersion": "V8"
+}
\ No newline at end of file
diff --git a/solutions/custom-functions/tier-pricing/.clasp.json b/solutions/custom-functions/tier-pricing/.clasp.json
new file mode 100644
index 000000000..c8264b479
--- /dev/null
+++ b/solutions/custom-functions/tier-pricing/.clasp.json
@@ -0,0 +1 @@
+{"scriptId": "1-ql7ECe91XZgWu-hW_UZBx8mhuTtQQj0yNITYh8yQCOuHxLEjxtTngGB"}
diff --git a/solutions/custom-functions/tier-pricing/Code.js b/solutions/custom-functions/tier-pricing/Code.js
new file mode 100644
index 000000000..9fca30cf0
--- /dev/null
+++ b/solutions/custom-functions/tier-pricing/Code.js
@@ -0,0 +1,51 @@
+// To learn how to use this script, refer to the documentation:
+// https://developers.google.com/apps-script/samples/custom-functions/tier-pricing
+
+/*
+Copyright 2022 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+/**
+ * Calculates the tiered pricing discount.
+ *
+ * You must provide a value to calculate its discount. The value can be a string or a reference
+ * to a cell that contains a string.
+ * You must provide a data table range, for example, $B$4:$D$7, that includes the
+ * tier start, end, and percent columns. If your table has headers, don't include
+ * the headers in the range.
+ *
+ * @param {string} value The value to calculate the discount for, which can be a string or a
+ * reference to a cell that contains a string.
+ * @param {string} table The tier table data range using A1 notation.
+ * @return number The total discount amount for the value.
+ * @customfunction
+ *
+ */
+function tierPrice(value, table) {
+ let total = 0;
+ // Creates an array for each row of the table and loops through each array.
+ for (let [start, end, percent] of table) {
+ // Checks if the value is less than the starting value of the tier. If it is less, the loop stops.
+ if (value < start) {
+ break;
+ }
+ // Calculates the portion of the value to be multiplied by the tier's percent value.
+ let amount = Math.min(value, end) - start;
+ // Multiplies the amount by the tier's percent value and adds the product to the total.
+ total += amount * percent;
+ }
+ return total;
+}
+
\ No newline at end of file
diff --git a/solutions/custom-functions/tier-pricing/README.md b/solutions/custom-functions/tier-pricing/README.md
new file mode 100644
index 000000000..edbadc063
--- /dev/null
+++ b/solutions/custom-functions/tier-pricing/README.md
@@ -0,0 +1,4 @@
+# Calculate a tiered pricing discount
+
+See [developers.google.com](https://developers.google.com/apps-script/samples/custom-functions/tier-pricing) for additional details.
+
diff --git a/solutions/custom-functions/tier-pricing/appsscript.json b/solutions/custom-functions/tier-pricing/appsscript.json
new file mode 100644
index 000000000..3cf1d247d
--- /dev/null
+++ b/solutions/custom-functions/tier-pricing/appsscript.json
@@ -0,0 +1,7 @@
+{
+ "timeZone": "America/New_York",
+ "dependencies": {
+ },
+ "exceptionLogging": "STACKDRIVER",
+ "runtimeVersion": "V8"
+}
\ No newline at end of file
diff --git a/solutions/editor-add-on/clean-sheet/.clasp.json b/solutions/editor-add-on/clean-sheet/.clasp.json
new file mode 100644
index 000000000..2cae3aa10
--- /dev/null
+++ b/solutions/editor-add-on/clean-sheet/.clasp.json
@@ -0,0 +1 @@
+{"scriptId": "10bxhn6eGypm20dgRcTbUCbzP4Bz0dyYR6IZTNEA2gIXXxwoy8Zqs06yr"}
diff --git a/solutions/editor-add-on/clean-sheet/Code.js b/solutions/editor-add-on/clean-sheet/Code.js
new file mode 100644
index 000000000..deb3136c3
--- /dev/null
+++ b/solutions/editor-add-on/clean-sheet/Code.js
@@ -0,0 +1,246 @@
+// To learn how to use this script, refer to the documentation:
+// https://developers.google.com/apps-script/add-ons/clean-sheet
+
+/*
+Copyright 2022 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+// Application Constants
+const APP_TITLE = 'Clean sheet';
+
+/**
+ * Identifies and deletes empty rows in selected range of active sheet.
+ *
+ * Cells that contain space characters are treated as non-empty.
+ * The entire row, including the cells outside of the selected range,
+ * must be empty to be deleted.
+ *
+ * Called from menu option.
+ */
+function deleteEmptyRows() {
+
+ const sheet = SpreadsheetApp.getActiveSheet();
+
+ // Gets active selection and dimensions.
+ let activeRange = sheet.getActiveRange();
+ const rowCount = activeRange.getHeight();
+ const firstActiveRow = activeRange.getRow();
+ const columnCount = sheet.getMaxColumns();
+
+ // Tests that the selection is a valid range.
+ if (rowCount < 1) {
+ showMessage('Select a valid range.');
+ return;
+ }
+ // Tests active range isn't too large to process. Enforces limit set to 10k.
+ if (rowCount > 10000) {
+ showMessage("Selected range too large. Select up to 10,000 rows at one time.");
+ return;
+ }
+
+ // Utilizes an array of values for efficient processing to determine blank rows.
+ const activeRangeValues = sheet.getRange(firstActiveRow, 1, rowCount, columnCount).getValues();
+
+ // Checks if array is all empty values.
+ const valueFilter = value => value !== '';
+ const isRowEmpty = (row) => {
+ return row.filter(valueFilter).length === 0;
+ }
+
+ // Maps the range values as an object with value (to test) and corresponding row index (with offset from selection).
+ const rowsToDelete = activeRangeValues.map((row, index) => ({ row, offset: index + activeRange.getRowIndex() }))
+ .filter(item => isRowEmpty(item.row)) // Test to filter out non-empty rows.
+ .map(item => item.offset); //Remap to include just the row indexes that will be removed.
+
+ // Combines a sorted, ascending list of indexes into a set of ranges capturing consecutive values as start/end ranges.
+ // Combines sequential empty rows for faster processing.
+ const rangesToDelete = rowsToDelete.reduce((ranges, index) => {
+ const currentRange = ranges[ranges.length - 1];
+ if (currentRange && index === currentRange[1] + 1) {
+ currentRange[1] = index;
+ return ranges;
+ }
+ ranges.push([index, index]);
+ return ranges;
+ }, []);
+
+ // Sends a list of row indexes to be deleted to the console.
+ console.log(rangesToDelete);
+
+ // Deletes the rows using REVERSE order to ensure proper indexing is used.
+ rangesToDelete.reverse().forEach(([start, end]) => sheet.deleteRows(start, end - start + 1));
+ SpreadsheetApp.flush();
+}
+
+/**
+ * Removes blank columns in a selected range.
+ *
+ * Cells containing Space characters are treated as non-empty.
+ * The entire column, including cells outside of the selected range,
+ * must be empty to be deleted.
+ *
+ * Called from menu option.
+ */
+function deleteEmptyColumns() {
+
+ const sheet = SpreadsheetApp.getActiveSheet();
+
+ // Gets active selection and dimensions.
+ let activeRange = sheet.getActiveRange();
+ const rowCountMax = sheet.getMaxRows();
+ const columnWidth = activeRange.getWidth();
+ const firstActiveColumn = activeRange.getColumn();
+
+ // Tests that the selection is a valid range.
+ if (columnWidth < 1) {
+ showMessage('Select a valid range.');
+ return;
+ }
+ // Tests active range is not too large to process. Enforces limit set to 1k.
+ if (columnWidth > 1000) {
+ showMessage("Selected range too large. Select up to 10,000 rows at one time.");
+ return;
+ }
+
+ // Utilizes an array of values for efficient processing to determine blank columns.
+ const activeRangeValues = sheet.getRange(1, firstActiveColumn, rowCountMax, columnWidth).getValues();
+
+ // Transposes the array of range values so it can be processed in order of columns.
+ const activeRangeValuesTransposed = activeRangeValues[0].map((_, colIndex) => activeRangeValues.map(row => row[colIndex]));
+
+ // Checks if array is all empty values.
+ const valueFilter = value => value !== '';
+ const isColumnEmpty = (column) => {
+ return column.filter(valueFilter).length === 0;
+ }
+
+ // Maps the range values as an object with value (to test) and corresponding column index (with offset from selection).
+ const columnsToDelete = activeRangeValuesTransposed.map((column, index) => ({ column, offset: index + firstActiveColumn}))
+ .filter(item => isColumnEmpty(item.column)) // Test to filter out non-empty rows.
+ .map(item => item.offset); //Remap to include just the column indexes that will be removed.
+
+ // Combines a sorted, ascending list of indexes into a set of ranges capturing consecutive values as start/end ranges.
+ // Combines sequential empty columns for faster processing.
+ const rangesToDelete = columnsToDelete.reduce((ranges, index) => {
+ const currentRange = ranges[ranges.length - 1];
+ if (currentRange && index === currentRange[1] + 1) {
+ currentRange[1] = index;
+ return ranges;
+ }
+ ranges.push([index, index]);
+ return ranges;
+ }, []);
+
+ // Sends a list of column indexes to be deleted to the console.
+ console.log(rangesToDelete);
+
+ // Deletes the columns using REVERSE order to ensure proper indexing is used.
+ rangesToDelete.reverse().forEach(([start, end]) => sheet.deleteColumns(start, end - start + 1));
+ SpreadsheetApp.flush();
+}
+
+/**
+ * Trims all of the unused rows and columns outside of selected data range.
+ *
+ * Called from menu option.
+ */
+function cropSheet() {
+ const dataRange = SpreadsheetApp.getActiveSheet().getDataRange();
+ const sheet = dataRange.getSheet();
+
+ let numRows = dataRange.getNumRows();
+ let numColumns = dataRange.getNumColumns();
+
+ const maxRows = sheet.getMaxRows();
+ const maxColumns = sheet.getMaxColumns();
+
+ const numFrozenRows = sheet.getFrozenRows();
+ const numFrozenColumns = sheet.getFrozenColumns();
+
+ // If last data row is less than maximium row, then deletes rows after the last data row.
+ if (numRows < maxRows) {
+ numRows = Math.max(numRows, numFrozenRows + 1); // Don't crop empty frozen rows.
+ sheet.deleteRows(numRows + 1, maxRows - numRows);
+ }
+
+ // If last data column is less than maximium column, then deletes columns after the last data column.
+ if (numColumns < maxColumns) {
+ numColumns = Math.max(numColumns, numFrozenColumns + 1); // Don't crop empty frozen columns.
+ sheet.deleteColumns(numColumns + 1, maxColumns - numColumns);
+ }
+}
+
+/**
+ * Copies value of active cell to the blank cells beneath it.
+ * Stops at last row of the sheet's data range if only blank cells are encountered.
+ *
+ * Called from menu option.
+ */
+function fillDownData() {
+
+ const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
+
+ // Gets sheet's active cell and confirms it's not empty.
+ const activeCell = sheet.getActiveCell();
+ const activeCellValue = activeCell.getValue();
+
+ if (!activeCellValue) {
+ showMessage("The active cell is empty. Nothing to fill.");
+ return;
+ }
+
+ // Gets coordinates of active cell.
+ const column = activeCell.getColumn();
+ const row = activeCell.getRow();
+
+ // Gets entire data range of the sheet.
+ const dataRange = sheet.getDataRange();
+ const dataRangeRows = dataRange.getNumRows();
+
+ // Gets trimmed range starting from active cell to the end of sheet data range.
+ const searchRange = dataRange.offset(row - 1, column - 1, dataRangeRows - row + 1, 1)
+ const searchValues = searchRange.getDisplayValues();
+
+ // Find the number of empty rows below the active cell.
+ let i = 1; // Start at 1 to skip the ActiveCell.
+ while (searchValues[i] && searchValues[i][0] == "") { i++; }
+
+ // If blanks exist, fill the range with values.
+ if (i > 1) {
+ const fillRange = searchRange.offset(0, 0, i, 1).setValue(activeCellValue)
+ //sheet.setActiveRange(fillRange) // Uncomment to test affected range.
+ }
+ else {
+ showMessage("There are no empty cells below the Active Cell to fill.");
+ }
+}
+
+/**
+ * A helper function to display messages to user.
+ *
+ * @param {string} message - Message to be displayed.
+ * @param {string} caller - {Optional} text to append to title.
+ */
+function showMessage(message, caller) {
+
+ // Sets the title using the APP_TITLE variable; adds optional caller string.
+ const title = APP_TITLE
+ if (caller != null) {
+ title += ` : ${caller}`
+ };
+
+ const ui = SpreadsheetApp.getUi();
+ ui.alert(title, message, ui.ButtonSet.OK);
+}
diff --git a/solutions/editor-add-on/clean-sheet/Menu.js b/solutions/editor-add-on/clean-sheet/Menu.js
new file mode 100644
index 000000000..fb6feca40
--- /dev/null
+++ b/solutions/editor-add-on/clean-sheet/Menu.js
@@ -0,0 +1,60 @@
+/**
+ * Copyright 2022 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Creates a menu entry in the Google Sheets Extensions menu when the document is opened.
+ *
+ * @param {object} e The event parameter for a simple onOpen trigger.
+ */
+function onOpen(e) {
+ // Builds a menu that displays under the Extensions menu in Sheets.
+ let menu = SpreadsheetApp.getUi().createAddonMenu()
+
+ menu
+ .addItem('Delete blank rows (from selected rows only)', 'deleteEmptyRows')
+ .addItem('Delete blank columns (from selected columns only)', 'deleteEmptyColumns')
+ .addItem('Crop sheet to data range', 'cropSheet')
+ .addSeparator()
+ .addItem('Fill in blank rows below', 'fillDownData')
+ .addSeparator()
+ .addItem('About', 'aboutApp')
+ .addToUi();
+}
+
+/**
+ * Runs when the add-on is installed; calls onOpen() to ensure menu creation and
+ * any other initializion work is done immediately. This method is only used by
+ * the desktop add-on and is never called by the mobile version.
+ *
+ * @param {object} e The event parameter for a simple onInstall trigger.
+ */
+function onInstall(e) {
+ onOpen(e);
+}
+
+/**
+ * About box for context and developer contact information.
+ * TODO: Personalize
+ */
+function aboutApp() {
+ const msg = `
+ Name: ${APP_TITLE}
+ Version: 1.0
+ Contact: `
+
+ const ui = SpreadsheetApp.getUi();
+ ui.alert("About this application", msg, ui.ButtonSet.OK);
+}
\ No newline at end of file
diff --git a/solutions/editor-add-on/clean-sheet/README.md b/solutions/editor-add-on/clean-sheet/README.md
new file mode 100644
index 000000000..11a3932ca
--- /dev/null
+++ b/solutions/editor-add-on/clean-sheet/README.md
@@ -0,0 +1,4 @@
+# Clean up data in a spreadsheet
+
+See [developers.google.com](https://developers.google.com/apps-script/add-ons/clean-sheet) for additional details.
+
diff --git a/solutions/editor-add-on/clean-sheet/appsscript.json b/solutions/editor-add-on/clean-sheet/appsscript.json
new file mode 100644
index 000000000..3cf1d247d
--- /dev/null
+++ b/solutions/editor-add-on/clean-sheet/appsscript.json
@@ -0,0 +1,7 @@
+{
+ "timeZone": "America/New_York",
+ "dependencies": {
+ },
+ "exceptionLogging": "STACKDRIVER",
+ "runtimeVersion": "V8"
+}
\ No newline at end of file
diff --git a/solutions/ooo-chat-app/Code.js b/solutions/ooo-chat-app/Code.js
new file mode 100644
index 000000000..b03dde223
--- /dev/null
+++ b/solutions/ooo-chat-app/Code.js
@@ -0,0 +1,246 @@
+/*
+Copyright 2022 Google LLC
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+ https://www.apache.org/licenses/LICENSE-2.0
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+/**
+ * Responds to an ADDED_TO_SPACE event in Chat.
+ * @param {object} event the event object from Chat
+ * @return {object} JSON-formatted response
+ * @see https://developers.google.com/hangouts/chat/reference/message-formats/events
+ */
+function onAddToSpace(event) {
+ let message = 'Thank you for adding me to ';
+ if (event.space.type === 'DM') {
+ message += 'a DM, ' + event.user.displayName + '!';
+ } else {
+ message += event.space.displayName;
+ }
+ return { text: message };
+}
+
+/**
+ * Responds to a REMOVED_FROM_SPACE event in Chat.
+ * @param {object} event the event object from Chat
+ * @param {object} event the event object from Chat
+ * @see https://developers.google.com/hangouts/chat/reference/message-formats/events
+ */
+function onRemoveFromSpace(event) {
+ console.log('App removed from ', event.space.name);
+}
+
+
+/**
+ * Responds to a MESSAGE event triggered in Chat.
+ * @param {object} event the event object from Chat
+ * @return {function} call the respective function
+ */
+function onMessage(event) {
+ const message = event.message;
+
+ if (message.slashCommand) {
+ switch (message.slashCommand.commandId) {
+ case 1: // Help command
+ return createHelpCard();
+ case 2: // Block out day command
+ return blockDayOut();
+ case 3: // Cancel all meetings command
+ return cancelAllMeetings();
+ case 4: // Set auto reply command
+ return setAutoReply();
+ }
+ }
+}
+
+function createHelpCard() {
+ return {
+ "cardsV2": [
+ {
+ "cardId": "2",
+ "card": {
+ "sections": [
+ {
+ "header": "",
+ "widgets": [
+ {
+ "decoratedText": {
+ "topLabel": "",
+ "text": "Hi! 👋 I'm here to help you with your out of office tasks.
Here's a list of commands I understand.",
+ "wrapText": true
+ }
+ }
+ ]
+ },
+ {
+ "widgets": [
+ {
+ "decoratedText": {
+ "topLabel": "",
+ "text": "/blockDayOut: I will block out your calendar for you.",
+ "wrapText": true
+ }
+ },
+ {
+ "decoratedText": {
+ "topLabel": "",
+ "text": "/cancelAllMeetings: I will cancel all your meetings for the day.",
+ "wrapText": true
+ }
+ },
+ {
+ "decoratedText": {
+ "topLabel": "",
+ "text": "/setAutoReply: Set an out of office auto reply in Gmail.",
+ "wrapText": true
+ }
+ }
+ ]
+ }
+ ],
+ "header": {
+ "title": "OOO app",
+ "subtitle": "Helping you manage your OOO",
+ "imageUrl": "https://goo.gle/3SfMkjb",
+ "imageType": "SQUARE"
+ }
+ }
+ }
+ ]
+ }
+}
+
+/**
+ * Adds an all day event to the users Google Calendar.
+ * @return {object} JSON-formatted response
+ */
+function blockDayOut() {
+ blockOutCalendar();
+ return createResponseCard('Your calendar has been blocked out for you.')
+}
+
+/**
+ * Cancels all of the users meeting for the current day.
+ * @return {object} JSON-formatted response
+ */
+function cancelAllMeetings() {
+ cancelMeetings();
+ return createResponseCard('All your meetings have been canceled.')
+}
+
+/**
+ * Sets an out of office auto reply in the users Gmail account.
+ * @return {object} JSON-formatted response
+ */
+function setAutoReply() {
+ turnOnAutoResponder();
+ return createResponseCard('The out of office auto reply has been turned on.')
+}
+
+
+
+/**
+ * Creates an out of office event in the user's Calendar.
+ */
+function blockOutCalendar() {
+ /**
+ * Helper function to get a the current date and set the time for the start and end of the event.
+ * @param {number} hour The hour of the day for the new date.
+ * @param {number} minutes The minutes of the day for the new date.
+ * @return {Date} The new date.
+ */
+ function getDateAndHours(hour, minutes) {
+ const date = new Date();
+ date.setHours(hour);
+ date.setMinutes(minutes);
+ date.setSeconds(0);
+ date.setMilliseconds(0);
+ return date.toISOString();
+ }
+
+ const event = {
+ start: {dateTime: getDateAndHours(9,00)},
+ end: {dateTime: getDateAndHours(17,00)},
+ eventType: 'outOfOffice',
+ summary: 'Out of office',
+ outOfOfficeProperties: {
+ autoDeclineMode: 'declineOnlyNewConflictingInvitations',
+ declineMessage: 'Declined because I am taking a day of.',
+ }
+ }
+ Calendar.Events.insert(event, 'primary');
+}
+
+/**
+ * Declines all meetings for the day.
+ */
+function cancelMeetings() {
+ const events = CalendarApp.getEventsForDay(new Date());
+
+ events.forEach(function(event) {
+ if (event.getGuestList().length > 0) {
+ event.setMyStatus(CalendarApp.GuestStatus.NO);
+ }
+ });
+}
+
+/**
+ * Turns on the user's vacation response for today in Gmail.
+ */
+function turnOnAutoResponder() {
+ const ONE_DAY_MILLIS = 24 * 60 * 60 * 1000;
+ const currentTime = (new Date()).getTime();
+ Gmail.Users.Settings.updateVacation({
+ enableAutoReply: true,
+ responseSubject: 'I am out of the office today',
+ responseBodyHtml: 'I am out of the office today; will be back on the next business day.