|
| 1 | +/** |
| 2 | + * Copyright Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | + |
| 18 | +/** |
| 19 | + * Creates an add-on menu, the main entry point for this add-on |
| 20 | + */ |
| 21 | +function onOpen() { |
| 22 | + SpreadsheetApp.getUi().createAddonMenu() |
| 23 | + .addItem('Login To Salesforce', 'login') |
| 24 | + .addItem('Run SOQL Query', 'promptQuery') |
| 25 | + .addSeparator() |
| 26 | + .addItem('Logout From Salesforce', 'logout') |
| 27 | + .addSeparator() |
| 28 | + .addItem('Generate Invoices', 'generateInvoices') |
| 29 | + .addItem('Generate Report', 'generateReport') |
| 30 | + .addToUi(); |
| 31 | +} |
| 32 | + |
| 33 | +/** Ensure the menu is created when the add-on is installed */ |
| 34 | +function onInstall() { |
| 35 | + onOpen(); |
| 36 | +} |
| 37 | + |
| 38 | +/** |
| 39 | + * If we dont have a Salesforce OAuth token, starts the OAuth flow with |
| 40 | + * Salesforce. |
| 41 | + */ |
| 42 | +function login() { |
| 43 | + var salesforce = getSalesforceService(); |
| 44 | + if (!salesforce.hasAccess()) { |
| 45 | + showLinkDialog(salesforce.getAuthorizationUrl(), |
| 46 | + 'Sign-in to Salesforce', 'Sign-in'); |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +/** |
| 51 | + * Displays a modal dialog with a simple HTML link that opens in a new tab. |
| 52 | + * |
| 53 | + * @param {string} url the URL to link to |
| 54 | + * @param {string} message the message to display to the user as a link |
| 55 | + * @param {string} title the title of the dialog |
| 56 | + */ |
| 57 | +function showLinkDialog(url, message, title) { |
| 58 | + var template = HtmlService.createTemplateFromFile('LinkDialog'); |
| 59 | + template.url = url; |
| 60 | + template.message = message; |
| 61 | + SpreadsheetApp.getUi().showModalDialog(template.evaluate(), title); |
| 62 | +} |
| 63 | + |
| 64 | +/** |
| 65 | + * Creates a Salesforce OAuth2 service, using the Apps Script OAuth2 library: |
| 66 | + * https://github.com/gsuitedevs/apps-script-oauth2 |
| 67 | + * |
| 68 | + * @return {Object} a Salesforce OAuth2 service |
| 69 | + */ |
| 70 | +function getSalesforceService() { |
| 71 | + return OAuth2.createService('salesforce') |
| 72 | + .setAuthorizationBaseUrl( |
| 73 | + 'https://login.salesforce.com/services/oauth2/authorize') |
| 74 | + .setTokenUrl('https://login.salesforce.com/services/oauth2/token') |
| 75 | + .setClientId(SALESFORCE_CLIENT_ID) |
| 76 | + .setClientSecret(SALESFORCE_CLIENT_SECRET) |
| 77 | + .setCallbackFunction('authCallback') |
| 78 | + .setPropertyStore(PropertiesService.getUserProperties()); |
| 79 | +} |
| 80 | + |
| 81 | +/** |
| 82 | + * Authentication callback for OAuth2: called when Salesforce redirects back to |
| 83 | + * Apps Script after sign-in. |
| 84 | + * |
| 85 | + * @param {Object} request the HTTP request, provided by Apps Script |
| 86 | + * @return {Object} HTMLOutput to render the callback as a web page |
| 87 | + */ |
| 88 | +function authCallback(request) { |
| 89 | + var salesforce = getSalesforceService(); |
| 90 | + var isAuthorized = salesforce.handleCallback(request); |
| 91 | + var message = isAuthorized ? |
| 92 | + 'Success! You can close this tab and the dialog in Sheets.' |
| 93 | + : 'Denied. You can close this tab and the dialog in Sheets.'; |
| 94 | + |
| 95 | + return HtmlService.createHtmlOutput(message); |
| 96 | +} |
| 97 | + |
| 98 | +/** |
| 99 | + * Prompts the user to enter a SOQL (Salesforce Object Query Language) query |
| 100 | + * to execute. If given, the query is run and its results are added as a new |
| 101 | + * sheet. |
| 102 | + */ |
| 103 | +function promptQuery() { |
| 104 | + var ui = SpreadsheetApp.getUi(); |
| 105 | + var response = ui.prompt('Run SOQL Query', |
| 106 | + 'Enter your query, ex: "select Id from Opportunity"', |
| 107 | + ui.ButtonSet.OK_CANCEL); |
| 108 | + var query = response.getResponseText(); |
| 109 | + if (response.getSelectedButton() === ui.Button.OK) { |
| 110 | + executeQuery(query); |
| 111 | + } |
| 112 | +} |
| 113 | + |
| 114 | +/** |
| 115 | + * Executes the given SOQL query and copies its results to a new sheet. |
| 116 | + * |
| 117 | + * @param {string} query the SOQL to execute |
| 118 | + */ |
| 119 | +function executeQuery(query) { |
| 120 | + var response = fetchSoqlResults(query); |
| 121 | + var outputSheet = SpreadsheetApp.getActive().insertSheet(); |
| 122 | + var records = response['records']; |
| 123 | + var fields = getFields(records[0]); |
| 124 | + |
| 125 | + // Builds the new sheet's contents as a 2D array that can be passed in |
| 126 | + // to setValues() at once. This gives better performance than updating |
| 127 | + // a single cell at a time. |
| 128 | + var outputValues = []; |
| 129 | + outputValues.push(fields); |
| 130 | + for (var i = 0; i < records.length; i++) { |
| 131 | + var row = []; |
| 132 | + var record = records[i]; |
| 133 | + for (var j = 0; j < fields.length; j++) { |
| 134 | + var fieldName = fields[j]; |
| 135 | + row.push(record[fieldName]); |
| 136 | + } |
| 137 | + outputValues.push(row); |
| 138 | + } |
| 139 | + |
| 140 | + outputSheet.getRange(1, 1, outputValues.length, fields.length) |
| 141 | + .setValues(outputValues); |
| 142 | +} |
| 143 | + |
| 144 | +/** |
| 145 | + * Makes an API call to Salesforce to execute a given SOQL query. |
| 146 | + * |
| 147 | + * @param {string} query the SOQL query to execute |
| 148 | + * @return {Object} the API response from Salesforce, as a parsed JSON object. |
| 149 | + */ |
| 150 | +function fetchSoqlResults(query) { |
| 151 | + var salesforce = getSalesforceService(); |
| 152 | + if (!salesforce.hasAccess()) { |
| 153 | + throw new Error('Please login first'); |
| 154 | + } else { |
| 155 | + var params = { |
| 156 | + 'headers': { |
| 157 | + 'Authorization': 'Bearer ' + salesforce.getAccessToken(), |
| 158 | + 'Content-Type': 'application/json' |
| 159 | + } |
| 160 | + }; |
| 161 | + var url = 'https://' + SALESFORCE_INSTANCE + |
| 162 | + '.salesforce.com/services/data/v30.0/query'; |
| 163 | + var response = UrlFetchApp.fetch(url + |
| 164 | + '?q=' + encodeURIComponent(query), params); |
| 165 | + return JSON.parse(response.getContentText()); |
| 166 | + } |
| 167 | +} |
| 168 | + |
| 169 | +/** |
| 170 | + * Parses the Salesforce response and extracts the list of field names in the |
| 171 | + * result set. |
| 172 | + * |
| 173 | + * @param {Object} record a single Salesforce response record |
| 174 | + * @return {Array<string>} an array of string keys of that record |
| 175 | + */ |
| 176 | +function getFields(record) { |
| 177 | + var fields = []; |
| 178 | + for (var field in record) { |
| 179 | + if (record.hasOwnProperty(field) && field !== 'attributes') { |
| 180 | + fields.push(field); |
| 181 | + } |
| 182 | + } |
| 183 | + return fields; |
| 184 | +} |
| 185 | + |
| 186 | +/** Resets the Salesforce service, removing any saved OAuth tokens. */ |
| 187 | +function logout() { |
| 188 | + getSalesforceService().reset(); |
| 189 | +} |
0 commit comments