diff --git a/.eslintrc.js b/.eslintrc.js index eb416789c..114dd6491 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,3 +1,19 @@ +/** + * 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. + */ + module.exports = { extends: 'google', parserOptions: { @@ -10,16 +26,16 @@ module.exports = { rules: { 'comma-dangle': ['error', 'never'], 'max-len': ['error', { code: 100 }], - camelcase: 'off', // Off for destructuring - 'async-await/space-after-async': 2, - 'async-await/space-after-await': 2, - eqeqeq: 2, + 'camelcase': ['error', { + 'ignoreDestructuring': true, + 'ignoreImports': true, + 'allow': ['access_type', 'redirect_uris'], + }], 'guard-for-in': 'off', 'no-var': 'off', // ES3 'no-unused-vars': 'off' // functions aren't used. }, plugins: [ - 'async-await', 'googleappsscript' ] } diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 000000000..804a0939c --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,17 @@ +# 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. + +# https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners + +.github/ @googleworkspace/workspace-devrel-dpe diff --git a/.github/linters/.yaml-lint.yml b/.github/linters/.yaml-lint.yml new file mode 100644 index 000000000..e8394fd59 --- /dev/null +++ b/.github/linters/.yaml-lint.yml @@ -0,0 +1,59 @@ +--- +########################################### +# These are the rules used for # +# linting all the yaml files in the stack # +# NOTE: # +# You can disable line with: # +# # yamllint disable-line # +########################################### +rules: + braces: + level: warning + min-spaces-inside: 0 + max-spaces-inside: 0 + min-spaces-inside-empty: 1 + max-spaces-inside-empty: 5 + brackets: + level: warning + min-spaces-inside: 0 + max-spaces-inside: 0 + min-spaces-inside-empty: 1 + max-spaces-inside-empty: 5 + colons: + level: warning + max-spaces-before: 0 + max-spaces-after: 1 + commas: + level: warning + max-spaces-before: 0 + min-spaces-after: 1 + max-spaces-after: 1 + comments: disable + comments-indentation: disable + document-end: disable + document-start: + level: warning + present: true + empty-lines: + level: warning + max: 2 + max-start: 0 + max-end: 0 + hyphens: + level: warning + max-spaces-after: 1 + indentation: + level: warning + spaces: consistent + indent-sequences: true + check-multi-line-strings: false + key-duplicates: enable + line-length: + level: warning + max: 120 + allow-non-breakable-words: true + allow-non-breakable-inline-mappings: true + new-line-at-end-of-file: disable + new-lines: + type: unix + trailing-spaces: disable \ No newline at end of file diff --git a/.github/linters/sun_checks.xml b/.github/linters/sun_checks.xml new file mode 100644 index 000000000..76d0840d0 --- /dev/null +++ b/.github/linters/sun_checks.xml @@ -0,0 +1,374 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.github/scripts/clasp_push.sh b/.github/scripts/clasp_push.sh new file mode 100755 index 000000000..4d0ad7288 --- /dev/null +++ b/.github/scripts/clasp_push.sh @@ -0,0 +1,52 @@ +#! /bin/bash +# Copyright 2020 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. + +export LC_ALL=C.UTF-8 +export LANG=C.UTF-8 + +function contains_changes() { + [[ "${*:2}" = "" ]] && return 0 + for f in "${@:2}"; do + case $(realpath "$f")/ in + $(realpath "$1")/*) return 0;; + esac + done + return 1 +} + +changed_files=$(echo "${@:1}" | xargs realpath | xargs -I {} dirname {}| sort -u | uniq) +dirs=() + +IFS=$'\n' read -r -d '' -a dirs < <( find . -name '.clasp.json' -exec dirname '{}' \; | sort -u | xargs realpath ) + +exit_code=0 + +for dir in "${dirs[@]}"; do + pushd "${dir}" > /dev/null || exit + contains_changes "$dir" "${changed_files[@]}" || continue + echo "Publishing ${dir}" + clasp push -f + status=$? + if [ $status -ne 0 ]; then + exit_code=$status + fi + popd > /dev/null || exit +done + +if [ $exit_code -ne 0 ]; then + echo "Script push failed." +fi + +exit $exit_code \ No newline at end of file diff --git a/.github/snippet-bot.yml b/.github/snippet-bot.yml new file mode 100644 index 000000000..bb488a813 --- /dev/null +++ b/.github/snippet-bot.yml @@ -0,0 +1,14 @@ +# 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. + diff --git a/.github/sync-repo-settings.yaml b/.github/sync-repo-settings.yaml new file mode 100644 index 000000000..7b363bc42 --- /dev/null +++ b/.github/sync-repo-settings.yaml @@ -0,0 +1,41 @@ +# 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. + +# .github/sync-repo-settings.yaml +# See https://github.com/googleapis/repo-automation-bots/tree/main/packages/sync-repo-settings for app options. +rebaseMergeAllowed: true +squashMergeAllowed: true +mergeCommitAllowed: false +deleteBranchOnMerge: true +branchProtectionRules: + - pattern: main + isAdminEnforced: false + requiresStrictStatusChecks: false + requiredStatusCheckContexts: + # .github/workflows/test.yml with a job called "test" + - "test" + # .github/workflows/lint.yml with a job called "lint" + - "lint" + # Google bots below + - "cla/google" + - "snippet-bot check" + - "header-check" + - "conventionalcommits.org" + requiredApprovingReviewCount: 1 + requiresCodeOwnerReviews: true +permissionRules: + - team: workspace-devrel-dpe + permission: admin + - team: workspace-devrel + permission: push diff --git a/.github/workflows/automation.yml b/.github/workflows/automation.yml new file mode 100644 index 000000000..95f323bfb --- /dev/null +++ b/.github/workflows/automation.yml @@ -0,0 +1,69 @@ +# 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. +--- +name: Automation +on: [ push, pull_request, workflow_dispatch ] +jobs: + dependabot: + runs-on: ubuntu-latest + if: ${{ github.actor == 'dependabot[bot]' && github.event_name == 'pull_request' }} + env: + PR_URL: ${{github.event.pull_request.html_url}} + GITHUB_TOKEN: ${{secrets.GOOGLEWORKSPACE_BOT_TOKEN}} + steps: + - name: approve + run: gh pr review --approve "$PR_URL" + - name: merge + run: gh pr merge --auto --squash --delete-branch "$PR_URL" + default-branch-migration: + # this job helps with migrating the default branch to main + # it pushes main to master if master exists and main is the default branch + # it pushes master to main if master is the default branch + runs-on: ubuntu-latest + if: ${{ github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master' }} + steps: + - uses: actions/checkout@v2 + with: + fetch-depth: 0 + # required otherwise GitHub blocks infinite loops in pushes originating in an action + token: ${{ secrets.GOOGLEWORKSPACE_BOT_TOKEN }} + - name: Set env + run: | + # set DEFAULT BRANCH + echo "DEFAULT_BRANCH=$(gh repo view --json defaultBranchRef --jq '.defaultBranchRef.name')" >> "$GITHUB_ENV"; + + # set HAS_MASTER_BRANCH + if [ -n "$(git ls-remote --heads origin master)" ]; then + echo "HAS_MASTER_BRANCH=true" >> "$GITHUB_ENV" + else + echo "HAS_MASTER_BRANCH=false" >> "$GITHUB_ENV" + fi + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: configure git + run: | + git config --global user.name 'googleworkspace-bot' + git config --global user.email 'googleworkspace-bot@google.com' + - if: ${{ env.DEFAULT_BRANCH == 'main' && env.HAS_MASTER_BRANCH == 'true' }} + name: Update master branch from main + run: | + git checkout -B master + git reset --hard origin/main + git push origin master + - if: ${{ env.DEFAULT_BRANCH == 'master'}} + name: Update main branch from master + run: | + git checkout -B main + git reset --hard origin/master + git push origin main diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yml similarity index 85% rename from .github/workflows/lint.yaml rename to .github/workflows/lint.yml index db03d2151..fd65241d3 100644 --- a/.github/workflows/lint.yaml +++ b/.github/workflows/lint.yml @@ -11,15 +11,9 @@ # 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. +--- name: Lint -on: - workflow_dispatch: - push: - branches: - - master - pull_request: - branches: - - master +on: [push, pull_request, workflow_dispatch] jobs: lint: concurrency: @@ -27,10 +21,10 @@ jobs: cancel-in-progress: true runs-on: ubuntu-20.04 steps: - - uses: actions/checkout@v3.0.0 + - uses: actions/checkout@v3.0.2 with: fetch-depth: 0 - - uses: github/super-linter/slim@v4.9.0 + - uses: github/super-linter/slim@v4.9.4 env: ERROR_ON_MISSING_EXEC_BIT: true VALIDATE_JSCPD: false diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml new file mode 100644 index 000000000..292075162 --- /dev/null +++ b/.github/workflows/publish.yaml @@ -0,0 +1,43 @@ +# Copyright 2021 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. +--- +name: Publish Apps Script +on: + workflow_dispatch: + push: + branches: + - main +jobs: + publish: + concurrency: + group: ${{ github.head_ref || github.ref }} + cancel-in-progress: false + runs-on: ubuntu-20.04 + steps: + - uses: actions/checkout@v3.0.2 + with: + fetch-depth: 0 + - name: Get changed files + id: changed-files + uses: tj-actions/changed-files@v23.1 + - name: Write test credentials + run: | + echo "${CLASP_CREDENTIALS}" > "${HOME}/.clasprc.json" + env: + CLASP_CREDENTIALS: ${{secrets.CLASP_CREDENTIALS}} + - uses: actions/setup-node@v3 + with: + node-version: '14' + - run: npm install -g @google/clasp + - run: ./.github/scripts/clasp_push.sh ${{ steps.changed-files.outputs.all_changed_files }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 000000000..debf46551 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,24 @@ +# 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. + +name: Test +on: [push, pull_request] +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - run: | + echo "No tests"; + exit 1; diff --git a/LICENSE b/LICENSE index d64569567..4c7a704c1 100644 --- a/LICENSE +++ b/LICENSE @@ -1,23 +1,23 @@ +B5690EEEBB952194 + Apapache engedély + 2.0. változat 2004. január 2.0. változat + http://www.apache.org/licenses/ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ + A HASZNÁLAT, A SZAPORODÁS ÉS AZ ELOSZTÁS FELTÉTELEI - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + 1. Meghatárok. - 1. Definitions. + A "engedély" a használat feltételeit, a szaporodást jelenti, + és a dokumentum 1. és 9. szakasza által meghatározott elosztás. - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. + Az "engedélyor" a szerzői jog tulajdonosát vagy jogalanyt jelenti, amelyet a szerzői jog tulajdonosa vagy jogalany + a szerzői jogi tulajdonos, aki az engedélyt biztosítja. - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or + A "jogi sértés" a jogalany és minden + más olyan jogalanyok, amelyek ellenőrzik vagy közös jellegűek + az a jogalany ellenőrzése. E meghatározás érdekében, + Az "ellenőrzés" azt jelenti (i) a hatalom, közvetlen vagy közvetett, hogy a + az ilyen jogalany irányítása vagy kezelése, akár szerződéssel, akár otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. diff --git a/README.md b/README.md index faba5fdc3..92d6209db 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Google Apps Script Samples [![Build Status](https://travis-ci.org/googleworkspace/apps-script-samples.svg?branch=master)](https://travis-ci.org/googleworkspace/apps-script-samples) +# Google Apps Script Samples Various sample code and projects for the Google Apps Script platform, a JavaScript platform in the cloud. @@ -28,7 +28,7 @@ align="left" width="96px"/> ### Calendar - [List upcoming events](calendar/quickstart) -- [Create a vacation calendar](calendar/vacationCalendar) +- [Create a vacation calendar](solutions/automations/vacation-calendar/Code.js) header.name)); + // Append the headers. + sheet.appendRow(report.headers.map((header) => header.name)); - // Append the results. - sheet.getRange(2, 1, report.rows.length, report.headers.length) - .setValues(report.rows.map((row) => row.cells.map((cell) => cell.value))); + // Append the results. + sheet.getRange(2, 1, report.rows.length, report.headers.length) + .setValues(report.rows.map((row) => row.cells.map((cell) => cell.value))); - Logger.log('Report spreadsheet created: %s', - spreadsheet.getUrl()); - } else { - Logger.log('No rows returned.'); - } + console.log('Report spreadsheet created: %s', + spreadsheet.getUrl()); } /** diff --git a/advanced/analytics.gs b/advanced/analytics.gs index 79b551b92..a691ce4a2 100644 --- a/advanced/analytics.gs +++ b/advanced/analytics.gs @@ -21,20 +21,20 @@ function listAccounts() { try { const accounts = Analytics.Management.Accounts.list(); if (!accounts.items || !accounts.items.length) { - Logger.log('No accounts found.'); + console.log('No accounts found.'); return; } for (let i = 0; i < accounts.items.length; i++) { const account = accounts.items[i]; - Logger.log('Account: name "%s", id "%s".', account.name, account.id); + console.log('Account: name "%s", id "%s".', account.name, account.id); // List web properties in the account. listWebProperties(account.id); } } catch (e) { // TODO (Developer) - Handle exception - Logger.log('Failed with error: %s', e.error); + console.log('Failed with error: %s', e.error); } } @@ -46,12 +46,12 @@ function listWebProperties(accountId) { try { const webProperties = Analytics.Management.Webproperties.list(accountId); if (!webProperties.items || !webProperties.items.length) { - Logger.log('\tNo web properties found.'); + console.log('\tNo web properties found.'); return; } for (let i = 0; i < webProperties.items.length; i++) { const webProperty = webProperties.items[i]; - Logger.log('\tWeb Property: name "%s", id "%s".', + console.log('\tWeb Property: name "%s", id "%s".', webProperty.name, webProperty.id); // List profiles in the web property. @@ -59,7 +59,7 @@ function listWebProperties(accountId) { } } catch (e) { // TODO (Developer) - Handle exception - Logger.log('Failed with error: %s', e.error); + console.log('Failed with error: %s', e.error); } } @@ -77,17 +77,17 @@ function listProfiles(accountId, webPropertyId) { webPropertyId); if (!profiles.items || !profiles.items.length) { - Logger.log('\t\tNo web properties found.'); + console.log('\t\tNo web properties found.'); return; } for (let i = 0; i < profiles.items.length; i++) { const profile = profiles.items[i]; - Logger.log('\t\tProfile: name "%s", id "%s".', profile.name, + console.log('\t\tProfile: name "%s", id "%s".', profile.name, profile.id); } } 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_analytics_accounts] @@ -118,7 +118,7 @@ function runReport(profileId) { options); if (!report.rows) { - Logger.log('No rows returned.'); + console.log('No rows returned.'); return; } @@ -135,7 +135,7 @@ function runReport(profileId) { sheet.getRange(2, 1, report.rows.length, headers.length) .setValues(report.rows); - Logger.log('Report spreadsheet created: %s', + console.log('Report spreadsheet created: %s', spreadsheet.getUrl()); } // [END apps_script_analytics_reports] diff --git a/advanced/analyticsAdmin.gs b/advanced/analyticsAdmin.gs index b995a1d79..973388fd5 100644 --- a/advanced/analyticsAdmin.gs +++ b/advanced/analyticsAdmin.gs @@ -21,17 +21,17 @@ function listAccounts() { try { accounts = AnalyticsAdmin.Accounts.list(); if (!accounts.items || !accounts.items.length) { - Logger.log('No accounts found.'); + console.log('No accounts found.'); return; } for (let i = 0; i < accounts.items.length; i++) { const account = accounts.items[i]; - Logger.log('Account: name "%s", displayName "%s".', account.name, account.displayName); + console.log('Account: name "%s", displayName "%s".', account.name, account.displayName); } } 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_analyticsadmin] diff --git a/advanced/analyticsData.gs b/advanced/analyticsData.gs index 3371ec144..b881998d1 100644 --- a/advanced/analyticsData.gs +++ b/advanced/analyticsData.gs @@ -44,7 +44,7 @@ function runReport() { const report = AnalyticsData.Properties.runReport(request, 'properties/' + propertyId); if (!report.rows) { - Logger.log('No rows returned.'); + console.log('No rows returned.'); return; } @@ -80,11 +80,11 @@ function runReport() { sheet.getRange(2, 1, report.rows.length, headers.length) .setValues(rows); - Logger.log('Report spreadsheet created: %s', + console.log('Report spreadsheet created: %s', spreadsheet.getUrl()); } 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_analyticsdata] diff --git a/advanced/bigquery.gs b/advanced/bigquery.gs index 46431f09b..a4127aa1b 100644 --- a/advanced/bigquery.gs +++ b/advanced/bigquery.gs @@ -24,8 +24,12 @@ function runQuery() { const request = { // TODO (developer) - Replace query with yours - query: 'SELECT TOP(word, 300) AS word, COUNT(*) AS word_count ' + - 'FROM `publicdata.samples.shakespeare` WHERE LENGTH(word) > 10;', + query: 'SELECT refresh_date AS Day, term AS Top_Term, rank ' + + 'FROM `bigquery-public-data.google_trends.top_terms` ' + + 'WHERE rank = 1 ' + + 'AND refresh_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 2 WEEK) ' + + 'GROUP BY Day, Top_Term, rank ' + + 'ORDER BY Day DESC;', useLegacySql: false }; let queryResults = BigQuery.Jobs.query(request, projectId); @@ -49,10 +53,10 @@ function runQuery() { } if (!rows) { - Logger.log('No rows returned.'); + console.log('No rows returned.'); return; } - const spreadsheet = SpreadsheetApp.create('BiqQuery Results'); + const spreadsheet = SpreadsheetApp.create('BigQuery Results'); const sheet = spreadsheet.getActiveSheet(); // Append the headers. @@ -62,7 +66,7 @@ function runQuery() { sheet.appendRow(headers); // Append the results. - var data = new Array(rows.length); + const data = new Array(rows.length); for (let i = 0; i < rows.length; i++) { const cols = rows[i].f; data[i] = new Array(cols.length); @@ -72,8 +76,7 @@ function runQuery() { } sheet.getRange(2, 1, rows.length, headers.length).setValues(data); - Logger.log('Results spreadsheet created: %s', - spreadsheet.getUrl()); + console.log('Results spreadsheet created: %s', spreadsheet.getUrl()); } // [END apps_script_bigquery_run_query] @@ -111,9 +114,9 @@ function loadCsv() { }; try { table = BigQuery.Tables.insert(table, projectId, datasetId); - Logger.log('Table created: %s', table.id); + console.log('Table created: %s', table.id); } catch (err) { - Logger.log('unable to create table'); + console.log('unable to create table'); } // Load CSV data from Drive and convert to the correct format for upload. const file = DriveApp.getFileById(csvFileId); @@ -133,11 +136,10 @@ function loadCsv() { } }; try { - BigQuery.Jobs.insert(job, projectId, data); - Logger.log('Load job started. Check on the status of it here: ' + - 'https://bigquery.cloud.google.com/jobs/%s', projectId); + const jobResult = BigQuery.Jobs.insert(job, projectId, data); + console.log(`Load job started. Status: ${jobResult.status.state}`); } catch (err) { - Logger.log('unable to insert job'); + console.log('unable to insert job'); } } // [END apps_script_bigquery_load_csv] diff --git a/advanced/calendar.gs b/advanced/calendar.gs index e0d00f989..f41a54fda 100644 --- a/advanced/calendar.gs +++ b/advanced/calendar.gs @@ -28,12 +28,12 @@ function listCalendars() { }); if (!calendars.items || calendars.items.length === 0) { - Logger.log('No calendars found.'); + console.log('No calendars found.'); return; } // Print the calendar id and calendar summary for (const calendar of calendars.items) { - Logger.log('%s (ID: %s)', calendar.summary, calendar.id); + console.log('%s (ID: %s)', calendar.summary, calendar.id); } pageToken = calendars.nextPageToken; } while (pageToken); @@ -70,9 +70,9 @@ function createEvent() { try { // call method to insert/create new event in provided calandar event = Calendar.Events.insert(event, calendarId); - Logger.log('Event ID: ' + event.id); + console.log('Event ID: ' + event.id); } catch (err) { - Logger.log('Failed with error %s', err.message); + console.log('Failed with error %s', err.message); } } @@ -109,18 +109,18 @@ function listNext10Events() { maxResults: 10 }); if (!events.items || events.items.length === 0) { - Logger.log('No events found.'); + console.log('No events found.'); return; } for (const event of events.items) { if (event.start.date) { // All-day event. const start = new Date(event.start.date); - Logger.log('%s (%s)', event.summary, start.toLocaleDateString()); - return; + console.log('%s (%s)', event.summary, start.toLocaleDateString()); + continue; } const start = new Date(event.start.dateTime); - Logger.log('%s (%s)', event.summary, start.toLocaleString()); + console.log('%s (%s)', event.summary, start.toLocaleString()); } } // [END calendar_list_events] @@ -165,22 +165,22 @@ function logSyncedEvents(calendarId, fullSync) { throw new Error(e.message); } if (events.items && events.items.length === 0) { - Logger.log('No events found.'); + console.log('No events found.'); return; } for (const event of events.items) { if (event.status === 'cancelled') { - Logger.log('Event id %s was cancelled.', event.id); + console.log('Event id %s was cancelled.', event.id); return; } if (event.start.date) { const start = new Date(event.start.date); - Logger.log('%s (%s)', event.summary, start.toLocaleDateString()); + console.log('%s (%s)', event.summary, start.toLocaleDateString()); return; } // Events that don't last all day; they have defined start times. const start = new Date(event.start.dateTime); - Logger.log('%s (%s)', event.summary, start.toLocaleString()); + console.log('%s (%s)', event.summary, start.toLocaleString()); } pageToken = events.nextPageToken; } while (pageToken); @@ -221,7 +221,7 @@ function conditionalUpdate() { colorId: 11 }; event = Calendar.Events.insert(event, calendarId); - Logger.log('Event ID: ' + event.getId()); + console.log('Event ID: ' + event.getId()); // Wait 30 seconds to see if the event has been updated outside this script. Utilities.sleep(30 * 1000); // Try to update the event, on the condition that the event state has not @@ -235,9 +235,9 @@ function conditionalUpdate() { {}, {'If-Match': event.etag} ); - Logger.log('Successfully updated event: ' + event.id); + console.log('Successfully updated event: ' + event.id); } catch (e) { - Logger.log('Fetch threw an exception: ' + e); + console.log('Fetch threw an exception: ' + e); } } // [END calendar_conditional_update] @@ -275,15 +275,15 @@ function conditionalFetch() { try { // insert event event = Calendar.Events.insert(event, calendarId); - Logger.log('Event ID: ' + event.getId()); + console.log('Event ID: ' + event.getId()); // Re-fetch the event each second, but only get a result if it has changed. for (let i = 0; i < 30; i++) { Utilities.sleep(1000); event = Calendar.Events.get(calendarId, event.id, {}, {'If-None-Match': event.etag}); - Logger.log('New event description: ' + event.start.dateTime); + console.log('New event description: ' + event.start.dateTime); } } catch (e) { - Logger.log('Fetch threw an exception: ' + e); + console.log('Fetch threw an exception: ' + e); } } // [END calendar_conditional_fetch] diff --git a/advanced/chat.gs b/advanced/chat.gs new file mode 100644 index 000000000..9cb506934 --- /dev/null +++ b/advanced/chat.gs @@ -0,0 +1,118 @@ +/** + * 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 chat_post_message_with_user_credentials] +/** + * Posts a new message to the specified space on behalf of the user. + * @param {string} spaceName The resource name of the space. + */ +function postMessageWithUserCredentials(spaceName) { + try { + const message = {'text': 'Hello world!'}; + Chat.Spaces.Messages.create(message, spaceName); + } catch (err) { + // TODO (developer) - Handle exception + console.log('Failed to create message with error %s', err.message); + } +} +// [END chat_post_message_with_user_credentials] + +// [START chat_post_message_with_app_credentials] +/** + * Posts a new message to the specified space on behalf of the app. + * @param {string} spaceName The resource name of the space. + */ +function postMessageWithAppCredentials(spaceName) { + try { + // See https://developers.google.com/chat/api/guides/auth/service-accounts + // for details on how to obtain a service account OAuth token. + const appToken = getToken_(); + const message = {'text': 'Hello world!'}; + Chat.Spaces.Messages.create( + message, + spaceName, + {}, + // Authenticate with the service account token. + {'Authorization': 'Bearer ' + appToken}); + } catch (err) { + // TODO (developer) - Handle exception + console.log('Failed to create message with error %s', err.message); + } +} +// [END chat_post_message_with_app_credentials] + +// [START chat_get_space] +/** + * Gets information about a Chat space. + * @param {string} spaceName The resource name of the space. + */ +function getSpace(spaceName) { + try { + const space = Chat.Spaces.get(spaceName); + console.log('Space display name: %s', space.displayName); + console.log('Space type: %s', space.spaceType); + } catch (err) { + // TODO (developer) - Handle exception + console.log('Failed to get space with error %s', err.message); + } +} +// [END chat_get_space] + +// [START chat_create_space] +/** + * Creates a new Chat space. + */ +function createSpace() { + try { + const space = {'displayName': 'New Space', 'spaceType': 'SPACE'}; + Chat.Spaces.create(space); + } catch (err) { + // TODO (developer) - Handle exception + console.log('Failed to create space with error %s', err.message); + } +} +// [END chat_create_space] + +// [START chat_list_memberships] +/** + * Lists all the members of a Chat space. + * @param {string} spaceName The resource name of the space. + */ +function listMemberships(spaceName) { + let response; + let pageToken = null; + try { + do { + response = Chat.Spaces.Members.list(spaceName, { + pageSize: 10, + pageToken: pageToken + }); + if (!response.memberships || response.memberships.length === 0) { + pageToken = response.nextPageToken; + continue; + } + response.memberships.forEach((membership) => console.log( + 'Member resource name: %s (type: %s)', + membership.name, + membership.member.type)); + pageToken = response.nextPageToken; + } while (pageToken); + } catch (err) { + // TODO (developer) - Handle exception + console.log('Failed with error %s', err.message); + } +} +// [END chat_list_memberships] diff --git a/advanced/classroom.gs b/advanced/classroom.gs index c23ed97fc..1dc7c8a54 100644 --- a/advanced/classroom.gs +++ b/advanced/classroom.gs @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// [START classroom_list_courses] +// [START apps_script_classroom_list_courses] /** * Lists 10 course names and IDs. */ @@ -29,16 +29,16 @@ function listCourses() { const response = Classroom.Courses.list(optionalArgs); const courses = response.courses; if (!courses || courses.length === 0) { - Logger.log('No courses found.'); + console.log('No courses found.'); return; } // Print the course names and IDs of the available courses. for (const course in courses) { - Logger.log('%s (%s)', courses[course].name, courses[course].id); + console.log('%s (%s)', courses[course].name, courses[course].id); } } catch (err) { // TODO (developer)- Handle Courses.list() exception from Classroom API - Logger.log('Failed with error %s', err.message); + console.log('Failed with error %s', err.message); } } -// [END classroom_list_courses] +// [END apps_script_classroom_list_courses] diff --git a/advanced/docs.gs b/advanced/docs.gs index 76763dbb3..c8721bf5e 100644 --- a/advanced/docs.gs +++ b/advanced/docs.gs @@ -24,11 +24,11 @@ function createDocument() { try { // Create document with title const document = Docs.Documents.create({'title': 'My New Document'}); - Logger.log('Created document with ID: ' + document.documentId); + console.log('Created document with ID: ' + document.documentId); return document.documentId; } catch (e) { // TODO (developer) - Handle exception - Logger.log('Failed with error %s', e.message); + console.log('Failed with error %s', e.message); } } // [END docs_create_document] @@ -61,12 +61,12 @@ function findAndReplace(documentId, findTextToReplacementMap) { const replies = response.replies; for (const [index] of replies.entries()) { const numReplacements = replies[index].replaceAllText.occurrencesChanged || 0; - Logger.log('Request %s performed %s replacements.', index, numReplacements); + console.log('Request %s performed %s replacements.', index, numReplacements); } return replies; } catch (e) { // TODO (developer) - Handle exception - Logger.log('Failed with error : %s', e.message); + console.log('Failed with error : %s', e.message); } } // [END docs_find_and_replace_text] @@ -95,7 +95,7 @@ function insertAndStyleText(documentId, text) { startIndex: 1, endIndex: text.length + 1 }, - text_style: { + textStyle: { fontSize: { magnitude: 12, unit: 'PT' @@ -112,7 +112,7 @@ function insertAndStyleText(documentId, text) { return response.replies; } catch (e) { // TODO (developer) - Handle exception - Logger.log('Failed with an error %s', e.message); + console.log('Failed with an error %s', e.message); } } // [END docs_insert_and_style_text] @@ -142,13 +142,13 @@ function readFirstParagraph(documentId) { paragraphText += paragraphElement.textRun.content; } } - Logger.log(paragraphText); + console.log(paragraphText); return paragraphText; } } } catch (e) { // TODO (developer) - Handle exception - Logger.log('Failed with error %s', e.message); + console.log('Failed with error %s', e.message); } } // [END docs_read_first_paragraph] diff --git a/advanced/doubleclick.gs b/advanced/doubleclick.gs index 0d63ff090..1d556465b 100644 --- a/advanced/doubleclick.gs +++ b/advanced/doubleclick.gs @@ -26,13 +26,13 @@ function listUserProfiles() { // Print out the user ID and name of each for (let i = 0; i < profiles.items.length; i++) { const profile = profiles.items[i]; - Logger.log('Found profile with ID %s and name "%s".', + console.log('Found profile with ID %s and name "%s".', profile.profileId, profile.userName); } } } 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_doubleclick_list_user_profiles] @@ -57,7 +57,7 @@ function listActiveCampaigns() { if (result.campaigns) { for (let i = 0; i < result.campaigns.length; i++) { const campaign = result.campaigns[i]; - Logger.log('Found campaign with ID %s and name "%s".', + console.log('Found campaign with ID %s and name "%s".', campaign.id, campaign.name); } } @@ -65,7 +65,7 @@ function listActiveCampaigns() { } while (pageToken); } 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_doubleclick_list_active_campaigns] @@ -111,7 +111,7 @@ function createAdvertiserAndCampaign() { DoubleClickCampaigns.Campaigns.insert(campaign, profileId); } 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_doubleclick_create_advertiser_and_campaign] diff --git a/advanced/drive.gs b/advanced/drive.gs index 21b669c7c..a0ff1ab18 100644 --- a/advanced/drive.gs +++ b/advanced/drive.gs @@ -23,15 +23,15 @@ function uploadFile() { // Makes a request to fetch a URL. const image = UrlFetchApp.fetch('http://goo.gl/nd7zjB').getBlob(); let file = { - title: 'google_logo.png', + name: 'google_logo.png', mimeType: 'image/png' }; - // Insert new files to user's Drive - file = Drive.Files.insert(file, image); - Logger.log('ID: %s, File size (bytes): %s', file.id, file.fileSize); + // Create a file in the user's Drive. + file = Drive.Files.create(file, image, {'fields': 'id,size'}); + console.log('ID: %s, File size (bytes): %s', file.id, file.size); } catch (err) { // TODO (developer) - Handle exception - Logger.log('Failed to upload file with error %s', err.message); + console.log('Failed to upload file with error %s', err.message); } } // [END drive_upload_file] @@ -49,21 +49,21 @@ function listRootFolders() { try { folders = Drive.Files.list({ q: query, - maxResults: 100, + pageSize: 100, pageToken: pageToken }); - if (!folders.items || folders.items.length === 0) { - Logger.log('No folders found.'); + if (!folders.files || folders.files.length === 0) { + console.log('All folders found.'); return; } - for (let i = 0; i < folders.items.length; i++) { - const folder = folders.items[i]; - Logger.log('%s (ID: %s)', folder.title, folder.id); + for (let i = 0; i < folders.files.length; i++) { + const folder = folders.files[i]; + console.log('%s (ID: %s)', folder.name, folder.id); } pageToken = folders.nextPageToken; } catch (err) { // TODO (developer) - Handle exception - Logger.log('Failed with error %s', err.message); + console.log('Failed with error %s', err.message); } } while (pageToken); } @@ -71,51 +71,60 @@ function listRootFolders() { // [START drive_add_custom_property] /** - * Adds a custom property to a file. Unlike Apps Script's DocumentProperties, + * Adds a custom app property to a file. Unlike Apps Script's DocumentProperties, * Drive's custom file properties can be accessed outside of Apps Script and - * by other applications (if the visibility is set to PUBLIC). - * @param {string} fileId The ID of the file to add the property to. + * by other applications; however, appProperties are only visible to the script. + * @param {string} fileId The ID of the file to add the app property to. */ -function addCustomProperty(fileId) { +function addAppProperty(fileId) { try { - const property = { - key: 'department', - value: 'Sales', - visibility: 'PUBLIC' + let file = { + 'appProperties': { + 'department': 'Sales' + } }; - // Adds a property to a file - Drive.Properties.insert(property, fileId); + // Updates a file to add an app property. + file = Drive.Files.update(file, fileId, null, {'fields': 'id,appProperties'}); + console.log( + 'ID: %s, appProperties: %s', + file.id, + JSON.stringify(file.appProperties, null, 2)); } catch (err) { // TODO (developer) - Handle exception - Logger.log('Failed with error %s', err.message); + console.log('Failed with error %s', err.message); } } // [END drive_add_custom_property] // [START drive_list_revisions] /** - * Lists the revisions of a given file. Note that some properties of revisions - * are only available for certain file types. For example, G Suite application - * files do not consume space in Google Drive and thus list a file size of 0. + * Lists the revisions of a given file. * @param {string} fileId The ID of the file to list revisions for. */ function listRevisions(fileId) { - try { - const revisions = Drive.Revisions.list(fileId); - if (!revisions.items || revisions.items.length === 0) { - Logger.log('No revisions found.'); - return; - } - for (let i = 0; i < revisions.items.length; i++) { - const revision = revisions.items[i]; - const date = new Date(revision.modifiedDate); - Logger.log('Date: %s, File size (bytes): %s', date.toLocaleString(), - revision.fileSize); + let revisions; + const pageToken = null; + do { + try { + revisions = Drive.Revisions.list( + fileId, + {'fields': 'revisions(modifiedTime,size),nextPageToken'}); + if (!revisions.revisions || revisions.revisions.length === 0) { + console.log('All revisions found.'); + return; + } + for (let i = 0; i < revisions.revisions.length; i++) { + const revision = revisions.revisions[i]; + const date = new Date(revision.modifiedTime); + console.log('Date: %s, File size (bytes): %s', date.toLocaleString(), + revision.size); + } + pageToken = revisions.nextPageToken; + } catch (err) { + // TODO (developer) - Handle exception + console.log('Failed with error %s', err.message); } - } catch (err) { - // TODO (developer) - Handle exception - Logger.log('Failed with error %s', err.message); - } + } while (pageToken); } // [END drive_list_revisions] diff --git a/advanced/driveActivity.gs b/advanced/driveActivity.gs index 3719bc05c..3d5f8bd0f 100644 --- a/advanced/driveActivity.gs +++ b/advanced/driveActivity.gs @@ -39,6 +39,6 @@ function getUsersActivity() { } pageToken = result.nextPageToken; } while (pageToken); - Logger.log(Object.keys(users)); + console.log(Object.keys(users)); } // [END apps_script_drive_activity_get_users_activity] diff --git a/advanced/driveLabels.gs b/advanced/driveLabels.gs new file mode 100644 index 000000000..1e4ffa447 --- /dev/null +++ b/advanced/driveLabels.gs @@ -0,0 +1,124 @@ +/** + * 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_drive_labels_list_labels] +/** + * List labels available to the user. + */ +function listLabels() { + let pageToken = null; + let labels = []; + do { + try { + const response = DriveLabels.Labels.list({ + publishedOnly: true, + pageToken: pageToken + }); + pageToken = response.nextPageToken; + labels = labels.concat(response.labels); + } catch (err) { + // TODO (developer) - Handle exception + console.log('Failed to list labels with error %s', err.message); + } + } while (pageToken != null); + + console.log('Found %d labels', labels.length); +} +// [END apps_script_drive_labels_list_labels] + +// [START apps_script_drive_labels_get_label] +/** + * Get a label by name. + * @param {string} labelName The label name. + */ +function getLabel(labelName) { + try { + const label = DriveLabels.Labels.get(labelName, {view: 'LABEL_VIEW_FULL'}); + const title = label.properties.title; + const fieldsLength = label.fields.length; + console.log(`Fetched label with title: '${title}' and ${fieldsLength} fields.`); + } catch (err) { + // TODO (developer) - Handle exception + console.log('Failed to get label with error %s', err.message); + } +} +// [END apps_script_drive_labels_get_label] + +// [START apps_script_drive_labels_list_labels_on_drive_item] +/** + * List Labels on a Drive Item + * Fetches a Drive Item and prints all applied values along with their to their + * human-readable names. + * + * @param {string} fileId The Drive File ID + */ +function listLabelsOnDriveItem(fileId) { + try { + const appliedLabels = Drive.Files.listLabels(fileId); + + console.log('%d label(s) are applied to this file', appliedLabels.items.length); + + appliedLabels.items.forEach((appliedLabel) => { + // Resource name of the label at the applied revision. + const labelName = 'labels/' + appliedLabel.id + '@' + appliedLabel.revisionId; + + console.log('Fetching Label: %s', labelName); + const label = DriveLabels.Labels.get(labelName, {view: 'LABEL_VIEW_FULL'}); + + console.log('Label Title: %s', label.properties.title); + + Object.keys(appliedLabel.fields).forEach((fieldId) => { + const fieldValue = appliedLabel.fields[fieldId]; + const field = label.fields.find((f) => f.id == fieldId); + + console.log(`Field ID: ${field.id}, Display Name: ${field.properties.displayName}`); + switch (fieldValue.valueType) { + case 'text': + console.log('Text: %s', fieldValue.text[0]); + break; + case 'integer': + console.log('Integer: %d', fieldValue.integer[0]); + break; + case 'dateString': + console.log('Date: %s', fieldValue.dateString[0]); + break; + case 'user': + const user = fieldValue.user.map((user) => { + return `${user.emailAddress}: ${user.displayName}`; + }).join(', '); + console.log(`User: ${user}`); + break; + case 'selection': + const choices = fieldValue.selection.map((choiceId) => { + return field.selectionOptions.choices.find((choice) => choice.id === choiceId); + }); + const selection = choices.map((choice) => { + return `${choice.id}: ${choice.properties.displayName}`; + }).join(', '); + console.log(`Selection: ${selection}`); + break; + default: + console.log('Unknown: %s', fieldValue.valueType); + console.log(fieldValue.value); + } + }); + }); + } catch (err) { + // TODO (developer) - Handle exception + console.log('Failed with error %s', err.message); + } +} +// [END apps_script_drive_labels_list_labels_on_drive_item] diff --git a/advanced/fusionTables.gs b/advanced/fusionTables.gs deleted file mode 100644 index 87d45f054..000000000 --- a/advanced/fusionTables.gs +++ /dev/null @@ -1,62 +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_fusion_tables_list] -/** - * This sample lists Fusion Tables that the user has access to. - */ -function listTables() { - var tables = FusionTables.Table.list(); - if (tables.items) { - for (var i = 0; i < tables.items.length; i++) { - var table = tables.items[i]; - Logger.log('Table with name "%s" and ID "%s" was found.', - table.name, table.tableId); - } - } else { - Logger.log('No tables found.'); - } -} -// [END apps_script_fusion_tables_list] - -// [START apps_script_fusion_tables_run_query] -/** - * This sample queries for the first 100 rows in the given Fusion Table and - * saves the results to a new spreadsheet. - * @param {string} tableId The table ID. - */ -function runQuery(tableId) { - var sql = 'SELECT * FROM ' + tableId + ' LIMIT 100'; - var result = FusionTables.Query.sqlGet(sql, { - hdrs: false - }); - if (result.rows) { - var spreadsheet = SpreadsheetApp.create('Fusion Table Query Results'); - var sheet = spreadsheet.getActiveSheet(); - - // Append the headers. - sheet.appendRow(result.columns); - - // Append the results. - sheet.getRange(2, 1, result.rows.length, result.columns.length) - .setValues(result.rows); - - Logger.log('Query results spreadsheet created: %s', - spreadsheet.getUrl()); - } else { - Logger.log('No rows returned.'); - } -} -// [END apps_script_fusion_tables_run_query] diff --git a/advanced/gmail.gs b/advanced/gmail.gs index 1333a3c74..a1195c6b7 100644 --- a/advanced/gmail.gs +++ b/advanced/gmail.gs @@ -24,10 +24,10 @@ function listLabelInfo() { Gmail.Users.Labels.list('me'); for (let i = 0; i < response.labels.length; i++) { const label = response.labels[i]; - Logger.log(JSON.stringify(label)); + console.log(JSON.stringify(label)); } } catch (err) { - Logger.log(err); + console.log(err); } } // [END gmail_label] @@ -47,13 +47,13 @@ function listInboxSnippets() { }); if (threadList.threads && threadList.threads.length > 0) { threadList.threads.forEach(function(thread) { - Logger.log('Snippet: %s', thread.snippet); + console.log('Snippet: %s', thread.snippet); }); } pageToken = threadList.nextPageToken; } while (pageToken); } catch (err) { - Logger.log(err); + console.log(err); } } // [END gmail_inbox_snippets] @@ -74,7 +74,7 @@ function logRecentHistory() { maxResults: 1 }); if (!sent.threads || !sent.threads[0]) { - Logger.log('No sent threads found.'); + console.log('No sent threads found.'); return; } const historyId = sent.threads[0].historyId; @@ -102,10 +102,10 @@ function logRecentHistory() { } while (pageToken); changed.forEach(function(id) { - Logger.log('Message Changed: %s', id); + console.log('Message Changed: %s', id); }); } catch (err) { - Logger.log(err); + console.log(err); } } // [END gmail_history] @@ -126,7 +126,7 @@ function getRawMessage() { const encodedMessage = Utilities.base64Encode(message.raw); console.log(encodedMessage); } catch (err) { - Logger.log(err); + console.log(err); } } // [END gmail_raw] diff --git a/advanced/googlePlus.gs b/advanced/googlePlus.gs deleted file mode 100644 index fbf2cc7e3..000000000 --- a/advanced/googlePlus.gs +++ /dev/null @@ -1,76 +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_plus_people] -/** - * The following example demonstrates how to retrieve a list of the people - * in the user's Google+ circles. - */ -function getPeople() { - var userId = 'me'; - var people; - var pageToken; - do { - people = Plus.People.list(userId, 'visible', { - pageToken: pageToken - }); - if (people.items) { - for (var i = 0; i < people.items.length; i++) { - var person = people.items[i]; - Logger.log(person.displayName); - } - } else { - Logger.log('No people in your visible circles.'); - } - pageToken = people.nextPageToken; - } while (pageToken); -} -// [END apps_script_plus_people] - -// [START apps_script_plus_posts] -/** - * The following example demonstrates how to list a user's posts. The returned - * results contain a brief summary of the posts, including a list of comments - * made on the post. - */ -function getPosts() { - var userId = 'me'; - var posts; - var pageToken; - do { - posts = Plus.Activities.list(userId, 'public', { - maxResults: 10, - pageToken: pageToken - }); - if (posts.items) { - for (var i = 0; i < posts.items.length; i++) { - var post = posts.items[i]; - Logger.log(post.title); - var comments = Plus.Comments.list(post.id); - if (comments.items) { - for (var j = 0; j < comments.items.length; j++) { - var comment = comments.items[j]; - Logger.log(comment.actor.displayName + ': ' + - comment.object.content); - } - } - } - } else { - Logger.log('No posts found.'); - } - pageToken = posts.pageToken; - } while (pageToken); -} -// [END apps_script_plus_posts] diff --git a/advanced/googlePlusDomains.gs b/advanced/googlePlusDomains.gs deleted file mode 100644 index 3a0e8364f..000000000 --- a/advanced/googlePlusDomains.gs +++ /dev/null @@ -1,95 +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_plus_domains_profile] -/** - * The following example demonstrates how to retrieve details from a user's - * Google+ profile. - */ -function getProfile() { - var userId = 'me'; - var profile = PlusDomains.People.get(userId); - - Logger.log('ID: %s', profile.id); - Logger.log('Display name: %s', profile.displayName); - Logger.log('Image URL: %s', profile.image.url); - Logger.log('Profile URL: %s', profile.url); -} -// [END apps_script_plus_domains_profile] - -// [START apps_script_plus_domains_circle] -/** - * The following example demonstrates how to create an empty circle for a user - * within your G Suite domain. - */ -function createCircle() { - var userId = 'me'; - var circle = PlusDomains.newCircle(); - circle.displayName = 'Tech support'; - - circle = PlusDomains.Circles.insert(circle, userId); - Logger.log('Created "Tech support" circle with id: ' + circle.id); -} -// [END apps_script_plus_domains_circle] - -// [START apps_script_plus_domains_get_posts] -/** - * The following example demonstrates how to list a user's posts. The returned - * results contain a brief summary of the posts, including a title. Use the - * Activities.get() method to read the full details of a post. - */ -function getPosts() { - var userId = 'me'; - var pageToken; - var posts; - do { - posts = PlusDomains.Activities.list(userId, 'user', { - maxResults: 100, - pageToken: pageToken - }); - if (posts.items) { - for (var i = 0; i < posts.items.length; i++) { - var post = posts.items[i]; - Logger.log('ID: %s, Content: %s', post.id, post.object.content); - } - } - pageToken = posts.nextPageToken; - } while (pageToken); -} -// [END apps_script_plus_domains_get_posts] - -// [START apps_script_plus_domains_create_post] -/** - * The following example demonstrates how to create a post that is available - * to all users within your G Suite domain. - */ -function createPost() { - var userId = 'me'; - var post = { - object: { - originalContent: 'Happy Monday! #caseofthemondays' - }, - access: { - items: [{ - type: 'domain' - }], - domainRestricted: true - } - }; - - post = PlusDomains.Activities.insert(post, userId); - Logger.log('Post created with URL: %s', post.url); -} -// [END apps_script_plus_domains_create_post] diff --git a/advanced/iot.gs b/advanced/iot.gs index 3f03b87f3..8087fd023 100644 --- a/advanced/iot.gs +++ b/advanced/iot.gs @@ -18,7 +18,7 @@ * Lists the registries for the configured project and region. */ function listRegistries() { - Logger.log(response); + console.log(response); var projectId = 'your-project-id'; var cloudRegion = 'us-central1'; var parent = 'projects/' + projectId + '/locations/' + cloudRegion; @@ -27,7 +27,7 @@ function listRegistries() { if (response.deviceRegistries) { response.deviceRegistries.forEach( function(registry) { - Logger.log(registry.id); + console.log(registry.id); }); } } @@ -55,7 +55,7 @@ function createRegistry() { var parent = 'projects/' + projectId + '/locations/' + cloudRegion; var response = CloudIoT.Projects.Locations.Registries.create(registry, parent); - Logger.log('Created registry: ' + response.id); + console.log('Created registry: ' + response.id); } // [END apps_script_iot_create_registry] @@ -72,7 +72,7 @@ function getRegistry() { var registryName = parent + '/registries/' + name; var response = CloudIoT.Projects.Locations.Registries.get(registryName); - Logger.log('Retrieved registry: ' + response.id); + console.log('Retrieved registry: ' + response.id); } // [END apps_script_iot_get_registry] @@ -90,7 +90,7 @@ function deleteRegistry() { var response = CloudIoT.Projects.Locations.Registries.remove(registryName); // Successfully removed registry if exception was not thrown. - Logger.log('Deleted registry: ' + name); + console.log('Deleted registry: ' + name); } // [END apps_script_iot_delete_registry] @@ -108,11 +108,11 @@ function listDevicesForRegistry() { var response = CloudIoT.Projects.Locations.Registries.Devices.list(registryName); - Logger.log('Registry contains the following devices: '); + console.log('Registry contains the following devices: '); if (response.devices) { response.devices.forEach( function(device) { - Logger.log('\t' + device.id); + console.log('\t' + device.id); }); } } @@ -128,7 +128,7 @@ function createDevice() { var projectId = 'your-project-id'; var registry = 'your-registry-name'; - Logger.log('Creating device: ' + name + ' in Registry: ' + registry); + console.log('Creating device: ' + name + ' in Registry: ' + registry); var parent = 'projects/' + projectId + '/locations/' + cloudRegion + '/registries/' + registry; var device = { @@ -140,7 +140,7 @@ function createDevice() { }; var response = CloudIoT.Projects.Locations.Registries.Devices.create(device, parent); - Logger.log('Created device:' + response.name); + console.log('Created device:' + response.name); } // [END apps_script_iot_create_unauth_device] @@ -182,7 +182,7 @@ function createRsaDevice() { }; var response = CloudIoT.Projects.Locations.Registries.Devices.create(device, parent); - Logger.log('Created device:' + response.name); + console.log('Created device:' + response.name); } // [END apps_script_iot_create_rsa_device] @@ -201,7 +201,7 @@ function deleteDevice() { var response = CloudIoT.Projects.Locations.Registries.Devices.remove(deviceName); // If no exception thrown, device was successfully removed - Logger.log('Successfully deleted device: ' + deviceName); + console.log('Successfully deleted device: ' + deviceName); } // [END apps_script_iot_delete_device] diff --git a/advanced/mirror.gs b/advanced/mirror.gs deleted file mode 100644 index f0db2df5f..000000000 --- a/advanced/mirror.gs +++ /dev/null @@ -1,83 +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_mirror_timeline] -/** - * This sample inserts a new item into the timeline. - */ -function insertTimelineItem() { - const timelineItem = Mirror.newTimelineItem(); - timelineItem.text = 'Hello world!'; - - const notificationConfig = Mirror.newNotificationConfig(); - notificationConfig.level = 'AUDIO_ONLY'; - - const menuItem = Mirror.newMenuItem(); - menuItem.action = 'REPLY'; - - timelineItem.notification = notificationConfig; - timelineItem.menuItems = [menuItem]; - try { - // @see https://developers.google.com/glass/v1/reference/timeline/insert - Mirror.Timeline.insert(timelineItem); - Logger.log('Successfully inserted new item to Timeline '); - } catch (err) { - // TODO (developer)- Handle exception from the API - Logger.log('Failed with error %s', err.message); - } -} -// [END apps_script_mirror_timeline] - -// [START apps_script_mirror_contact] -/** - * This sample inserts a new contact. - * @see https://developers.google.com/glass/v1/reference/contacts/insert - */ -function insertContact() { - const contact = { - id: 'harold', - displayName: 'Harold Penguin', - imageUrls: ['https://developers.google.com/glass/images/harold.jpg'] - }; - try { - Mirror.Contacts.insert(contact); - Logger.log('Successfully inserted contact '); - } catch (err) { - // TODO (developer)- Handle exception from the API - Logger.log('Failed with error %s', err.message); - } -} -// [END apps_script_mirror_contact] - -// [START apps_script_mirror_location] -/** - * This sample prints the most recent known location of the user's Glass to the - * script editor's log. - * @see https://developers.google.com/glass/v1/reference/locations/get - */ -function printLatestLocation() { - try { - const location = Mirror.Locations.get('latest'); - - Logger.log('Location recorded on: ' + location.timestamp); - Logger.log(' > Latitude: ' + location.latitude); - Logger.log(' > Longitude: ' + location.longitude); - Logger.log(' > Accuracy: ' + location.accuracy + ' meters'); - } catch (err) { - // TODO (developer)- Handle exception from the API - Logger.log('Failed with error %s', err.message); - } -} -// [END apps_script_mirror_location] diff --git a/advanced/people.gs b/advanced/people.gs index aa8d996c1..10cf68d09 100644 --- a/advanced/people.gs +++ b/advanced/people.gs @@ -25,10 +25,10 @@ function getConnections() { personFields: 'names,emailAddresses' }); // Print the connections/contacts - Logger.log('Connections: %s', JSON.stringify(people, null, 2)); + console.log('Connections: %s', JSON.stringify(people, null, 2)); } catch (err) { // TODO (developers) - Handle exception here - Logger.log('Failed to get the connection with an error %s', err.message); + console.log('Failed to get the connection with an error %s', err.message); } } // [END people_get_connections] @@ -46,10 +46,10 @@ function getSelf() { personFields: 'names,emailAddresses' // Use other query parameter here if needed }); - Logger.log('Myself: %s', JSON.stringify(people, null, 2)); + console.log('Myself: %s', JSON.stringify(people, null, 2)); } catch (err) { // TODO (developer) -Handle exception - Logger.log('Failed to get own profile with an error %s', err.message); + console.log('Failed to get own profile with an error %s', err.message); } } // [END people_get_self_profile] @@ -67,10 +67,123 @@ function getAccount(accountId) { personFields: 'names,emailAddresses' }); // Print the profile details of Account. - Logger.log('Public Profile: %s', JSON.stringify(people, null, 2)); + console.log('Public Profile: %s', JSON.stringify(people, null, 2)); } catch (err) { // TODO (developer) - Handle exception - Logger.log('Failed to get account with an error %s', err.message); + console.log('Failed to get account with an error %s', err.message); } } // [END people_get_account] + +// [START people_get_group] + +/** + * Gets a contact group with the given name + * @param {string} name The group name. + * @see https://developers.google.com/people/api/rest/v1/contactGroups/list + */ +function getContactGroup(name) { + try { + const people = People.ContactGroups.list(); + // Finds the contact group for the person where the name matches. + const group = people['contactGroups'].find((group) => group['name'] === name); + // Prints the contact group + console.log('Group: %s', JSON.stringify(group, null, 2)); + } catch (err) { + // TODO (developers) - Handle exception + console.log('Failed to get the contact group with an error %s', err.message); + } +} + +// [END people_get_group] + +// [START people_get_contact_by_email] + +/** + * Gets a contact by the email address. + * @param {string} email The email address. + * @see https://developers.google.com/people/api/rest/v1/people.connections/list + */ +function getContactByEmail(email) { + try { + // Gets the person with that email address by iterating over all contacts. + const people = People.People.Connections.list('people/me', { + personFields: 'names,emailAddresses' + }); + const contact = people['connections'].find((connection) => { + return connection['emailAddresses'].some((emailAddress) => emailAddress['value'] === email); + }); + // Prints the contact. + console.log('Contact: %s', JSON.stringify(contact, null, 2)); + } catch (err) { + // TODO (developers) - Handle exception + console.log('Failed to get the connection with an error %s', err.message); + } +} + +// [END people_get_contact_by_email] + +// [START people_get_full_name] +/** + * Gets the full name (given name and last name) of the contact as a string. + * @see https://developers.google.com/people/api/rest/v1/people/get + */ +function getFullName() { + try { + // Gets the person by specifying resource name/account ID + // in the first parameter of People.People.get. + // This example gets the person for the user running the script. + const people = People.People.get('people/me', {personFields: 'names'}); + // Prints the full name (given name + family name) + console.log(`${people['names'][0]['givenName']} ${people['names'][0]['familyName']}`); + } catch (err) { + // TODO (developers) - Handle exception + console.log('Failed to get the connection with an error %s', err.message); + } +} + +// [END people_get_full_name] + +// [START people_get_phone_numbers] +/** + * Gets all the phone numbers for this contact. + * @see https://developers.google.com/people/api/rest/v1/people/get + */ +function getPhoneNumbers() { + try { + // Gets the person by specifying resource name/account ID + // in the first parameter of People.People.get. + // This example gets the person for the user running the script. + const people = People.People.get('people/me', {personFields: 'phoneNumbers'}); + // Prints the phone numbers. + console.log(people['phoneNumbers']); + } catch (err) { + // TODO (developers) - Handle exception + console.log('Failed to get the connection with an error %s', err.message); + } +} + +// [END people_get_phone_numbers] + +// [START people_get_single_phone_number] +/** + * Gets a phone number by type, such as work or home. + * @see https://developers.google.com/people/api/rest/v1/people/get + */ +function getPhone() { + try { + // Gets the person by specifying resource name/account ID + // in the first parameter of People.People.get. + // This example gets the person for the user running the script. + const people = People.People.get('people/me', {personFields: 'phoneNumbers'}); + // Gets phone number by type, such as home or work. + const phoneNumber = people['phoneNumbers'].find((phone) => phone['type'] === 'home')['value']; + // Prints the phone numbers. + console.log(phoneNumber); + } catch (err) { + // TODO (developers) - Handle exception + console.log('Failed to get the connection with an error %s', err.message); + } +} + +// [END people_get_single_phone_number] diff --git a/advanced/prediction.gs b/advanced/prediction.gs deleted file mode 100644 index 88ba2817d..000000000 --- a/advanced/prediction.gs +++ /dev/null @@ -1,117 +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_prediction_query_hosted_model] -/** - * Runs sentiment analysis across a sentence. - * Prints the sentiment label. - */ -function queryHostedModel() { - // When querying hosted models you must always use this - // specific project number. - var projectNumber = '414649711441'; - var hostedModelName = 'sample.sentiment'; - - // Query the hosted model with a positive statement. - var predictionString = 'Want to go to the park this weekend?'; - var prediction = Prediction.Hostedmodels.predict( - { - input: { - csvInstance: [predictionString] - } - }, - projectNumber, - hostedModelName); - // Logs Sentiment: positive. - Logger.log('Sentiment: ' + prediction.outputLabel); - - // Now query the hosted model with a negative statement. - predictionString = 'You are not very nice!'; - prediction = Prediction.Hostedmodels.predict( - { - input: { - csvInstance: [predictionString] - } - }, - projectNumber, - hostedModelName); - // Logs Sentiment: negative. - Logger.log('Sentiment: ' + prediction.outputLabel); -} -// [END apps_script_prediction_query_hosted_model] - -// [START apps_script_prediction_create_new_model] -/** - * Creates a new prediction model. - */ -function createNewModel() { - // Replace this value with the project number listed in the Google - // APIs Console project. - var projectNumber = 'XXXXXXXX'; - var id = 'mylanguageidmodel'; - var storageDataLocation = 'languageidsample/language_id.txt'; - - // Returns immediately. Training happens asynchronously. - var result = Prediction.Trainedmodels.insert( - { - id: id, - storageDataLocation: storageDataLocation - }, - projectNumber); - Logger.log(result); -} -// [END apps_script_prediction_create_new_model] - -// [START apps_script_prediction_query_training_status] -/** - * Gets the training status from a prediction model. - * Logs the status. - */ -function queryTrainingStatus() { - // Replace this value with the project number listed in the Google - // APIs Console project. - var projectNumber = 'XXXXXXXX'; - var id = 'mylanguageidmodel'; - - var result = Prediction.Trainedmodels.get(projectNumber, id); - Logger.log(result.trainingStatus); -} -// [END apps_script_prediction_query_training_status] - -// [START apps_script_prediction_query_trailed_model] -/** - * Gets the language from a trained language model. - * Logs the language of the sentence. - */ -function queryTrainedModel() { - // Replace this value with the project number listed in the Google - // APIs Console project. - var projectNumber = 'XXXXXXXX'; - var id = 'mylanguageidmodel'; - var query = 'Este es un mensaje de prueba de ejemplo'; - - var prediction = Prediction.Trainedmodels.predict( - { - input: - { - csvInstance: [query] - } - }, - projectNumber, - id); - // Logs Language: Spanish. - Logger.log('Language: ' + prediction.outputLabel); -} -// [END apps_script_prediction_query_trailed_model] diff --git a/advanced/sheets.gs b/advanced/sheets.gs index 89804422c..cac5df416 100644 --- a/advanced/sheets.gs +++ b/advanced/sheets.gs @@ -27,13 +27,13 @@ function readRange(spreadsheetId = yourspreadsheetId) { try { const response = Sheets.Spreadsheets.Values.get(spreadsheetId, 'Sheet1!A1:D5'); if (response.values) { - Logger.log(response.values); + console.log(response.values); return; } - Logger.log('Failed to get range of values from spreadsheet'); + console.log('Failed to get range of values from spreadsheet'); } catch (e) { // TODO (developer) - Handle exception - Logger.log('Failed with error %s', e.message); + console.log('Failed with error %s', e.message); } } // [END sheets_read_range] @@ -72,13 +72,13 @@ function writeToMultipleRanges(spreadsheetId = yourspreadsheetId) { try { const response = Sheets.Spreadsheets.Values.batchUpdate(request, spreadsheetId); if (response) { - Logger.log(response); + console.log(response); return; } - Logger.log('response null'); + console.log('response null'); } catch (e) { // TODO (developer) - Handle exception - Logger.log('Failed with error %s', e.message); + console.log('Failed with error %s', e.message); } } // [END sheets_write_range] @@ -109,11 +109,11 @@ function addSheet(spreadsheetId = yourspreadsheetId) { try { const response = Sheets.Spreadsheets.batchUpdate({'requests': requests}, spreadsheetId); - Logger.log('Created sheet with ID: ' + + console.log('Created sheet with ID: ' + response.replies[0].addSheet.properties.sheetId); } catch (e) { // TODO (developer) - Handle exception - Logger.log('Failed with error %s', e.message); + console.log('Failed with error %s', e.message); } } // [END sheets_add_new_sheet] @@ -195,7 +195,7 @@ function addPivotTable( // The Pivot table will appear anchored to cell A50 of the destination sheet. } catch (e) { // TODO (developer) - Handle exception - Logger.log('Failed with error %s', e.message); + console.log('Failed with error %s', e.message); } } // [END sheets_add_pivot_table] diff --git a/advanced/shoppingContent.gs b/advanced/shoppingContent.gs index 69f1ad0d4..22cc7e2c8 100644 --- a/advanced/shoppingContent.gs +++ b/advanced/shoppingContent.gs @@ -18,9 +18,9 @@ * Inserts a product into the products list. Logs the API response. */ function productInsert() { - var merchantId = 123456; // Replace this with your Merchant Center ID. + const merchantId = 123456; // Replace this with your Merchant Center ID. // Create a product resource and insert it - var productResource = { + const productResource = { 'offerId': 'book123', 'title': 'A Tale of Two Cities', 'description': 'A classic novel about the French Revolution', @@ -52,8 +52,14 @@ function productInsert() { } }; - response = ShoppingContent.Products.insert(productResource, merchantId); - Logger.log(response); // RESTful insert returns the JSON object as a response. + try { + response = ShoppingContent.Products.insert(productResource, merchantId); + // RESTful insert returns the JSON object as a response. + console.log(response); + } catch (e) { + // TODO (Developer) - Handle exceptions + console.log('Failed with error: $s', e.error); + } } // [END apps_script_shopping_product_insert] @@ -62,26 +68,31 @@ function productInsert() { * Lists the products for a given merchant. */ function productList() { - var merchantId = 123456; // Replace this with your Merchant Center ID. - var pageToken; - var pageNum = 1; - var maxResults = 10; - do { - var products = ShoppingContent.Products.list(merchantId, { - pageToken: pageToken, - maxResults: maxResults - }); - Logger.log('Page ' + pageNum); - if (products.resources) { - for (var i = 0; i < products.resources.length; i++) { - Logger.log('Item [' + i + '] ==> ' + products.resources[i]); + const merchantId = 123456; // Replace this with your Merchant Center ID. + let pageToken; + let pageNum = 1; + const maxResults = 10; + try { + do { + const products = ShoppingContent.Products.list(merchantId, { + pageToken: pageToken, + maxResults: maxResults + }); + console.log('Page ' + pageNum); + if (products.resources) { + for (let i = 0; i < products.resources.length; i++) { + console.log('Item [' + i + '] ==> ' + products.resources[i]); + } + } else { + console.log('No more products in account ' + merchantId); } - } else { - Logger.log('No more products in account ' + merchantId); - } - pageToken = products.nextPageToken; - pageNum++; - } while (pageToken); + pageToken = products.nextPageToken; + pageNum++; + } while (pageToken); + } catch (e) { + // TODO (Developer) - Handle exceptions + console.log('Failed with error: $s', e.error); + } } // [END apps_script_shopping_product_list] @@ -93,7 +104,7 @@ function productList() { * @param {object} productResource3 The third product resource. */ function custombatch(productResource1, productResource2, productResource3) { - var merchantId = 123456; // Replace this with your Merchant Center ID. + const merchantId = 123456; // Replace this with your Merchant Center ID. custombatchResource = { 'entries': [ { @@ -119,8 +130,13 @@ function custombatch(productResource1, productResource2, productResource3) { } ] }; - var response = ShoppingContent.Products.custombatch(custombatchResource); - Logger.log(response); + try { + const response = ShoppingContent.Products.custombatch(custombatchResource); + console.log(response); + } catch (e) { + // TODO (Developer) - Handle exceptions + console.log('Failed with error: $s', e.error); + } } // [END apps_script_shopping_product_batch_insert] @@ -131,37 +147,43 @@ function custombatch(productResource1, productResource2, productResource3) { */ function updateAccountTax() { // Replace this with your Merchant Center ID. - var merchantId = 123456; + const merchantId = 123456; // Replace this with the account that you are updating taxes for. - var accountId = 123456; + const accountId = 123456; - var accounttax = ShoppingContent.Accounttax.get(merchantId, accountId); - Logger.log(accounttax); + try { + const accounttax = ShoppingContent.Accounttax.get(merchantId, accountId); + console.log(accounttax); - var taxInfo = { - accountId: accountId, - rules: [ - { - 'useGlobalRate': true, - 'locationId': 21135, - 'shippingTaxed': true, - 'country': 'US' - }, - { - 'ratePercent': 3, - 'locationId': 21136, - 'country': 'US' - }, - { - 'ratePercent': 2, - 'locationId': 21160, - 'shippingTaxed': true, - 'country': 'US' - } - ] - }; + const taxInfo = { + accountId: accountId, + rules: [ + { + 'useGlobalRate': true, + 'locationId': 21135, + 'shippingTaxed': true, + 'country': 'US' + }, + { + 'ratePercent': 3, + 'locationId': 21136, + 'country': 'US' + }, + { + 'ratePercent': 2, + 'locationId': 21160, + 'shippingTaxed': true, + 'country': 'US' + } + ] + }; - Logger.log(ShoppingContent.Accounttax.update(taxInfo, merchantId, accountId)); + console.log(ShoppingContent.Accounttax + .update(taxInfo, merchantId, accountId)); + } catch (e) { + // TODO (Developer) - Handle exceptions + console.log('Failed with error: $s', e.error); + } } // [END apps_script_shopping_account_info] diff --git a/advanced/slides.gs b/advanced/slides.gs index 9219b0669..d8532df0b 100644 --- a/advanced/slides.gs +++ b/advanced/slides.gs @@ -14,7 +14,7 @@ * limitations under the License. */ -// [START slides_create_presentation] +// [START apps_script_slides_create_presentation] /** * Create a new presentation. * @return {string} presentation Id. @@ -24,16 +24,16 @@ function createPresentation() { try { const presentation = Slides.Presentations.create({'title': 'MyNewPresentation'}); - Logger.log('Created presentation with ID: ' + presentation.presentationId); + console.log('Created presentation with ID: ' + presentation.presentationId); return presentation.presentationId; } catch (e) { // TODO (developer) - Handle exception - Logger.log('Failed with error %s', e.message); + console.log('Failed with error %s', e.message); } } -// [END slides_create_presentation] +// [END apps_script_slides_create_presentation] -// [START slides_create_slide] +// [START apps_script_slides_create_slide] /** * Create a new slide. * @param {string} presentationId The presentation to add the slide to. @@ -56,16 +56,16 @@ function createSlide(presentationId) { try { const slide = Slides.Presentations.batchUpdate({'requests': requests}, presentationId); - Logger.log('Created Slide with ID: ' + slide.replies[0].createSlide.objectId); + console.log('Created Slide with ID: ' + slide.replies[0].createSlide.objectId); return slide; } catch (e) { // TODO (developer) - Handle Exception - Logger.log('Failed with error %s', e.message); + console.log('Failed with error %s', e.message); } } -// [END slides_create_slide] +// [END apps_script_slides_create_slide] -// [START slides_read_page] +// [START apps_script_slides_read_page] /** * Read page element IDs. * @param {string} presentationId The presentation to read from. @@ -79,16 +79,16 @@ function readPageElementIds(presentationId, pageId) { try { const response = Slides.Presentations.Pages.get( presentationId, pageId, {'fields': 'pageElements.objectId'}); - Logger.log(response); + console.log(response); return response; } catch (e) { // TODO (developer) - Handle Exception - Logger.log('Failed with error %s', e.message); + console.log('Failed with error %s', e.message); } } -// [END slides_read_page] +// [END apps_script_slides_read_page] -// [START slides_add_text_box] +// [START apps_script_slides_add_text_box] /** * Add a new text box with text to a page. * @param {string} presentationId The presentation ID. @@ -136,17 +136,17 @@ function addTextBox(presentationId, pageId) { try { const response = Slides.Presentations.batchUpdate({'requests': requests}, presentationId); - Logger.log('Created Textbox with ID: ' + + console.log('Created Textbox with ID: ' + response.replies[0].createShape.objectId); return response; } catch (e) { // TODO (developer) - Handle Exception - Logger.log('Failed with error %s', e.message); + console.log('Failed with error %s', e.message); } } -// [END slides_add_text_box] +// [END apps_script_slides_add_text_box] -// [START slides_format_shape_text] +// [START apps_script_slides_format_shape_text] /** * Format the text in a shape. * @param {string} presentationId The presentation ID. @@ -185,12 +185,12 @@ function formatShapeText(presentationId, shapeId) { return response.replies; } catch (e) { // TODO (developer) - Handle Exception - Logger.log('Failed with error %s', e.message); + console.log('Failed with error %s', e.message); } } -// [END slides_format_shape_text] +// [END apps_script_slides_format_shape_text] -// [START slides_save_thumbnail] +// [START apps_script_slides_save_thumbnail] /** * Saves a thumbnail image of the current Google Slide presentation in Google Drive. * Logs the image URL. @@ -209,10 +209,10 @@ function saveThumbnailImage(i) { const image = response.getBlob(); // Creates a file in the root of the user's Drive from a given Blob of arbitrary data. const file = DriveApp.createFile(image); - Logger.log(file.getUrl()); + console.log(file.getUrl()); } catch (e) { // TODO (developer) - Handle Exception - Logger.log('Failed with error %s', e.message); + console.log('Failed with error %s', e.message); } } -// [END slides_save_thumbnail] +// [END apps_script_slides_save_thumbnail] diff --git a/advanced/tagManager.gs b/advanced/tagManager.gs index 852b97c62..3d15f8d8e 100644 --- a/advanced/tagManager.gs +++ b/advanced/tagManager.gs @@ -15,58 +15,64 @@ */ // [START apps_script_tag_manager_create_version] /** - * Creates a container version for a particular account with the input accountPath. + * Creates a container version for a particular account + * with the input accountPath. * @param {string} accountPath The account path. * @return {string} The tag manager container version. */ function createContainerVersion(accountPath) { - var date = new Date(); + const date = new Date(); // Creates a container in the account, using the current timestamp to make // sure the container is unique. - var container = TagManager.Accounts.Containers.create( - { - 'name': 'appscript tagmanager container ' + date.getTime(), - 'usageContext': ['WEB'] - }, - accountPath); - var containerPath = container.path; - // Creates a workspace in the container to track entity changes. - var workspace = TagManager.Accounts.Containers.Workspaces.create( - {'name': 'appscript workspace', 'description': 'appscript workspace'}, - containerPath); - var workspacePath = workspace.path; - // Creates a random value variable. - var variable = TagManager.Accounts.Containers.Workspaces.Variables.create( - {'name': 'apps script variable', 'type': 'r'}, - workspacePath); - // Creates a trigger that fires on any page view. - var trigger = TagManager.Accounts.Containers.Workspaces.Triggers.create( - {'name': 'apps script trigger', 'type': 'PAGEVIEW'}, - workspacePath); - // Creates a arbitary pixel that fires the tag on all page views. - var tag = TagManager.Accounts.Containers.Workspaces.Tags.create( - { - 'name': 'apps script tag', - 'type': 'img', - 'liveOnly': false, - 'parameter': [ - {'type': 'boolean', 'key': 'useCacheBuster', 'value': 'true'}, { - 'type': 'template', - 'key': 'cacheBusterQueryParam', - 'value': 'gtmcb' - }, - {'type': 'template', 'key': 'url', 'value': '//example.com'} - ], - 'firingTriggerId': [trigger.triggerId] - }, - workspacePath); - // Creates a container version with the variabe, trigger, and tag. - var version = TagManager.Accounts.Containers.Workspaces - .create_version( - {'name': 'apps script version'}, workspacePath) - .containerVersion; - Logger.log(version); - return version; + try { + const container = TagManager.Accounts.Containers.create( + { + 'name': 'appscript tagmanager container ' + date.getTime(), + 'usageContext': ['WEB'] + }, + accountPath); + const containerPath = container.path; + // Creates a workspace in the container to track entity changes. + const workspace = TagManager.Accounts.Containers.Workspaces.create( + {'name': 'appscript workspace', 'description': 'appscript workspace'}, + containerPath); + const workspacePath = workspace.path; + // Creates a random value variable. + const variable = TagManager.Accounts.Containers.Workspaces.Variables.create( + {'name': 'apps script variable', 'type': 'r'}, + workspacePath); + // Creates a trigger that fires on any page view. + const trigger = TagManager.Accounts.Containers.Workspaces.Triggers.create( + {'name': 'apps script trigger', 'type': 'PAGEVIEW'}, + workspacePath); + // Creates a arbitary pixel that fires the tag on all page views. + const tag = TagManager.Accounts.Containers.Workspaces.Tags.create( + { + 'name': 'apps script tag', + 'type': 'img', + 'liveOnly': false, + 'parameter': [ + {'type': 'boolean', 'key': 'useCacheBuster', 'value': 'true'}, { + 'type': 'template', + 'key': 'cacheBusterQueryParam', + 'value': 'gtmcb' + }, + {'type': 'template', 'key': 'url', 'value': '//example.com'} + ], + 'firingTriggerId': [trigger.triggerId] + }, + workspacePath); + // Creates a container version with the variabe, trigger, and tag. + const version = TagManager.Accounts.Containers.Workspaces + .create_version( + {'name': 'apps script version'}, workspacePath) + .containerVersion; + console.log(version); + return version; + } catch (e) { + // TODO (Developer) - Handle exception + console.log('Failed with error: %s', e.error); + } } // [END apps_script_tag_manager_create_version] @@ -77,7 +83,7 @@ function createContainerVersion(accountPath) { * @return {string} The container path. */ function grabContainerPath(versionPath) { - var pathParts = versionPath.split('/'); + const pathParts = versionPath.split('/'); return pathParts.slice(0, 4).join('/'); } @@ -87,17 +93,22 @@ function grabContainerPath(versionPath) { * @param {object} version The container version. */ function publishVersionAndQuickPreviewDraft(version) { - var containerPath = grabContainerPath(version.path); - // Publish the input container version. - TagManager.Accounts.Containers.Versions.publish(version.path); - var workspace = TagManager.Accounts.Containers.Workspaces.create( - {'name': 'appscript workspace', 'description': 'appscript workspace'}, - containerPath); - var workspaceId = workspace.path; - // Quick previews the current container draft. - var quickPreview = TagManager.Accounts.Containers.Workspaces.quick_preview( - workspace.path); - Logger.log(quickPreview); + try { + const containerPath = grabContainerPath(version.path); + // Publish the input container version. + TagManager.Accounts.Containers.Versions.publish(version.path); + const workspace = TagManager.Accounts.Containers.Workspaces.create( + {'name': 'appscript workspace', 'description': 'appscript workspace'}, + containerPath); + const workspaceId = workspace.path; + // Quick previews the current container draft. + const quickPreview = TagManager.Accounts.Containers.Workspaces + .quick_preview(workspace.path); + console.log(quickPreview); + } catch (e) { + // TODO (Developer) - Handle exceptions + console.log('Failed with error: $s', e.error); + } } // [END apps_script_tag_manager_publish_version] @@ -108,7 +119,7 @@ function publishVersionAndQuickPreviewDraft(version) { * @return {string} The container path. */ function grabContainerPath(versionPath) { - var pathParts = versionPath.split('/'); + const pathParts = versionPath.split('/'); return pathParts.slice(0, 4).join('/'); } @@ -118,20 +129,26 @@ function grabContainerPath(versionPath) { * @param {object} version The container version object. */ function createAndReauthorizeUserEnvironment(version) { - // Creates a container version. - var containerPath = grabContainerPath(version.path); - // Creates a user environment that points to a container version. - var environment = TagManager.Accounts.Containers.Environments.create( - { - 'name': 'test_environment', - 'type': 'user', - 'containerVersionId': version.containerVersionId - }, - containerPath); - Logger.log('Original user environment: ' + environment); - // Reauthorizes the user environment that points to a container version. - TagManager.Accounts.Containers.Environments.reauthorize({}, environment.path); - Logger.log('Reauthorized user environment: ' + environment); + try { + // Creates a container version. + const containerPath = grabContainerPath(version.path); + // Creates a user environment that points to a container version. + const environment = TagManager.Accounts.Containers.Environments.create( + { + 'name': 'test_environment', + 'type': 'user', + 'containerVersionId': version.containerVersionId + }, + containerPath); + console.log('Original user environment: ' + environment); + // Reauthorizes the user environment that points to a container version. + TagManager.Accounts.Containers.Environments.reauthorize( + {}, environment.path); + console.log('Reauthorized user environment: ' + environment); + } catch (e) { + // TODO (Developer) - Handle exceptions + console.log('Failed with error: $s', e.error); + } } // [END apps_script_tag_manager_create_user_environment] @@ -141,20 +158,25 @@ function createAndReauthorizeUserEnvironment(version) { * @param {string} accountPath The account path. */ function logAllAccountUserPermissionsWithContainerAccess(accountPath) { - var userPermissions = + try { + const userPermissions = TagManager.Accounts.User_permissions.list(accountPath).userPermission; - for (var i = 0; i < userPermissions.length; i++) { - var userPermission = userPermissions[i]; - if ('emailAddress' in userPermission) { - var containerAccesses = userPermission.containerAccess; - for (var j = 0; j < containerAccesses.length; j++) { - var containerAccess = containerAccesses[j]; - Logger.log( - 'emailAddress:' + userPermission.emailAddress + ' containerId:' + - containerAccess.containerId + ' containerAccess:' + - containerAccess.permission); + for (let i = 0; i < userPermissions.length; i++) { + const userPermission = userPermissions[i]; + if ('emailAddress' in userPermission) { + const containerAccesses = userPermission.containerAccess; + for (let j = 0; j < containerAccesses.length; j++) { + const containerAccess = containerAccesses[j]; + console.log( + 'emailAddress:' + userPermission.emailAddress + + ' containerId:' + containerAccess.containerId + + ' containerAccess:' + containerAccess.permission); + } } } + } catch (e) { + // TODO (Developer) - Handle exceptions + console.log('Failed with error: $s', e.error); } } // [END apps_script_tag_manager_log] diff --git a/advanced/tasks.gs b/advanced/tasks.gs index 2e9e90be7..af1e3bd9c 100644 --- a/advanced/tasks.gs +++ b/advanced/tasks.gs @@ -24,17 +24,17 @@ function listTaskLists() { const taskLists = Tasks.Tasklists.list(); // If taskLists are available then print all tasklists. if (!taskLists.items) { - Logger.log('No task lists found.'); + console.log('No task lists found.'); return; } // Print the tasklist title and tasklist id. for (let i = 0; i < taskLists.items.length; i++) { const taskList = taskLists.items[i]; - Logger.log('Task list with title "%s" and ID "%s" was found.', taskList.title, taskList.id); + console.log('Task list with title "%s" and ID "%s" was found.', taskList.title, taskList.id); } } catch (err) { // TODO (developer) - Handle exception from Task API - Logger.log('Failed with an error %s ', err.message); + console.log('Failed with an error %s ', err.message); } } // [END tasks_lists_task_lists] @@ -51,17 +51,17 @@ function listTasks(taskListId) { const tasks = Tasks.Tasks.list(taskListId); // If tasks are available then print all task of given tasklists. if (!tasks.items) { - Logger.log('No tasks found.'); + console.log('No tasks found.'); return; } // Print the task title and task id of specified tasklist. for (let i = 0; i < tasks.items.length; i++) { const task = tasks.items[i]; - Logger.log('Task with title "%s" and ID "%s" was found.', task.title, task.id); + console.log('Task with title "%s" and ID "%s" was found.', task.title, task.id); } } catch (err) { // TODO (developer) - Handle exception from Task API - Logger.log('Failed with an error %s', err.message); + console.log('Failed with an error %s', err.message); } } // [END tasks_list_tasks] @@ -82,10 +82,10 @@ function addTask(taskListId) { // Call insert method with taskDetails and taskListId to insert Task to specified tasklist. task = Tasks.Tasks.insert(task, taskListId); // Print the Task ID of created task. - Logger.log('Task with ID "%s" was created.', task.id); + console.log('Task with ID "%s" was created.', task.id); } catch (err) { // TODO (developer) - Handle exception from Tasks.insert() of Task API - Logger.log('Failed with an error %s', err.message); + console.log('Failed with an error %s', err.message); } } // [END tasks_add_task] diff --git a/advanced/test_adminSDK.gs b/advanced/test_adminSDK.gs new file mode 100644 index 000000000..fb825fe04 --- /dev/null +++ b/advanced/test_adminSDK.gs @@ -0,0 +1,147 @@ +/** + * 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. + */ + +/** + * Tests listAllUsers function of adminSDK.gs + */ +function itShouldListAllUsers() { + console.log('> itShouldListAllUsers'); + listAllUsers(); +} + +/** + * Tests getUser function of adminSDK.gs + */ +function itShouldGetUser() { + console.log('> itShouldGetUser'); + getUser(); +} + +/** + * Tests addUser function of adminSDK.gs + */ +function itShouldAddUser() { + console.log('> itShouldAddUser'); + addUser(); +} + +/** + * Tests createAlias function of adminSDK.gs + */ +function itShouldCreateAlias() { + console.log('> itShouldCreateAlias'); + createAlias(); +} + +/** + * Tests listAllGroups function of adminSDK.gs + */ +function itShouldListAllGroups() { + console.log('> itShouldListAllGroups'); + listAllGroups(); +} + +/** + * Tests addGroupMember function of adminSDK.gs + */ +function itShouldAddGroupMember() { + console.log('> itShouldAddGroupMember'); + addGroupMember(); +} + +/** + * Tests migrateMessages function of adminSDK.gs + */ +function itShouldMigrateMessages() { + console.log('> itShouldMigrateMessages'); + migrateMessages(); +} + +/** + * Tests getGroupSettings function of adminSDK.gs + */ +function itShouldGetGroupSettings() { + console.log('> itShouldGetGroupSettings'); + getGroupSettings(); +} + +/** + * Tests updateGroupSettings function of adminSDK.gs + */ +function itShouldUpdateGroupSettings() { + console.log('> itShouldUpdateGroupSettings'); + updateGroupSettings(); +} + +/** + * Tests getLicenseAssignments function of adminSDK.gs + */ +function itShouldGetLicenseAssignments() { + console.log('> itShouldGetLicenseAssignments'); + getLicenseAssignments(); +} + +/** + * Tests insertLicenseAssignment function of adminSDK.gs + */ +function itShouldInsertLicenseAssignment() { + console.log('> itShouldInsertLicenseAssignment'); + insertLicenseAssignment(); +} + +/** + * Tests generateLoginActivityReport function of adminSDK.gs + */ +function itShouldGenerateLoginActivityReport() { + console.log('> itShouldGenerateLoginActivityReport'); + generateLoginActivityReport(); +} + +/** + * Tests generateUserUsageReport function of adminSDK.gs + */ +function itShouldGenerateUserUsageReport() { + console.log('> itShouldGenerateUserUsageReport'); + generateUserUsageReport(); +} + +/** + * Tests getSubscriptions function of adminSDK.gs + */ +function itShouldGetSubscriptions() { + console.log('> itShouldGetSubscriptions'); + getSubscriptions(); +} + +/** + * Runs all the tests + */ +function RUN_ALL_TESTS() { + itShouldListAllUsers(); + itShouldGetUser(); + itShouldAddUser(); + itShouldCreateAlias(); + itShouldListAllGroups(); + itShouldAddGroupMember(); + itShouldMigrateMessages(); + itShouldGetGroupSettings(); + itShouldUpdateGroupSettings(); + itShouldGetLicenseAssignments(); + itShouldInsertLicenseAssignment(); + itShouldGenerateLoginActivityReport(); + itShouldGenerateUserUsageReport(); + itShouldGetSubscriptions(); +} diff --git a/advanced/test_adsense.gs b/advanced/test_adsense.gs new file mode 100644 index 000000000..1b7ef1e24 --- /dev/null +++ b/advanced/test_adsense.gs @@ -0,0 +1,52 @@ +/** + * 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. + */ + +// Replace with correct values +const accountName = 'account name'; +const clientName = 'ad client name'; + +/** + * Tests listAccounts function of adsense.gs + */ +function itShouldListAccounts() { + console.log('> itShouldListAccounts'); + listAccounts(); +} + +/** + * Tests listAdClients function of adsense.gs + */ +function itShouldListAdClients() { + console.log('> itShouldListAdClients'); + listAdClients(accountName); +} + +/** + * Tests listAdUnits function of adsense.gs + */ +function itShouldListAdUnits() { + console.log('> itShouldListAdUnits'); + listAdUnits(clientName); +} + +/** + * Run all tests + */ +function RUN_ALL_TESTS() { + itShouldListAccounts(); + itShouldListAdClients(); + itShouldListAdUnits(); +} diff --git a/advanced/test_analytics.gs b/advanced/test_analytics.gs new file mode 100644 index 000000000..505974c2b --- /dev/null +++ b/advanced/test_analytics.gs @@ -0,0 +1,42 @@ +/** + * 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. + */ + +// Replace with the required profileId +const profileId = 'abcd'; + +/** + * Tests listAccounts function of analytics.gs + */ +function itShouldListAccounts() { + console.log('> itShouldListAccounts'); + listAccounts(); +} + +/** + * Tests runReport function of analytics.gs + */ +function itShouldRunReport() { + console.log('> itShouldRunReport'); + runReport(profileId); +} + +/** + * Runs all the tests + */ +function RUN_ALL_TESTS() { + itShouldListAccounts(); + itShouldRunReport(); +} diff --git a/advanced/test_bigquery.gs b/advanced/test_bigquery.gs new file mode 100644 index 000000000..d79373b2f --- /dev/null +++ b/advanced/test_bigquery.gs @@ -0,0 +1,39 @@ +/** + * 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. + */ + +/** + * Tests runQuery function of adminSDK.gs + */ +function itShouldRunQuery() { + console.log('> itShouldRunQuery'); + runQuery(); +} + +/** + * Tests loadCsv function of adminSDK.gs + */ +function itShouldLoadCsv() { + console.log('> itShouldLoadCsv'); + loadCsv(); +} + +/** + * Runs all the tests + */ +function RUN_ALL_TESTS() { + itShouldRunQuery(); + itShouldLoadCsv(); +} diff --git a/advanced/test_calendar.gs b/advanced/test_calendar.gs index 4a8f46ed0..ceec9a2a4 100644 --- a/advanced/test_calendar.gs +++ b/advanced/test_calendar.gs @@ -18,7 +18,7 @@ * Tests listCalendars function of calendar.gs */ function itShouldListCalendars() { - Logger.log('> itShouldListCalendars'); + console.log('> itShouldListCalendars'); listCalendars(); } @@ -26,7 +26,7 @@ function itShouldListCalendars() { * Tests createEvent function of calendars.gs */ function itShouldCreateEvent() { - Logger.log('> itShouldCreateEvent'); + console.log('> itShouldCreateEvent'); createEvent(); } @@ -34,18 +34,18 @@ function itShouldCreateEvent() { * Tests gerRelativeDate function of calendar.gs */ function itShouldGetRelativeDate() { - Logger.log('> itShouldGetRelativeDate'); - Logger.log('no offset: ' + getRelativeDate(0, 0)); - Logger.log('4 hour offset: ' + getRelativeDate(0, 4)); - Logger.log('1 day offset: ' + getRelativeDate(1, 0)); - Logger.log('1 day and 3 hour off set: ' + getRelativeDate(1, 3)); + console.log('> itShouldGetRelativeDate'); + console.log('no offset: ' + getRelativeDate(0, 0)); + console.log('4 hour offset: ' + getRelativeDate(0, 4)); + console.log('1 day offset: ' + getRelativeDate(1, 0)); + console.log('1 day and 3 hour off set: ' + getRelativeDate(1, 3)); } /** * Tests listNext10Events function of calendar.gs */ function itShouldListNext10Events() { - Logger.log('> itShouldListNext10Events'); + console.log('> itShouldListNext10Events'); listNext10Events(); } @@ -53,7 +53,7 @@ function itShouldListNext10Events() { * Tests logSyncedEvents function of calendar.gs */ function itShouldLogSyncedEvents() { - Logger.log('> itShouldLogSyncedEvents'); + console.log('> itShouldLogSyncedEvents'); logSyncedEvents('primary', true); logSyncedEvents('primary', false); } @@ -62,7 +62,7 @@ function itShouldLogSyncedEvents() { * Tests conditionalUpdate function of calendar.gs */ function itShouldConditionalUpdate() { - Logger.log('> itShouldConditionalUpdate (takes 30 seconds)'); + console.log('> itShouldConditionalUpdate (takes 30 seconds)'); conditionalUpdate(); } @@ -70,7 +70,7 @@ function itShouldConditionalUpdate() { * Tests conditionalFetch function of calendar.gs */ function itShouldConditionalFetch() { - Logger.log('> itShouldConditionalFetch'); + console.log('> itShouldConditionalFetch'); conditionalFetch(); } diff --git a/advanced/test_classroom.gs b/advanced/test_classroom.gs new file mode 100644 index 000000000..bbe2d7625 --- /dev/null +++ b/advanced/test_classroom.gs @@ -0,0 +1,30 @@ +/** + * 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. + */ + +/** + * Tests listCourses function of classroom.gs + */ +function itShouldListCourses() { + console.log('> itShouldListCourses'); + listCourses(); +} + +/** + * Runs all the tests + */ +function RUN_ALL_TESTS() { + itShouldListCourses(); +} diff --git a/advanced/test_docs.gs b/advanced/test_docs.gs index 77cb44b50..97bbd35ce 100644 --- a/advanced/test_docs.gs +++ b/advanced/test_docs.gs @@ -21,10 +21,10 @@ const documentId='1EaLpBfuo3bMUeP6_P34auuQroh3bCWi6hLDppY6J6us'; */ function expectToExist(value) { if (!value) { - Logger.log('DNE'); + console.log('DNE'); return; } - Logger.log('TEST: Exists'); + console.log('TEST: Exists'); } /** @@ -35,10 +35,10 @@ function expectToExist(value) { */ function expectToEqual(expected, actual) { if (actual !== expected) { - Logger.log('TEST: actual: %s = expected: %s', actual, expected); + console.log('TEST: actual: %s = expected: %s', actual, expected); return; } - Logger.log('TEST: actual: %s = expected: %s', actual, expected); + console.log('TEST: actual: %s = expected: %s', actual, expected); } diff --git a/advanced/test_doubleclick.gs b/advanced/test_doubleclick.gs new file mode 100644 index 000000000..c0efee4b8 --- /dev/null +++ b/advanced/test_doubleclick.gs @@ -0,0 +1,48 @@ +/** + * 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. + */ + +/** + * Tests listUserProfiles function of doubleclick.gs + */ +function itShouldListUserProfiles() { + console.log('> itShouldListUserProfiles'); + listUserProfiles(); +} + +/** + * Tests listActiveCampaigns function of doubleclick.gs + */ +function itShouldListActiveCampaigns() { + console.log('> itShouldListActiveCampaigns'); + listActiveCampaigns(); +} + +/** + * Tests createAdvertiserAndCampaign function of doubleclick.gs + */ +function itShouldCreateAdvertiserAndCampaign() { + console.log('> itShouldCreateAdvertiserAndCampaign'); + createAdvertiserAndCampaign(); +} + +/** + * Run all tests + */ +function RUN_ALL_TESTS() { + itShouldListUserProfiles(); + itShouldListActiveCampaigns(); + itShouldCreateAdvertiserAndCampaign(); +} diff --git a/advanced/test_drive.gs b/advanced/test_drive.gs index 26366f116..f3ebd5eeb 100644 --- a/advanced/test_drive.gs +++ b/advanced/test_drive.gs @@ -93,7 +93,7 @@ function checkListRootFolders() { const folders = DriveApp.getFolders(); while (folders.hasNext()) { const folder = folders.next(); - Logger.log(folder.getName() + ' ' + folder.getId()); + console.log(folder.getName() + ' ' + folder.getId()); } listRootFolders(); folderCleanUp(); diff --git a/advanced/test_gmail.gs b/advanced/test_gmail.gs index 1a78e2d18..494871f66 100644 --- a/advanced/test_gmail.gs +++ b/advanced/test_gmail.gs @@ -19,12 +19,12 @@ * Add gmail services to run */ function RUN_ALL_TESTS() { - Logger.log('> ltShouldListLabelInfo'); + console.log('> ltShouldListLabelInfo'); listLabelInfo(); - Logger.log('> ltShouldListInboxSnippets'); + console.log('> ltShouldListInboxSnippets'); listInboxSnippets(); - Logger.log('> ltShouldLogRecentHistory'); + console.log('> ltShouldLogRecentHistory'); logRecentHistory(); - Logger.log('> ltShouldGetRawMessage'); + console.log('> ltShouldGetRawMessage'); getRawMessage(); } diff --git a/advanced/test_people.gs b/advanced/test_people.gs index d365ed1e1..07e1e09e0 100644 --- a/advanced/test_people.gs +++ b/advanced/test_people.gs @@ -20,10 +20,10 @@ * to tests people.gs add people api services */ function RUN_ALL_TESTS() { - Logger.log('> itShouldGetConnections'); + console.log('> itShouldGetConnections'); getConnections(); - Logger.log('> itShouldGetSelf'); // Requires the scope userinfo.profile + console.log('> itShouldGetSelf'); // Requires the scope userinfo.profile getSelf(); - Logger.log('> itShouldGetAccount'); + console.log('> itShouldGetAccount'); getAccount('me'); } diff --git a/advanced/test_sheets.gs b/advanced/test_sheets.gs index bc09c7cfd..345214c06 100644 --- a/advanced/test_sheets.gs +++ b/advanced/test_sheets.gs @@ -55,7 +55,7 @@ function populateValues(spreadsheetId) { * @return {string} spreadsheet ID */ function itShouldReadRange() { - Logger.log('> itShouldReadRange'); + console.log('> itShouldReadRange'); spreadsheetId = createTestSpreadsheet(); populateValues(spreadsheetId); readRange(spreadsheetId); @@ -67,13 +67,13 @@ function itShouldReadRange() { * @param {string} spreadsheetId */ function itShouldAddPivotTable(spreadsheetId) { - Logger.log('> itShouldAddPivotTable'); + console.log('> itShouldAddPivotTable'); const spreadsheet = SpreadsheetApp.openById(spreadsheetId); const sheets = spreadsheet.getSheets(); sheetId = sheets[0].getSheetId(); addPivotTable(spreadsheetId, sheetId, sheetId); SpreadsheetApp.flush(); - Logger.log('Created pivot table'); + console.log('Created pivot table'); } /** @@ -81,9 +81,9 @@ function itShouldAddPivotTable(spreadsheetId) { */ function RUN_ALL_TEST() { const spreadsheetId = itShouldReadRange(); - Logger.log('> itShouldWriteToMultipleRanges'); + console.log('> itShouldWriteToMultipleRanges'); writeToMultipleRanges(spreadsheetId); - Logger.log('> itShouldAddSheet'); + console.log('> itShouldAddSheet'); addSheet(spreadsheetId); itShouldAddPivotTable(spreadsheetId); } diff --git a/advanced/test_shoppingContent.gs b/advanced/test_shoppingContent.gs new file mode 100644 index 000000000..14cc296c2 --- /dev/null +++ b/advanced/test_shoppingContent.gs @@ -0,0 +1,62 @@ +/** + * 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. + */ + +// Before running these tests replace the product resource variables +const productResource1 = {}; +const productResource2 = {}; +const productResource3 = {}; + +/** + * Tests productInsert function of shoppingContent.gs + */ +function itShouldProductInsert() { + console.log('> itShouldPproductInsert'); + productInsert(); +} + +/** + * Tests productList function of shoppingContent.gs + */ +function itShouldProductList() { + console.log('> itShouldProductList'); + productList(); +} + +/** + * Tests custombatch function of shoppingContent.gs + */ +function itShouldCustombatch() { + console.log('> itShouldCustombatch'); + custombatch(productResource1, productResource2, productResource3); +} + +/** + * Tests updateAccountTax function of shoppingContent.gs + */ +function itShouldUpdateAccountTax() { + console.log('> itShouldUpdateAccountTax'); + updateAccountTax(); +} + +/** + * Run all tests + */ +function RUN_ALL_TESTS() { + itShouldProductInsert(); + itShouldProductList(); + itShouldCustombatch(); + itShouldUpdateAccountTax(); +} diff --git a/advanced/test_slides.gs b/advanced/test_slides.gs index c37763064..156221503 100644 --- a/advanced/test_slides.gs +++ b/advanced/test_slides.gs @@ -20,10 +20,10 @@ */ function expectToExist(value) { if (!value) { - Logger.log('DNE'); + console.log('DNE'); return; } - Logger.log('TEST: Exists'); + console.log('TEST: Exists'); } /** @@ -33,10 +33,10 @@ function expectToExist(value) { */ function expectToEqual(expected, actual) { if (actual !== expected) { - Logger.log('TEST: actual: %s = expected: %s', actual, expected); + console.log('TEST: actual: %s = expected: %s', actual, expected); return; } - Logger.log('TEST: actual: %s = expected: %s', actual, expected); + console.log('TEST: actual: %s = expected: %s', actual, expected); } /** * Creates a presentation. @@ -86,7 +86,7 @@ function addShape(presentationId, pageId) { requests: requests }, presentationId); const createShapeResponse = createTextboxWithTextResponse.replies[0].createShape; - Logger.log('Created textbox with ID: %s', createShapeResponse.objectId); + console.log('Created textbox with ID: %s', createShapeResponse.objectId); // [END slides_create_textbox_with_text] return createShapeResponse.objectId; } @@ -117,7 +117,7 @@ function itShouldCreateAPresentation() { * Creates a new slide. */ function itShouldCreateASlide() { - Logger.log('> itShouldCreateASlide'); + console.log('> itShouldCreateASlide'); const presentationId = createPresentation(); const slideId=createSlide(presentationId); expectToExist(slideId); diff --git a/advanced/test_tagManager.gs b/advanced/test_tagManager.gs new file mode 100644 index 000000000..42053dd27 --- /dev/null +++ b/advanced/test_tagManager.gs @@ -0,0 +1,65 @@ +/** + * 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. + */ +// Before running tagManager tests create a test tagMAnager account +// and replace the value below with its account path +const path = 'accounts/6007387289'; + +/** + * Tests createContainerVersion function of tagManager.gs + * @param {string} accountPath Tag manager account's path + * @return {object} version The container version + */ +function itShouldCreateContainerVersion(accountPath) { + console.log('> itShouldCreateContainerVersion'); + const version = createContainerVersion(accountPath); + return version; +} + +/** + * Tests publishVersionAndQuickPreviewDraft function of tagManager.gs + * @param {object} version tag managers container version + */ +function itShouldPublishVersionAndQuickPreviewDraft(version) { + console.log('> itShouldPublishVersionAndQuickPreviewDraft'); + publishVersionAndQuickPreviewDraft(version); +} + +/** + * Tests createAndReauthorizeUserEnvironment function of tagManager.gs + * @param {object} version tag managers container version + */ +function itShouldCreateAndReauthorizeUserEnvironment(version) { + console.log('> itShouldCreateAndReauthorizeUserEnvironment'); + createAndReauthorizeUserEnvironment(version); +} + +/** + * Tests logAllAccountUserPermissionsWithContainerAccess function of tagManager.gs + * @param {string} accountPath Tag manager account's path + */ +function itShouldLogAllAccountUserPermissionsWithContainerAccess(accountPath) { + console.log('> itShouldLogAllAccountUserPermissionsWithContainerAccess'); + logAllAccountUserPermissionsWithContainerAccess(accountPath); +} +/** + * Runs all tests + */ +function RUN_ALL_TESTS() { + const version = itShouldCreateContainerVersion(path); + itShouldPublishVersionAndQuickPreviewDraft(version); + itShouldCreateAndReauthorizeUserEnvironment(version); + itShouldLogAllAccountUserPermissionsWithContainerAccess(path); +} diff --git a/advanced/test_tasks.gs b/advanced/test_tasks.gs index 4aead942d..b38668fcd 100644 --- a/advanced/test_tasks.gs +++ b/advanced/test_tasks.gs @@ -24,7 +24,7 @@ * tests listTaskLists of tasks.gs */ function itShouldListTaskLists() { - Logger.log('> itShouldListTaskLists'); + console.log('> itShouldListTaskLists'); listTaskLists(); } @@ -32,7 +32,7 @@ function itShouldListTaskLists() { * tests listTasks of tasks.gs */ function itShouldListTasks() { - Logger.log('> itShouldListTasks'); + console.log('> itShouldListTasks'); const taskId = Tasks.Tasklists.list().items[0].id; listTasks(taskId); } @@ -41,7 +41,7 @@ function itShouldListTasks() { * tests addTask of tasks.gs */ function itShouldAddTask() { - Logger.log('> itShouldAddTask'); + console.log('> itShouldAddTask'); const taskId = Tasks.Tasklists.list().items[0].id; addTask(taskId); } diff --git a/advanced/test_youtube.gs b/advanced/test_youtube.gs index df3c68c04..6afd7454d 100644 --- a/advanced/test_youtube.gs +++ b/advanced/test_youtube.gs @@ -18,12 +18,12 @@ * Run all tests */ function RUN_ALL_TESTS() { - Logger.log('> itShouldSearchByKeyword'); + console.log('> itShouldSearchByKeyword'); searchByKeyword(); - Logger.log('> itShouldRetrieveMyUploads'); + console.log('> itShouldRetrieveMyUploads'); retrieveMyUploads(); - Logger.log('> itShouldAddSubscription'); + console.log('> itShouldAddSubscription'); addSubscription(); - Logger.log('> itShouldCreateSlides'); + console.log('> itShouldCreateSlides'); createSlides(); } diff --git a/advanced/test_youtubeAnalytics.gs b/advanced/test_youtubeAnalytics.gs new file mode 100644 index 000000000..5211bfb83 --- /dev/null +++ b/advanced/test_youtubeAnalytics.gs @@ -0,0 +1,30 @@ +/** + * 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. + */ + +/** + * Tests createReport function of youtubeAnalytics.gs + */ +function itShouldCreateReport() { + console.log('> itShouldCreateReport'); + createReport(); +} + +/** + * Run all tests + */ +function RUN_ALL_TESTS() { + itShouldCreateReport(); +} diff --git a/advanced/test_youtubeContentId.gs b/advanced/test_youtubeContentId.gs new file mode 100644 index 000000000..350c88de7 --- /dev/null +++ b/advanced/test_youtubeContentId.gs @@ -0,0 +1,48 @@ +/** + * 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. + */ + +/** + * Tests claimYourVideoWithMonetizePolicy function of youtubeContentId.gs + */ +function itShouldClaimVideoWithMonetizePolicy() { + console.log('> itShouldClaimVideoWithMonetizePolicy'); + claimYourVideoWithMonetizePolicy(); +} + +/** + * Tests updateAssetOwnership function of youtubeContentId.gs + */ +function itShouldUpdateAssetOwnership() { + console.log('> itShouldUpdateAssetOwnership'); + updateAssetOwnership(); +} + +/** + * Tests releaseClaim function of youtubeContentId.gs + */ +function itShouldReleaseClaim() { + console.log('> itShouldReleaseClaim'); + releaseClaim(); +} + +/** + * Run all tests + */ +function RUN_ALL_TESTS() { + itShouldClaimVideoWithMonetizePolicy(); + itShouldUpdateAssetOwnership(); + itShouldReleaseClaim(); +} diff --git a/advanced/urlShortener.gs b/advanced/urlShortener.gs deleted file mode 100644 index e39c85361..000000000 --- a/advanced/urlShortener.gs +++ /dev/null @@ -1,39 +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_url_shortener_shorten] -/** - * Shortens a long URL. Logs this URL. - */ -function shortenUrl() { - var url = UrlShortener.Url.insert({ - longUrl: 'http://www.example.com' - }); - Logger.log('Shortened URL is "%s".', url.id); -} -// [END apps_script_url_shortener_shorten] - -// [START apps_script_url_shortener_get_clicks] -/** - * Logs the number of clicks to a short URL over the last week. - * @param {string} shortUrl The short URL. - */ -function getClicks(shortUrl) { - var url = UrlShortener.Url.get(shortUrl, { - projection: 'ANALYTICS_CLICKS' - }); - Logger.log('The URL received %s clicks this week.', url.analytics.week.shortUrlClicks); -} -// [END apps_script_url_shortener_get_clicks] diff --git a/advanced/youtube.gs b/advanced/youtube.gs index c3e0dd8b3..87a2f86d8 100644 --- a/advanced/youtube.gs +++ b/advanced/youtube.gs @@ -27,15 +27,15 @@ function searchByKeyword() { maxResults: 25 }); if (results === null) { - Logger.log('Unable to search videos'); + console.log('Unable to search videos'); return; } results.items.forEach((item)=> { - Logger.log('[%s] Title: %s', item.id.videoId, item.snippet.title); + console.log('[%s] Title: %s', item.id.videoId, item.snippet.title); }); } catch (err) { // TODO (developer) - Handle exceptions from Youtube API - Logger.log('Failed with an error %s', err.message); + console.log('Failed with an error %s', err.message); } } // [END apps_script_youtube_search] @@ -55,7 +55,7 @@ function retrieveMyUploads() { mine: true }); if (!results || results.items.length === 0) { - Logger.log('No Channels found.'); + console.log('No Channels found.'); return; } for (let i = 0; i < results.items.length; i++) { @@ -73,12 +73,12 @@ function retrieveMyUploads() { pageToken: nextPageToken }); if (!playlistResponse || playlistResponse.items.length === 0) { - Logger.log('No Playlist found.'); + console.log('No Playlist found.'); break; } for (let j = 0; j < playlistResponse.items.length; j++) { const playlistItem = playlistResponse.items[j]; - Logger.log('[%s] Title: %s', + console.log('[%s] Title: %s', playlistItem.snippet.resourceId.videoId, playlistItem.snippet.title); } @@ -87,7 +87,7 @@ function retrieveMyUploads() { } } catch (err) { // TODO (developer) - Handle exception - Logger.log('Failed with err %s', err.message); + console.log('Failed with err %s', err.message); } } // [END apps_script_youtube_uploads] @@ -99,7 +99,7 @@ function retrieveMyUploads() { */ function addSubscription() { // Replace this channel ID with the channel ID you want to subscribe to - const channelId = 'UC9gFih9rw0zNCK3ZtoKQQyA'; + const channelId = 'UC_x5XG1OV2P6uZZ5FSM9Ttw'; const resource = { snippet: { resourceId: { @@ -111,14 +111,14 @@ function addSubscription() { try { const response = YouTube.Subscriptions.insert(resource, 'snippet'); - Logger.log('Added subscription for channel title : %s', response.snippet.title); + console.log('Added subscription for channel title : %s', response.snippet.title); } catch (e) { if (e.message.match('subscriptionDuplicate')) { - Logger.log('Cannot subscribe; already subscribed to channel: ' + + console.log('Cannot subscribe; already subscribed to channel: ' + channelId); } else { // TODO (developer) - Handle exception - Logger.log('Error adding subscription: ' + e.message); + console.log('Error adding subscription: ' + e.message); } } } @@ -165,7 +165,7 @@ function createSlides() { presentation.getSlides()[0].getPageElements()[0].asShape() .getText().setText(PRESENTATION_TITLE); if (!presentation) { - Logger.log('Unable to create presentation'); + console.log('Unable to create presentation'); return; } // Add slides with videos and log the presentation URL to the user. @@ -174,10 +174,10 @@ function createSlides() { slide.insertVideo(video.url, 0, 0, presentation.getPageWidth(), presentation.getPageHeight()); }); - Logger.log(presentation.getUrl()); + console.log(presentation.getUrl()); } catch (err) { // TODO (developer) - Handle exception - Logger.log('Failed with error %s', err.message); + console.log('Failed with error %s', err.message); } } // [END apps_script_youtube_slides] diff --git a/advanced/youtubeAnalytics.gs b/advanced/youtubeAnalytics.gs index 2d4182fc7..cfb0edda0 100644 --- a/advanced/youtubeAnalytics.gs +++ b/advanced/youtubeAnalytics.gs @@ -46,7 +46,7 @@ function createReport() { }); if (!result.rows) { - Logger.log('No rows returned.'); + console.log('No rows returned.'); return; } const spreadsheet = SpreadsheetApp.create('YouTube Analytics Report'); @@ -62,7 +62,7 @@ function createReport() { sheet.getRange(2, 1, result.rows.length, headers.length) .setValues(result.rows); - Logger.log('Report spreadsheet created: %s', + console.log('Report spreadsheet created: %s', spreadsheet.getUrl()); } diff --git a/advanced/youtubeContentId.gs b/advanced/youtubeContentId.gs index c68f6900a..22d37737c 100644 --- a/advanced/youtubeContentId.gs +++ b/advanced/youtubeContentId.gs @@ -40,9 +40,9 @@ function claimYourVideoWithMonetizePolicy() { try { const claimInserted = YouTubeContentId.Claims.insert(claimToInsert, {'onBehalfOfContentOwner': onBehalfOfContentOwner}); - Logger.log('Claim created on video %s: %s', videoId, claimInserted); + console.log('Claim created on video %s: %s', videoId, claimInserted); } catch (e) { - Logger.log('Failed to create claim on video %s, error: %s', + console.log('Failed to create claim on video %s, error: %s', videoId, e.message); } } @@ -76,9 +76,9 @@ function updateAssetOwnership() { try { const updatedOwnership = YouTubeContentId.Ownership.update(myAssetOwnership, assetId, {'onBehalfOfContentOwner': onBehalfOfContentOwner}); - Logger.log('Ownership updated on asset %s: %s', assetId, updatedOwnership); + console.log('Ownership updated on asset %s: %s', assetId, updatedOwnership); } catch (e) { - Logger.log('Ownership update failed on asset %s, error: %s', + console.log('Ownership update failed on asset %s, error: %s', assetId, e.message); } } @@ -102,9 +102,9 @@ function releaseClaim() { try { const claimReleased = YouTubeContentId.Claims.patch(claimToBeReleased, claimId, {'onBehalfOfContentOwner': onBehalfOfContentOwner}); - Logger.log('Claim %s was released: %s', claimId, claimReleased); + console.log('Claim %s was released: %s', claimId, claimReleased); } catch (e) { - Logger.log('Failed to release claim %s, error: %s', claimId, e.message); + console.log('Failed to release claim %s, error: %s', claimId, e.message); } } // [END apps_script_youtube_release_claim] diff --git a/apps-script/execute/target.js b/apps-script/execute/target.js index d0d7b67b8..aa79e72fc 100644 --- a/apps-script/execute/target.js +++ b/apps-script/execute/target.js @@ -1,3 +1,18 @@ +/** + * 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_api_execute] /** * Return the set of folder names contained in the user's root folder as an diff --git a/calendar/README.md b/calendar/README.md deleted file mode 100644 index 9174ad519..000000000 --- a/calendar/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Apps Scripts for Google Calendar - -## [Vacation Calendar](https://developers.google.com/apps-script/articles/vacation-calendar) - -This tutorial allows a user in a domain to automatically populate a team vacation calendar. diff --git a/calendar/quickstart/quickstart.gs b/calendar/quickstart/quickstart.gs index da7efabf7..026aedc6d 100644 --- a/calendar/quickstart/quickstart.gs +++ b/calendar/quickstart/quickstart.gs @@ -34,7 +34,7 @@ function listUpcomingEvents() { const response = Calendar.Events.list(calendarId, optionalArgs); const events = response.items; if (events.length === 0) { - Logger.log('No upcoming events found'); + console.log('No upcoming events found'); return; } // Print the calendar events @@ -43,11 +43,11 @@ function listUpcomingEvents() { if (!when) { when = event.start.date; } - Logger.log('%s (%s)', event.summary, when); + console.log('%s (%s)', event.summary, when); } } catch (err) { // TODO (developer) - Handle exception from Calendar API - Logger.log('Failed with error %s', err.message); + console.log('Failed with error %s', err.message); } } // [END calendar_quickstart] diff --git a/calendar/vacationCalendar/appsscript.json b/calendar/vacationCalendar/appsscript.json deleted file mode 100644 index bc80838f3..000000000 --- a/calendar/vacationCalendar/appsscript.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "timeZone": "America/Los_Angeles", - "dependencies": { - "enabledAdvancedServices": [{ - "userSymbol": "AdminDirectory", - "serviceId": "admin", - "version": "directory_v1" - }, { - "userSymbol": "Calendar", - "serviceId": "calendar", - "version": "v3" - }] - }, - "exceptionLogging": "STACKDRIVER" -} diff --git a/calendar/vacationCalendar/vacationCalendar.gs b/calendar/vacationCalendar/vacationCalendar.gs deleted file mode 100644 index 534cfbcbc..000000000 --- a/calendar/vacationCalendar/vacationCalendar.gs +++ /dev/null @@ -1,186 +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_calendar_vacation] -var TEAM_CALENDAR_ID = 'ENTER_TEAM_CALENDAR_ID_HERE'; -var KEYWORDS = ['vacation', 'ooo', 'out of office']; -var MONTHS_IN_ADVANCE = 3; - -// The maximum script run time under Apps Script Pro is 30 minutes; this setting -// will be used to report when the script is about to reach that limit. -var MAX_PRO_RUNTIME_MS = 29 * 60 * 1000; - -/** - * Look through the domain users' public calendars and add any - * 'vacation' or 'out of office' events to the team calendar. - */ -function syncTeamVacationCalendar() { - // Define the calendar event date range to search. - var today = new Date(); - var futureDate = new Date(); - futureDate.setMonth(futureDate.getMonth() + MONTHS_IN_ADVANCE); - var lastRun = PropertiesService.getScriptProperties().getProperty('lastRun'); - lastRun = lastRun ? new Date(lastRun) : null; - - // Get the list of users in the domain. - var users = getDomainUsers(); - - // For each user, find events having one or more of the keywords in the event - // summary in the specified date range. Import each of those to the team - // calendar. - var count = 0; - var timeout = false; - for (var i = 0; i < users.length; i++) { - if (isTimeUp(today, new Date())) { - timeout = true; - break; - } - var user = users[i]; - var username = user.split('@')[0]; - KEYWORDS.forEach(function(keyword) { - var events = findEvents(user, keyword, today, futureDate, lastRun); - events.forEach(function(event) { - event.summary = '[' + username + '] ' + event.summary; - event.organizer = { - id: TEAM_CALENDAR_ID - }; - event.attendees = []; - Logger.log('Importing: %s', event.summary); - try { - Calendar.Events.import(event, TEAM_CALENDAR_ID); - count++; - } catch (e) { - Logger.log( - 'Error attempting to import event: %s. Skipping.', e.toString()); - } - }); - }); - } - PropertiesService.getScriptProperties().setProperty('lastRun', today); - Logger.log('Imported ' + count + ' events'); - if (timeout) { - Logger.log('Execution time about to hit quota limit; execution stopped.'); - } - var executionTime = ((new Date()).getTime() - today.getTime()) / 1000.0; - Logger.log('Total execution time (s) : ' + executionTime); ; -} - -/** - * In a given user's calendar, look for occurrences of the given keyword - * in events within the specified date range and return any such events - * found. - * @param {string} user the user's primary email String. - * @param {string} keyword the keyword String 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} opt_since a Date indicating the last time this script was run. - * @return {object[]} an array of calendar event Objects. - */ -function findEvents(user, keyword, start, end, opt_since) { - var params = { - q: keyword, - timeMin: formatDate(start), - timeMax: formatDate(end), - showDeleted: true - }; - if (opt_since) { - // 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'] = formatDate(opt_since); - } - var results = []; - try { - var response = Calendar.Events.list(user, params); - results = response.items.filter(function(item) { - // Filter 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 (item.summary.toLowerCase().indexOf(keyword) < 0) { - return false; - } - // If the event was created by someone other than the user, only include - // it if the user has marked it as 'accepted'. - if (item.organizer && item.organizer.email != user) { - if (!item.attendees) { - return false; - } - var matching = item.attendees.filter(function(attendee) { - return attendee.self; - }); - return matching.length > 0 && matching[0].status == 'accepted'; - } - return true; - }); - } catch (e) { - Logger.log('Error retriving events for %s, %s: %s; skipping', - user, keyword, e.toString()); - results = []; - } - return results; -} - -/** - * Return a list of the primary emails of users in this domain. - * @return {string[]} An array of user email strings. - */ -function getDomainUsers() { - var pageToken; - var page; - var userEmails = []; - do { - page = AdminDirectory.Users.list({ - customer: 'my_customer', - orderBy: 'givenName', - maxResults: 100, - pageToken: pageToken, - viewType: 'domain_public' - }); - var users = page.users; - if (users) { - userEmails = userEmails.concat(users.map(function(user) { - return user.primaryEmail; - })); - } else { - Logger.log('No domain users found.'); - } - pageToken = page.nextPageToken; - } while (pageToken); - return userEmails; -} - -/** - * Return an RFC3339 formated date String corresponding to the given - * Date object. - * @param {Date} date a Date. - * @return {string} a formatted date string. - */ -function formatDate(date) { - return Utilities.formatDate(date, 'UTC', 'yyyy-MM-dd\'T\'HH:mm:ssZ'); -} - -/** - * Compares two Date objects and returns true if the difference - * between them is more than the maximum specified run time. - * - * @param {Date} start the first Date object. - * @param {Date} now the (later) Date object. - * @return {boolean} true if the time difference is greater than - * MAX_PROP_RUNTIME_MS (in milliseconds). - */ -function isTimeUp(start, now) { - return now.getTime() - start.getTime() > MAX_PRO_RUNTIME_MS; -} -// [END apps_script_calendar_vacation] diff --git a/classroom/quickstart/quickstart.gs b/classroom/quickstart/quickstart.gs index 94e9a07ef..1b61dc5fd 100644 --- a/classroom/quickstart/quickstart.gs +++ b/classroom/quickstart/quickstart.gs @@ -30,17 +30,17 @@ function listCourses() { const response = Classroom.Courses.list(optionalArgs); const courses = response.courses; if (!courses || courses.length === 0) { - Logger.log('No courses found.'); + console.log('No courses found.'); return; } // Print the course names and IDs of the courses for (const course of courses) { - Logger.log('%s (%s)', course.name, course.id); + console.log('%s (%s)', course.name, course.id); } } catch (err) { // TODO (developer)- Handle Courses.list() exception from Classroom API // get errors like PERMISSION_DENIED/INVALID_ARGUMENT/NOT_FOUND - Logger.log('Failed with error %s', err.message); + console.log('Failed with error %s', err.message); } } // [END classroom_quickstart] diff --git a/classroom/snippets/addAlias.gs b/classroom/snippets/addAlias.gs index ac14c0ce9..b48888bd1 100644 --- a/classroom/snippets/addAlias.gs +++ b/classroom/snippets/addAlias.gs @@ -25,10 +25,10 @@ function addAlias(course_id) { }; try { const course_alias = Classroom.Courses.Aliases.create(resource=alias, courseId=course_id); - Logger.log('%s successfully added as an alias!', course_alias.alias); + console.log('%s successfully added as an alias!', course_alias.alias); } catch (err) { // TODO (developer) - Handle exception - Logger.log('Request to add alias %s failed with error %s.', alias.alias, err.message); + console.log('Request to add alias %s failed with error %s.', alias.alias, err.message); } } // [END classroom_add_alias] diff --git a/classroom/snippets/courseUpdate.gs b/classroom/snippets/courseUpdate.gs index 53ab00a6a..ececcd627 100644 --- a/classroom/snippets/courseUpdate.gs +++ b/classroom/snippets/courseUpdate.gs @@ -27,10 +27,10 @@ function courseUpdate(courseId) { course.room = '302'; // Update the course course = Classroom.Courses.update(course, courseId); - Logger.log('Course "%s" updated.', course.name); + console.log('Course "%s" updated.', course.name); } catch (e) { // TODO (developer) - Handle exception - Logger.log('Failed to update the course with error %s', e.message); + console.log('Failed to update the course with error %s', e.message); } } // [END classroom_update_course] diff --git a/classroom/snippets/createAlias.gs b/classroom/snippets/createAlias.gs index 923552a5e..090342fde 100644 --- a/classroom/snippets/createAlias.gs +++ b/classroom/snippets/createAlias.gs @@ -32,10 +32,10 @@ function createAlias() { try { // Create the course using course details. course = Classroom.Courses.create(course); - Logger.log('Course created: %s (%s)', course.name, course.id); + console.log('Course created: %s (%s)', course.name, course.id); } catch (err) { // TODO (developer) - Handle Courses.create() exception - Logger.log('Failed to create course %s with an error %s', course.name, err.message); + console.log('Failed to create course %s with an error %s', course.name, err.message); } } // [END classroom_create_alias] diff --git a/classroom/snippets/createCourse.gs b/classroom/snippets/createCourse.gs index 174ecef8e..8aa5c87f3 100644 --- a/classroom/snippets/createCourse.gs +++ b/classroom/snippets/createCourse.gs @@ -17,6 +17,7 @@ /** * Creates 10th Grade Biology Course. * @see https://developers.google.com/classroom/reference/rest/v1/courses/create + * return {string} Id of created course */ function createCourse() { let course = { @@ -32,10 +33,11 @@ function createCourse() { try { // Create the course using course details. course = Classroom.Courses.create(course); - Logger.log('Course created: %s (%s)', course.name, course.id); + console.log('Course created: %s (%s)', course.name, course.id); + return course.id; } catch (err) { // TODO (developer) - Handle Courses.create() exception - Logger.log('Failed to create course %s with an error %s', course.name, err.message); + console.log('Failed to create course %s with an error %s', course.name, err.message); } } // [END classroom_create_course] diff --git a/classroom/snippets/getCourse.gs b/classroom/snippets/getCourse.gs index 620d745aa..25e1b3ffb 100644 --- a/classroom/snippets/getCourse.gs +++ b/classroom/snippets/getCourse.gs @@ -23,10 +23,10 @@ function getCourse(courseId) { try { // Get the course details using course id const course = Classroom.Courses.get(courseId); - Logger.log('Course "%s" found. ', course.name); + console.log('Course "%s" found. ', course.name); } catch (err) { // TODO (developer) - Handle Courses.get() exception of Handle Classroom API - Logger.log('Failed to found course %s with error %s ', courseId, err.message); + console.log('Failed to found course %s with error %s ', courseId, err.message); } } // [END classroom_get_course] diff --git a/classroom/snippets/listCourses.gs b/classroom/snippets/listCourses.gs index 27525975b..474dd04ef 100644 --- a/classroom/snippets/listCourses.gs +++ b/classroom/snippets/listCourses.gs @@ -29,17 +29,17 @@ function listCourses() { const response = Classroom.Courses.list(optionalArgs); courses = response.courses; if (courses.length === 0) { - Logger.log('No courses found.'); + console.log('No courses found.'); return; } // Print the courses available in classroom - Logger.log('Courses:'); + console.log('Courses:'); for ( const course in courses) { - Logger.log('%s (%s)', courses[course].name, courses[course].id); + console.log('%s (%s)', courses[course].name, courses[course].id); } } catch (err) { // TODO (developer) - Handle exception - Logger.log('Failed with error %s', err.message); + console.log('Failed with error %s', err.message); } } // [END classroom_list_courses] diff --git a/classroom/snippets/patchCourse.gs b/classroom/snippets/patchCourse.gs index e968c9a6f..56d97978a 100644 --- a/classroom/snippets/patchCourse.gs +++ b/classroom/snippets/patchCourse.gs @@ -30,10 +30,10 @@ function coursePatch(courseId) { try { // Update section and room in course. course = Classroom.Courses.patch(body=course, id=courseId, updateMask=mask); - Logger.log('Course "%s" updated.', course.name); + console.log('Course "%s" updated.', course.name); } catch (err) { // TODO (developer) - Handle Courses.patch() exception - Logger.log('Failed to update the course. Error message: %s', err.message); + console.log('Failed to update the course. Error message: %s', err.message); } } // [END classroom_patch_course] diff --git a/classroom/snippets/test_classroom_snippets.gs b/classroom/snippets/test_classroom_snippets.gs new file mode 100644 index 000000000..7a024d6a6 --- /dev/null +++ b/classroom/snippets/test_classroom_snippets.gs @@ -0,0 +1,90 @@ +/** + * 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. + */ + +/** + * Tests createCourse function of createCourse.gs + * @return {string} courseId course id of created course + */ +function itShouldCreateCourse() { + console.log('> itShouldCreateCourse'); + const courseId = createCourse(); + return courseId; +} + +/** + * Tests getCourse function of getCourse.gs + * @param {string} courseId course id + */ +function itShouldGetCourse(courseId) { + console.log('> itShouldGetCourse'); + getCourse(courseId); +} + +/** + * Tests createAlias function of createAlias.gs + */ +function itShouldCreateAlias() { + console.log('> itShouldCreateAlias'); + createAlias(); +} + +/** + * Tests addAlias function of addAlias.gs + * @param {string} courseId course id + */ +function itShouldAddAlias(courseId) { + console.log('> itShouldAddAlias'); + addAlias(courseId); +} + +/** + * Tests courseUpdate function of courseUpdate.gs + * @param {string} courseId course id + */ +function itShouldUpdateCourse(courseId) { + console.log('> itShouldUpdateCourse'); + courseUpdate(courseId); +} + +/** + * Tests coursePatch function of patchCourse.gs + * @param {string} courseId course id + */ +function itShouldPatchCourse(courseId) { + console.log('> itShouldPatchCourse'); + coursePatch(courseId); +} + +/** + * Tests listCourses function of listCourses.gs + */ +function itShouldListCourses() { + console.log('> itShouldListCourses'); + listCourses(); +} + +/** + * Runs all the tests + */ +function RUN_ALL_TESTS() { + const courseId = itShouldCreateCourse(); + itShouldGetCourse(courseId); + itShouldCreateAlias(); + itShouldAddAlias(courseId); + itShouldUpdateCourse(courseId); + itShouldPatchCourse(courseId); + itShouldListCourses(); +} diff --git a/data-studio/auth.gs b/data-studio/auth.gs index 0d7104fdf..5035107ee 100644 --- a/data-studio/auth.gs +++ b/data-studio/auth.gs @@ -133,9 +133,9 @@ function resetAuth() { * Resets the auth service. */ function resetAuth() { - var user_tokenProperties = PropertiesService.getUserProperties(); - user_tokenProperties.deleteProperty('dscc.username'); - user_tokenProperties.deleteProperty('dscc.password'); + var userTokenProperties = PropertiesService.getUserProperties(); + userTokenProperties.deleteProperty('dscc.username'); + userTokenProperties.deleteProperty('dscc.password'); } // [END apps_script_data_studio_auth_reset_user_token] diff --git a/docs/cursorInspector/sidebar.css.html b/docs/cursorInspector/sidebar.css.html index 685176869..4f5d09fec 100644 --- a/docs/cursorInspector/sidebar.css.html +++ b/docs/cursorInspector/sidebar.css.html @@ -1,3 +1,19 @@ + + diff --git a/docs/cursorInspector/sidebar.html b/docs/cursorInspector/sidebar.html index 7880f0ea7..b21def38b 100644 --- a/docs/cursorInspector/sidebar.html +++ b/docs/cursorInspector/sidebar.html @@ -1,3 +1,19 @@ + +
diff --git a/docs/cursorInspector/sidebar.js.html b/docs/cursorInspector/sidebar.js.html index e52c32fac..c73566080 100644 --- a/docs/cursorInspector/sidebar.js.html +++ b/docs/cursorInspector/sidebar.js.html @@ -1,5 +1,21 @@ + + - + diff --git a/docs/quickstart/quickstart.gs b/docs/quickstart/quickstart.gs index 49f630ddd..ea514fc00 100644 --- a/docs/quickstart/quickstart.gs +++ b/docs/quickstart/quickstart.gs @@ -25,10 +25,10 @@ function printDocTitle() { // Get the document using document id const doc = Docs.Documents.get(documentId); // Log the title of document. - Logger.log('The title of the doc is: %s', doc.title); + console.log('The title of the doc is: %s', doc.title); } catch (err) { // TODO (developer) - Handle exception from Docs API - Logger.log('Failed to found document with an error %s', err.message); + console.log('Failed to found document with an error %s', err.message); } } // [END docs_quickstart] diff --git a/drive/activity-v2/quickstart.gs b/drive/activity-v2/quickstart.gs index 45bd8789b..662d2060b 100644 --- a/drive/activity-v2/quickstart.gs +++ b/drive/activity-v2/quickstart.gs @@ -28,10 +28,10 @@ function listDriveActivity() { const response = DriveActivity.Activity.query(request); const activities = response.activities; if (!activities || activities.length === 0) { - Logger.log('No activity.'); + console.log('No activity.'); return; } - Logger.log('Recent activity:'); + console.log('Recent activity:'); for (const activity of activities) { // get time information of activity. const time = getTimeInfo(activity); @@ -42,11 +42,11 @@ function listDriveActivity() { // get target information of activity. const targets = activity.targets.map(getTargetInfo); // print the time,actor,action and targets of drive activity. - Logger.log('%s: %s, %s, %s', time, actors, action, targets); + console.log('%s: %s, %s, %s', time, actors, action, targets); } } catch (err) { // TODO (developer) - Handle error from drive activity API - Logger.log('Failed with an error %s', err.message); + console.log('Failed with an error %s', err.message); } } diff --git a/drive/activity/quickstart.gs b/drive/activity/quickstart.gs index a2ddd354a..c3fbf0fed 100644 --- a/drive/activity/quickstart.gs +++ b/drive/activity/quickstart.gs @@ -26,7 +26,7 @@ function listActivity() { var response = AppsActivity.Activities.list(optionalArgs); var activities = response.activities; if (activities && activities.length > 0) { - Logger.log('Recent activity:'); + console.log('Recent activity:'); for (i = 0; i < activities.length; i++) { var activity = activities[i]; var event = activity.combinedEvent; @@ -36,12 +36,12 @@ function listActivity() { continue; } else { var time = new Date(Number(event.eventTimeMillis)); - Logger.log('%s: %s, %s, %s (%s)', time, user.name, + console.log('%s: %s, %s, %s (%s)', time, user.name, event.primaryEventType, target.name, target.mimeType); } } } else { - Logger.log('No recent activity'); + console.log('No recent activity'); } } // [END drive_activity_quickstart] diff --git a/drive/quickstart/quickstart.gs b/drive/quickstart/quickstart.gs index 48f727f05..47087ec83 100644 --- a/drive/quickstart/quickstart.gs +++ b/drive/quickstart/quickstart.gs @@ -26,11 +26,11 @@ function listFiles() { }).items; // Print the title and id of files available in drive for (const file of files) { - Logger.log('%s (%s)', file.title, file.id); + console.log('%s (%s)', file.title, file.id); } } catch (err) { // TODO(developer)-Handle Files.list() exception - Logger.log('failed with error %s', err.message); + console.log('failed with error %s', err.message); } } // [END drive_quickstart] diff --git a/forms-api/demos/AppsScriptFormsAPIWebApp/FormsAPI.gs b/forms-api/demos/AppsScriptFormsAPIWebApp/FormsAPI.gs index 87c170caf..5be743b4e 100644 --- a/forms-api/demos/AppsScriptFormsAPIWebApp/FormsAPI.gs +++ b/forms-api/demos/AppsScriptFormsAPIWebApp/FormsAPI.gs @@ -13,7 +13,7 @@ // limitations under the License. // Global constants. Customize as needed. -const formsAPIUrl = 'https://forms.googleapis.com/v1beta/forms/'; +const formsAPIUrl = 'https://forms.googleapis.com/v1/forms/'; const formId = ''; const topicName = 'projects/'; @@ -22,7 +22,7 @@ const topicName = 'projects/'; /** * Forms API Method: forms.create - * POST https://forms.googleapis.com/v1beta/forms + * POST https://forms.googleapis.com/v1/forms */ function create(title) { const accessToken = ScriptApp.getOAuthToken(); @@ -41,16 +41,16 @@ function create(title) { 'payload': jsonTitle }; - Logger.log('Forms API POST options was: ' + JSON.stringify(options)); + console.log('Forms API POST options was: ' + JSON.stringify(options)); let response = UrlFetchApp.fetch(formsAPIUrl, options); - Logger.log('Response from Forms API was: ' + JSON.stringify(response)); + console.log('Response from Forms API was: ' + JSON.stringify(response)); return ('' + response); } /** * Forms API Method: forms.get - * GET https://forms.googleapis.com/v1beta/forms/{formId}/responses/{responseId} + * GET https://forms.googleapis.com/v1/forms/{formId}/responses/{responseId} */ function get(formId) { const accessToken = ScriptApp.getOAuthToken(); @@ -65,10 +65,10 @@ function get(formId) { try { let response = UrlFetchApp.fetch(formsAPIUrl + formId, options); - Logger.log('Response from Forms API was: ' + response); + console.log('Response from Forms API was: ' + response); return ('' + response); } catch (e) { - Logger.log(JSON.stringify(e)); + console.log(JSON.stringify(e)); return ('Error:' + JSON.stringify(e) + '

Unable to find Form with formId:
' + formId); } @@ -76,7 +76,7 @@ function get(formId) { /** * Forms API Method: forms.batchUpdate - * POST https://forms.googleapis.com/v1beta/forms/{formId}:batchUpdate + * POST https://forms.googleapis.com/v1/forms/{formId}:batchUpdate */ function batchUpdate(formId) { const accessToken = ScriptApp.getOAuthToken(); @@ -105,13 +105,13 @@ function batchUpdate(formId) { let response = UrlFetchApp.fetch(formsAPIUrl + formId + ':batchUpdate', options); - Logger.log('Response code from API: ' + response.getResponseCode()); + console.log('Response code from API: ' + response.getResponseCode()); return (response.getResponseCode()); } /** * Forms API Method: forms.responses.get - * GET https://forms.googleapis.com/v1beta/forms/{formId}/responses/{responseId} + * GET https://forms.googleapis.com/v1/forms/{formId}/responses/{responseId} */ function responsesGet(formId, responseId) { const accessToken = ScriptApp.getOAuthToken(); @@ -127,17 +127,17 @@ function responsesGet(formId, responseId) { try { var response = UrlFetchApp.fetch(formsAPIUrl + formId + '/' + 'responses/' + responseId, options); - Logger.log('Response from Forms.responses.get was: ' + response); + console.log('Response from Forms.responses.get was: ' + response); return ('' + response); } catch (e) { - Logger.log(JSON.stringify(e)); + console.log(JSON.stringify(e)); return ('Error:' + JSON.stringify(e)) } } /** * Forms API Method: forms.responses.list - * GET https://forms.googleapis.com/v1beta/forms/{formId}/responses + * GET https://forms.googleapis.com/v1/forms/{formId}/responses */ function responsesList(formId) { const accessToken = ScriptApp.getOAuthToken(); @@ -153,17 +153,17 @@ function responsesList(formId) { try { var response = UrlFetchApp.fetch(formsAPIUrl + formId + '/' + 'responses', options); - Logger.log('Response from Forms.responses was: ' + response); + console.log('Response from Forms.responses was: ' + response); return ('' + response); } catch (e) { - Logger.log(JSON.stringify(e)); + console.log(JSON.stringify(e)); return ('Error:' + JSON.stringify(e)) } } /** * Forms API Method: forms.watches.create - * POST https://forms.googleapis.com/v1beta/forms/{formId}/watches + * POST https://forms.googleapis.com/v1/forms/{formId}/watches */ function createWatch(formId) { let accessToken = ScriptApp.getOAuthToken(); @@ -178,7 +178,7 @@ function createWatch(formId) { 'eventType': 'RESPONSES', } }; - Logger.log('myWatch is: ' + JSON.stringify(myWatch)); + console.log('myWatch is: ' + JSON.stringify(myWatch)); var options = { 'headers': { @@ -189,23 +189,23 @@ function createWatch(formId) { 'payload': JSON.stringify(myWatch), 'muteHttpExceptions': false, }; - Logger.log('options are: ' + JSON.stringify(options)); - Logger.log('formsAPIURL was: ' + formsAPIUrl); + console.log('options are: ' + JSON.stringify(options)); + console.log('formsAPIURL was: ' + formsAPIUrl); var response = UrlFetchApp.fetch(formsAPIUrl + formId + '/' + 'watches', options); - Logger.log(response); + console.log(response); return ('' + response); } /** * Forms API Method: forms.watches.delete - * DELETE https://forms.googleapis.com/v1beta/forms/{formId}/watches/{watchId} + * DELETE https://forms.googleapis.com/v1/forms/{formId}/watches/{watchId} */ function deleteWatch(formId, watchId) { let accessToken = ScriptApp.getOAuthToken(); - Logger.log('formsAPIUrl is: ' + formsAPIUrl); + console.log('formsAPIUrl is: ' + formsAPIUrl); var options = { 'headers': { @@ -219,10 +219,10 @@ function deleteWatch(formId, watchId) { try { var response = UrlFetchApp.fetch(formsAPIUrl + formId + '/' + 'watches/' + watchId, options); - Logger.log(response); + console.log(response); return ('' + response); } catch (e) { - Logger.log('API Error: ' + JSON.stringify(e)); + console.log('API Error: ' + JSON.stringify(e)); return (JSON.stringify(e)); } @@ -230,10 +230,10 @@ function deleteWatch(formId, watchId) { /** * Forms API Method: forms.watches.list - * GET https://forms.googleapis.com/v1beta/forms/{formId}/watches + * GET https://forms.googleapis.com/v1/forms/{formId}/watches */ function watchesList(formId) { - Logger.log('formId is: ' + formId); + console.log('formId is: ' + formId); let accessToken = ScriptApp.getOAuthToken(); var options = { 'headers': { @@ -245,17 +245,17 @@ function watchesList(formId) { try { var response = UrlFetchApp.fetch(formsAPIUrl + formId + '/' + 'watches', options); - Logger.log(response); + console.log(response); return ('' + response); } catch (e) { - Logger.log('API Error: ' + JSON.stringify(e)); + console.log('API Error: ' + JSON.stringify(e)); return (JSON.stringify(e)); } } /** * Forms API Method: forms.watches.renew - * POST https://forms.googleapis.com/v1beta/forms/{formId}/watches/{watchId}:renew + * POST https://forms.googleapis.com/v1/forms/{formId}/watches/{watchId}:renew */ function renewWatch(formId, watchId) { let accessToken = ScriptApp.getOAuthToken(); @@ -271,10 +271,10 @@ function renewWatch(formId, watchId) { try { var response = UrlFetchApp.fetch(formsAPIUrl + formId + '/' + 'watches/' + watchId + ':renew', options); - Logger.log(response); + console.log(response); return ('' + response); } catch (e) { - Logger.log('API Error: ' + JSON.stringify(e)); + console.log('API Error: ' + JSON.stringify(e)); return (JSON.stringify(e)); } -} \ No newline at end of file +} diff --git a/forms-api/demos/AppsScriptFormsAPIWebApp/Main.html b/forms-api/demos/AppsScriptFormsAPIWebApp/Main.html index 92e30905c..8612e1b37 100644 --- a/forms-api/demos/AppsScriptFormsAPIWebApp/Main.html +++ b/forms-api/demos/AppsScriptFormsAPIWebApp/Main.html @@ -1,4 +1,20 @@ + + @@ -257,7 +273,7 @@

(spec)
+ (spec)
Form title: @@ -267,7 +283,7 @@

(spec)
+ (spec)

@@ -275,7 +291,7 @@

(spec)
+ (spec)
@@ -284,7 +300,7 @@

(spec)
+ (spec)
@@ -293,7 +309,7 @@

(spec)
+ (spec)
Response id:
@@ -303,7 +319,7 @@

(spec)
+ (spec)
@@ -312,7 +328,7 @@

(spec)
+ (spec)
Watch id:
@@ -322,7 +338,7 @@

(spec)
+ (spec)
@@ -331,7 +347,7 @@

(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! Cat Emoji'; + 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 '
  • ' + topic + '
  • '; + }).join(''); + topicsHtml = '
      ' + topicsHtml + '
    '; + + // 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.

    ' + + 'Have a great day!

    ' + + 'Thanks,
    ' + + 'Course Team

    ' + + '****************************************************************

    ' + + 'Your feedback:

    ' + + 'What industry do you work in?

    ' + + industry + '

    ' + + 'How did you find out about this course?

    ' + + source + '

    ' + + 'On a scale of 1 - 5 how would you rate this course?

    ' + + rating + '

    ' + + 'What could be different to make it a 5 rating?

    ' + + productFeedback + '

    ' + + 'Any other feedback?

    ' + + otherFeedback + '

    '; + + return htmlBody; +} + +/** + * Create a draft email with the feedback + * + * @param {string} timestamp Timestamp for the form response + * @param {string} email Email address from the form response + * @param {string} emailBody The email body as an HTML string + */ +function createDraft(timestamp, email, emailBody) { + console.log('draft email create process started'); + + // create subject line + let subjectLine = 'Thanks for your course feedback! ' + timestamp; + + // create draft email + GmailApp.createDraft( + email, + subjectLine, + '', + { + htmlBody: emailBody, + } + ); +} diff --git a/solutions/automations/course-feedback-response/README.md b/solutions/automations/course-feedback-response/README.md new file mode 100644 index 000000000..5fe194863 --- /dev/null +++ b/solutions/automations/course-feedback-response/README.md @@ -0,0 +1,3 @@ +# Respond to feedback + +See [developers.google.com](https://developers.google.com/apps-script/samples/automations/course-feedback-response) for additional details. diff --git a/solutions/automations/course-feedback-response/appsscript.json b/solutions/automations/course-feedback-response/appsscript.json new file mode 100644 index 000000000..3cf1d247d --- /dev/null +++ b/solutions/automations/course-feedback-response/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/employee-certificate/.clasp.json b/solutions/automations/employee-certificate/.clasp.json new file mode 100644 index 000000000..89f032f45 --- /dev/null +++ b/solutions/automations/employee-certificate/.clasp.json @@ -0,0 +1 @@ +{"scriptId": "1f0EhMh_a2Jtq3DS96ZWeG2XviJ-XHSStB2B3mVXODPz3KyojS7nFRzV-"} diff --git a/solutions/automations/employee-certificate/Code.js b/solutions/automations/employee-certificate/Code.js new file mode 100644 index 000000000..8d2a63ad3 --- /dev/null +++ b/solutions/automations/employee-certificate/Code.js @@ -0,0 +1,131 @@ +// To learn how to use this script, refer to the documentation: +// https://developers.google.com/apps-script/samples/automations/employee-certificate + +/* +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 slideTemplateId = 'PRESENTATION_ID'; +const tempFolderId = 'FOLDER_ID'; // Create an empty folder in Google Drive + +/** + * Creates a custom menu "Appreciation" in the spreadsheet + * with drop-down options to create and send certificates + */ +function onOpen() { + const ui = SpreadsheetApp.getUi(); + ui.createMenu('Appreciation') + .addItem('Create certificates', 'createCertificates') + .addSeparator() + .addItem('Send certificates', 'sendCertificates') + .addToUi(); +} + +/** + * Creates a personalized certificate for each employee + * and stores every individual Slides doc on Google Drive + */ +function createCertificates() { + // Load the Google Slide template file + const template = DriveApp.getFileById(slideTemplateId); + + // Get all employee data from the spreadsheet and identify the headers + const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); + const values = sheet.getDataRange().getValues(); + const headers = values[0]; + const empNameIndex = headers.indexOf('Employee Name'); + const dateIndex = headers.indexOf('Date'); + const managerNameIndex = headers.indexOf('Manager Name'); + const titleIndex = headers.indexOf('Title'); + const compNameIndex = headers.indexOf('Company Name'); + const empEmailIndex = headers.indexOf('Employee Email'); + const empSlideIndex = headers.indexOf('Employee Slide'); + const statusIndex = headers.indexOf('Status'); + + // Iterate through each row to capture individual details + for (let i = 1; i < values.length; i++) { + const rowData = values[i]; + const empName = rowData[empNameIndex]; + const date = rowData[dateIndex]; + const managerName = rowData[managerNameIndex]; + const title = rowData[titleIndex]; + const compName = rowData[compNameIndex]; + + // Make a copy of the Slide template and rename it with employee name + const tempFolder = DriveApp.getFolderById(tempFolderId); + const empSlideId = template.makeCopy(tempFolder).setName(empName).getId(); + const empSlide = SlidesApp.openById(empSlideId).getSlides()[0]; + + // Replace placeholder values with actual employee related details + empSlide.replaceAllText('Employee Name', empName); + empSlide.replaceAllText('Date', 'Date: ' + Utilities.formatDate(date, Session.getScriptTimeZone(), 'MMMM dd, yyyy')); + empSlide.replaceAllText('Your Name', managerName); + empSlide.replaceAllText('Title', title); + empSlide.replaceAllText('Company Name', compName); + + // Update the spreadsheet with the new Slide Id and status + sheet.getRange(i + 1, empSlideIndex + 1).setValue(empSlideId); + sheet.getRange(i + 1, statusIndex + 1).setValue('CREATED'); + SpreadsheetApp.flush(); + } +} + +/** + * Send an email to each individual employee + * with a PDF attachment of their appreciation certificate + */ +function sendCertificates() { + // Get all employee data from the spreadsheet and identify the headers + const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); + const values = sheet.getDataRange().getValues(); + const headers = values[0]; + const empNameIndex = headers.indexOf('Employee Name'); + const dateIndex = headers.indexOf('Date'); + const managerNameIndex = headers.indexOf('Manager Name'); + const titleIndex = headers.indexOf('Title'); + const compNameIndex = headers.indexOf('Company Name'); + const empEmailIndex = headers.indexOf('Employee Email'); + const empSlideIndex = headers.indexOf('Employee Slide'); + const statusIndex = headers.indexOf('Status'); + + // Iterate through each row to capture individual details + for (let i = 1; i < values.length; i++) { + const rowData = values[i]; + const empName = rowData[empNameIndex]; + const date = rowData[dateIndex]; + const managerName = rowData[managerNameIndex]; + const title = rowData[titleIndex]; + const compName = rowData[compNameIndex]; + const empSlideId = rowData[empSlideIndex]; + const empEmail = rowData[empEmailIndex]; + + // Load the employee's personalized Google Slide file + const attachment = DriveApp.getFileById(empSlideId); + + // Setup the required parameters and send them the email + const senderName = 'CertBot'; + const subject = empName + ', you\'re awesome!'; + const body = 'Please find your employee appreciation certificate attached.' + + '\n\n' + compName + ' team'; + GmailApp.sendEmail(empEmail, subject, body, { + attachments: [attachment.getAs(MimeType.PDF)], + name: senderName + }); + + // Update the spreadsheet with email status + sheet.getRange(i + 1, statusIndex + 1).setValue('SENT'); + SpreadsheetApp.flush(); + } +} diff --git a/solutions/automations/employee-certificate/README.md b/solutions/automations/employee-certificate/README.md new file mode 100644 index 000000000..0b5bd18c7 --- /dev/null +++ b/solutions/automations/employee-certificate/README.md @@ -0,0 +1,3 @@ +# Send personalized appreciation certificates to employees + +See [developers.google.com](https://developers.google.com/apps-script/samples/automations/employee-certificate) for additional details. diff --git a/solutions/automations/employee-certificate/appsscript.json b/solutions/automations/employee-certificate/appsscript.json new file mode 100644 index 000000000..3cf1d247d --- /dev/null +++ b/solutions/automations/employee-certificate/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/equipment-requests/.clasp.json b/solutions/automations/equipment-requests/.clasp.json new file mode 100644 index 000000000..a4c52c62a --- /dev/null +++ b/solutions/automations/equipment-requests/.clasp.json @@ -0,0 +1 @@ +{"scriptId": "1T0G2Qr0QkHfqOK8dqjdiMRGuX2UVzkQU3BGfl2lC3wsNwkSmISbp2q6t"} diff --git a/solutions/automations/equipment-requests/Code.js b/solutions/automations/equipment-requests/Code.js new file mode 100644 index 000000000..528bb4c5c --- /dev/null +++ b/solutions/automations/equipment-requests/Code.js @@ -0,0 +1,212 @@ +// To learn how to use this script, refer to the documentation: +// https://developers.google.com/apps-script/samples/automations/equipment-requests + +/* +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. +*/ + +// Update this variable with the email address you want to send equipment requests to. +const REQUEST_NOTIFICATION_EMAIL = 'request_intake@example.com'; + +// Update the following variables with your own equipment options. +const AVAILABLE_LAPTOPS = [ + '15" high Performance Laptop (OS X)', + '15" high Performance Laptop (Windows)', + '15" high performance Laptop (Linux)', + '13" lightweight laptop (Windows)', +]; +const AVAILABLE_DESKTOPS = [ + 'Standard workstation (Windows)', + 'Standard workstation (Linux)', + 'High performance workstation (Windows)', + 'High performance workstation (Linux)', + 'Mac Pro (OS X)', +]; +const AVAILABLE_MONITORS = [ + 'Single 27"', + 'Single 32"', + 'Dual 24"', +]; + +// Form field titles, used for creating the form and as keys when handling +// responses. +/** + * Adds a custom menu to the spreadsheet. + */ +function onOpen() { + SpreadsheetApp.getUi().createMenu('Equipment requests') + .addItem('Set up', 'setup_') + .addItem('Clean up', 'cleanup_') + .addToUi(); +} + +/** + * Creates the form and triggers for the workflow. + */ +function setup_() { + 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('Equipment Requests') + .setCollectEmail(true) + .setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId()) + .setLimitOneResponsePerUser(false); + form.addTextItem().setTitle('Employee name').setRequired(true); + form.addTextItem().setTitle('Desk location').setRequired(true); + form.addDateItem().setTitle('Due date').setRequired(true); + form.addListItem().setTitle('Laptop').setChoiceValues(AVAILABLE_LAPTOPS); + form.addListItem().setTitle('Desktop').setChoiceValues(AVAILABLE_DESKTOPS); + form.addListItem().setTitle('Monitor').setChoiceValues(AVAILABLE_MONITORS); + + // Hide the raw form responses. + ss.getSheets().forEach(function(sheet) { + if (sheet.getFormUrl() == ss.getFormUrl()) { + sheet.hideSheet(); + } + }); + // Start workflow on each form submit + ScriptApp.newTrigger('onFormSubmit_') + .forForm(form) + .onFormSubmit() + .create(); + // Archive completed items every 5m. + ScriptApp.newTrigger('processCompletedItems_') + .timeBased() + .everyMinutes(5) + .create(); +} + +/** + * Cleans up the project (stop triggers, form submission, etc.) + */ +function cleanup_() { + let formUrl = SpreadsheetApp.getActiveSpreadsheet().getFormUrl(); + if (!formUrl) { + return; + } + ScriptApp.getProjectTriggers().forEach(function(trigger) { + ScriptApp.deleteTrigger(trigger); + }); + FormApp.openByUrl(formUrl) + .deleteAllResponses() + .setAcceptingResponses(false); +} + +/** + * Handles new form submissions to trigger the workflow. + * + * @param {Object} event - Form submit event + */ +function onFormSubmit_(event) { + let response = mapResponse_(event.response); + sendNewEquipmentRequestEmail_(response); + let equipmentDetails = Utilities.formatString('%s\n%s\n%s', + response['Laptop'], + response['Desktop'], + response['Monitor']); + let row = ['New', + '', + response['Due date'], + response['Employee name'], + response['Desk location'], + equipmentDetails, + response['email']]; + let ss = SpreadsheetApp.getActiveSpreadsheet(); + let sheet = ss.getSheetByName('Pending requests'); + sheet.appendRow(row); +} + +/** + * Sweeps completed and cancelled requests, notifying the requestors and archiving them + * to the completed sheet. + * + * @param {Object} event + */ +function processCompletedItems_() { + let ss = SpreadsheetApp.getActiveSpreadsheet(); + let pending = ss.getSheetByName('Pending requests'); + let completed = ss.getSheetByName('Completed requests'); + let rows = pending.getDataRange().getValues(); + for (let i = rows.length; i >= 2; i--) { + let row = rows[i -1]; + let status = row[0]; + if (status === 'Completed' || status == 'Cancelled') { + pending.deleteRow(i); + completed.appendRow(row); + console.log("Deleted row: " + i); + sendEquipmentRequestCompletedEmail_({ + 'Employee name': row[3], + 'Desk location': row[4], + 'email': row[6], + }); + } + }; +} + +/** + * Sends an email notification that a new equipment request has been submitted. + * + * @param {Object} request - Request details + */ +function sendNewEquipmentRequestEmail_(request) { + let template = HtmlService.createTemplateFromFile('new-equipment-request.html'); + template.request = request; + template.sheetUrl = SpreadsheetApp.getActiveSpreadsheet().getUrl(); + let msg = template.evaluate(); + MailApp.sendEmail({ + to: REQUEST_NOTIFICATION_EMAIL, + subject: 'New equipment request', + htmlBody: msg.getContent(), + }); +} + +/** + * Sends an email notifying the requestor that the request is complete. + * + * @param {Object} request - Request details + */ +function sendEquipmentRequestCompletedEmail_(request) { + let template = HtmlService.createTemplateFromFile('request-complete.html'); + template.request = request; + let msg = template.evaluate(); + MailApp.sendEmail({ + to: request.email, + subject: 'Equipment request completed', + htmlBody: msg.getContent(), + }); +} + +/** + * 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 mapResponse_(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); +} + diff --git a/solutions/automations/equipment-requests/README.md b/solutions/automations/equipment-requests/README.md new file mode 100644 index 000000000..b6e5d1009 --- /dev/null +++ b/solutions/automations/equipment-requests/README.md @@ -0,0 +1,3 @@ +# Manage new employee equipment requests + +See [developers.google.com](https://developers.google.com/apps-script/samples/automations/equipment-requests) for additional details. diff --git a/solutions/automations/equipment-requests/appsscript.json b/solutions/automations/equipment-requests/appsscript.json new file mode 100644 index 000000000..3cf1d247d --- /dev/null +++ b/solutions/automations/equipment-requests/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/equipment-requests/new-equipment-request.html b/solutions/automations/equipment-requests/new-equipment-request.html new file mode 100644 index 000000000..db2363517 --- /dev/null +++ b/solutions/automations/equipment-requests/new-equipment-request.html @@ -0,0 +1,35 @@ + + + + + +

    + A new equipment request has been made by . +

    + +

    + Employee name:
    + Desk location name:
    + Due date:
    + Laptop model:
    + Desktop model:
    + Monitor(s):
    +

    + + 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 @@ + + + + + +

    + An equipment request has been completed. +

    + +

    + Employee name:
    + Desk location name:
    +

    + + 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,

    You have new comments and/or replies on videos:

    + + + + + + + + + + + + + +
    Video TitleLinkNumber of new replies and comments
    + + + 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.

    Created by OOO Chat app!', + restrictToContacts: true, + restrictToDomain: true, + startTime: currentTime, + endTime: currentTime + ONE_DAY_MILLIS + }, 'me'); +} + +function createResponseCard(responseText) { + return { + "cardsV2": [ + { + "cardId": "1", + "card": { + "sections": [ + { + "widgets": [ + { + "decoratedText": { + "topLabel": "", + "text": responseText, + "startIcon": { + "knownIcon": "NONE", + "altText": "Task done", + "iconUrl": "https://fonts.gstatic.com/s/i/short-term/web/system/1x/task_alt_gm_grey_48dp.png" + }, + "wrapText": true + } + } + ] + } + ], + "header": { + "title": "OOO app", + "subtitle": "Helping you manage your OOO", + "imageUrl": "https://goo.gle/3SfMkjb", + "imageType": "CIRCLE" + } + } + } + ] + } +} + diff --git a/solutions/ooo-chat-app/README.md b/solutions/ooo-chat-app/README.md new file mode 100644 index 000000000..4d72f861a --- /dev/null +++ b/solutions/ooo-chat-app/README.md @@ -0,0 +1,5 @@ +# OOO Chat App + +Sample code for a custom Google Chat app that manages your out of office tasks. + +Learn more about [Chat apps](https://developers.google.com/chat). diff --git a/solutions/ooo-chat-app/appsscript.json b/solutions/ooo-chat-app/appsscript.json new file mode 100644 index 000000000..de9fa0b7b --- /dev/null +++ b/solutions/ooo-chat-app/appsscript.json @@ -0,0 +1,20 @@ +{ + "timeZone": "Europe/Madrid", + "exceptionLogging": "STACKDRIVER", + "runtimeVersion": "V8", + "dependencies": { + "enabledAdvancedServices": [ + { + "userSymbol": "Gmail", + "version": "v1", + "serviceId": "gmail" + }, + { + "userSymbol": "Calendar", + "version": "v3", + "serviceId": "calendar" + } + ] + }, + "chat": {} +} \ No newline at end of file diff --git a/tasks/quickstart/quickstart.gs b/tasks/quickstart/quickstart.gs index 2aba53579..fae31d265 100644 --- a/tasks/quickstart/quickstart.gs +++ b/tasks/quickstart/quickstart.gs @@ -28,15 +28,15 @@ function listTaskLists() { const taskLists = response.items; // Print task list of user if available. if (!taskLists || taskLists.length === 0) { - Logger.log('No task lists found.'); + console.log('No task lists found.'); return; } for (const taskList of taskLists) { - Logger.log('%s (%s)', taskList.title, taskList.id); + console.log('%s (%s)', taskList.title, taskList.id); } } catch (err) { // TODO (developer) - Handle exception from Task API - Logger.log('Failed with error %s', err.message); + console.log('Failed with error %s', err.message); } } // [END tasks_quickstart] diff --git a/tasks/simpleTasks/javascript.html b/tasks/simpleTasks/javascript.html index 7f057bacc..5331918ce 100644 --- a/tasks/simpleTasks/javascript.html +++ b/tasks/simpleTasks/javascript.html @@ -1,3 +1,19 @@ + + diff --git a/tasks/simpleTasks/page.html b/tasks/simpleTasks/page.html index 1322b3072..f5f9f677a 100644 --- a/tasks/simpleTasks/page.html +++ b/tasks/simpleTasks/page.html @@ -1,4 +1,20 @@ + + diff --git a/tasks/simpleTasks/stylesheet.html b/tasks/simpleTasks/stylesheet.html index 76f0567ab..02c35c0d0 100644 --- a/tasks/simpleTasks/stylesheet.html +++ b/tasks/simpleTasks/stylesheet.html @@ -1,3 +1,19 @@ + + diff --git a/templates/sheets-import/intercom.js.html b/templates/sheets-import/intercom.js.html index 1154c4048..c8fcde5cb 100644 --- a/templates/sheets-import/intercom.js.html +++ b/templates/sheets-import/intercom.js.html @@ -1,3 +1,19 @@ + +