Быстрый старт: как создать шаг калькулятора с помощью Google Apps Script

В этом кратком руководстве рассказывается, как создать собственный шаг для Workspace Studio с помощью Google Apps Script. Пользовательский шаг принимает на входе два числа и арифметическую операцию, выполняет вычисление и выводит результат.

Карточка этапа калькулятора Workspace Studio, на которой показаны два поля ввода чисел и раскрывающееся меню арифметических операций.
Рисунок 1. Пользователь настраивает шаг калькулятора в рамках процесса.

Цели

  • Создайте собственный шаг для Workspace Studio с помощью Google Apps Script.
  • Разверните пользовательский шаг в организации Google Workspace.
  • Протестируйте настраиваемый шаг в Workspace Studio.

Требования

  • Аккаунт Google с доступом к Workspace Studio.

Как настроить скрипт

Чтобы настроить скрипт, создайте новый проект Apps Script и добавьте код быстрого запуска:

  1. Чтобы создать проект Apps Script, нажмите кнопку ниже.

    Создайте проект

  2. Укажите название проекта Apps Script:

    1. Нажмите Проект без названия.

    2. В поле Project title (Название проекта) введите Calculator quickstart.

    3. Нажмите Переименовать.

  3. Рядом с файлом Code.gs нажмите на значок "Ещё" > Переименовать. Назовите файл Calculator.

  4. Замените содержимое файла Calculator.gs следующим кодом: Этот файл определяет настраиваемый шаг для Google Workspace Studio под названием "Вычислить", который принимает два числа и операцию в качестве входных данных и возвращает результат вычисления.

    Посмотреть код Calculator.gs

    /**
     * This script defines a custom step for Google Workspace Studio.
     * The step, named "Calculate", takes two numbers and an operation as input
     * and returns the result of the calculation.
     *
     * The script includes functions to:
     *
     * 1.  Define the configuration UI for the step using Card objects:
     *
     *     - `onConfigCalculateFunction()`: Generates the main configuration card.
     *     - Helper functions like `pushCard()`, `saveButton()` to build card components.
     *
     * 2.  Handle the execution of the step.
     *
     *     - `onExecuteCalculateFunction()`: Retrieves inputs, performs the calculation,
     *       and returns outputs.
     *
     * To learn more, see the following quickstart guide:
     * https://developers.google.com/workspace/add-ons/studio/quickstart
     */
    
    /**
     * Creates an action response to push a new card onto the card stack.
     *
     * This function generates an action object that, when returned, causes the
     * provided card to be pushed onto the card stack, making it the currently
     * displayed card in the configuration UI.
     * @param {Object} card The Card object to push.
     * @return {Object} The action response object.
     */
    function pushCard(card) {
      return {
    
          "action": {
            "navigations": [{
                "push_card": card
              }
            ]
          }  };  
    }
    
    /**
     * Creates an action response to update the currently displayed card.
     *
     * This function generates an action object that, when returned, causes the
     * currently displayed card to be replaced with the provided card in the
     * configuration UI.
     * @param {Object} card The Card object to update.
     * @return {Object} The render actions object.
     */
    function updateCard(card) {
      return {
        "render_actions": {
          "action": {
            "navigations": [{
                "update_card": card
              }
            ]
          }
        }
      };
    }
    
    /**
     * Creates a button configuration object for saving the step.
     *
     * This function generates a button definition that, when clicked, triggers
     * a save action for the current step configuration.
     * @return {Object} The button widget object.
     */
    function saveButton() {
      return {
          "text": "Save",
          "onClick": {
            "hostAppAction" : {
              "workflowAction" : {
                "saveWorkflowAction" : {}
              }
            }
          },
        };
    }
    
    /**
     * Creates a button configuration object for a refresh action.
     *
     * This function generates a button definition that, when clicked, triggers
     * a function to refresh the current card.
     * @param {string} functionName The name of the Apps Script function to call on click.
     * @return {Object} The button widget object.
     */
    function refreshButton(functionName) {
      return {
          "text": "Refresh",
          "onClick": {
            "action" : {
              "function" : functionName
            }
          },
        };
    }
    
    
    /**
     * Generates and displays a configuration card for the sample calculation action.
     *
     * This function creates a card with input fields for two values and a dropdown
     * for selecting an arithmetic operation. The card also includes a "Save"
     * button to save the action configuration for the step.
     *
     * The input fields are configured to let the user select outputs from previous
     * steps as input values using the `hostAppDataSource` property.
     * This function is called when the user adds or edits the "Calculate" step in the UI.
     * @return {Object} The action response object containing the card to display.
     */
    function onConfigCalculateFunction() {
      var card = {
        "sections": [
          {
            "header": "Action sample: Calculate",
            "widgets": [
              {
                "textInput": {
                  "name": "value1",
                  "label": "First value",
                  "hostAppDataSource" : {
                    "workflowDataSource" : {
                      "includeVariables" : true
                    }
                  }
                }
              },
              {
                "selectionInput": {
                  "name": "operation",
                  "label": "Operation",
                  "type": "DROPDOWN",
                  "items": [
                    {
                      "text": "+",
                      "value": "+",
                    },
                    {
                      "text": "-",
                      "value": "-",
                    },
                    {
                      "text": "x",
                      "value": "x",
                    },
                    {
                      "text": "/",
                      "value": "/",
                    }
                  ]
                }
              },
              {
                "textInput": {
                  "name": "value2",
                  "label": "Second value",
                  "hostAppDataSource" : {
                    "workflowDataSource" : {
                      "includeVariables" : true
                    }
                  }
                }
              }
            ]
          }
        ]
      };
      return pushCard(card);
    }
    
    /**
     * Gets an integer value from variable data, handling both string and integer formats.
     *
     * This function attempts to extract an integer value from the provided variable data.
     * It checks if the data contains string values and, if so, parses the first string
     * as an integer. If integer values are present, it returns the first integer.
     * @param {Object} variableData The variable data object from the event.
     * @return {number} The extracted integer value.
     */
    function getIntValue(variableData) {
      if (variableData.stringValues) {
        return parseInt(variableData.stringValues[0]);
      }
      return variableData.integerValues[0];
    }
    
    /**
    * Returns output variables from a step.
    *
    * This function constructs an object that, when returned, sends the
    * provided variable values as output from the current step.
    * The variable values are logged to the console for debugging purposes.
    */
    function outputVariables(variableDataMap) {
     const workflowAction = AddOnsResponseService.newReturnOutputVariablesAction()
       .setVariableDataMap(variableDataMap);
    
     const hostAppAction = AddOnsResponseService.newHostAppAction()
       .setWorkflowAction(workflowAction);
    
     const renderAction = AddOnsResponseService.newRenderActionBuilder()
       .setHostAppAction(hostAppAction)
       .build();
    
     return renderAction;
    }
    
    /**
     * Executes the calculation action based on the inputs from an event.
     *
     * This function retrieves input values ("value1", "value2") and the "operation"
     * from the event, performs the calculation, and returns the "result" and
     * "log" as output variables.
     * This function is called when the flow reaches this custom step.
     * @param {Object} event The event object passed by the runtime.
     * @return {Object} The output variables object.
     */
    function onExecuteCalculateFunction(event) {
     console.log("output: " + JSON.stringify(event));
     var calculatedValue = 0;
     var value1 = event.workflow.actionInvocation.inputs["value1"].integerValues[0];
     var value2 = event.workflow.actionInvocation.inputs["value2"].integerValues[0];
     var operation = event.workflow.actionInvocation.inputs["operation"].stringValues[0];
    
    
     if (operation == "+") {
       calculatedValue = value1 + value2;
     } else if (operation == "-") {
       calculatedValue = value1 - value2;
     } else if (operation == "x") {
       calculatedValue = value1 * value2;
     } else if (operation == "/") {
       calculatedValue = value1 / value2;
     }
    
     const variableDataMap = { "result": AddOnsResponseService.newVariableData().addIntegerValue(calculatedValue) };
    
     return outputVariables(variableDataMap);
    }
  5. Нажмите Настройки проекта и установите флажок Показывать файл манифеста appsscript.json в редакторе.

  6. Нажмите Редактор , откройте файл манифеста appsscript.json и замените его содержимое следующим кодом:

    Посмотреть код appsscript.json

    {
      "timeZone": "America/Los_Angeles",
      "exceptionLogging": "STACKDRIVER",
      "runtimeVersion": "V8",
      "addOns": {
        "common": {
          "name": "Calculator",
          "logoUrl": "https://www.gstatic.com/images/branding/productlogos/calculator_search/v1/web-24dp/logo_calculator_search_color_1x_web_24dp.png",
          "useLocaleFromApp": true
        },
        "flows": {
          "workflowElements": [
            {
              "id": "actionElement",
              "state": "ACTIVE",
              "name": "Calculate",
              "description": "Asks the user for two values and a math operation, then performs the math operation on the values and outputs the result.",
              "workflowAction": {
                "inputs": [
                  {
                    "id": "value1",
                    "description": "value1",
                    "cardinality": "SINGLE",
                    "dataType": {
                      "basicType": "INTEGER"
                    }
                  },
                  {
                    "id": "value2",
                    "description": "value2",
                    "cardinality": "SINGLE",
                    "dataType": {
                      "basicType": "INTEGER"
                    }
                  },
                  {
                    "id": "operation",
                    "description": "operation",
                    "cardinality": "SINGLE",
                    "dataType": {
                      "basicType": "STRING"
                    }
                  }
                ],
                "outputs": [
                  {
                    "id": "result",
                    "description": "Calculated result",
                    "cardinality": "SINGLE",
                    "dataType": {
                      "basicType": "INTEGER"
                    }
                  }
                ],
                "onConfigFunction": "onConfigCalculateFunction",
                "onExecuteFunction": "onExecuteCalculateFunction"
              }
            }
          ]
        }
      }
    }
  7. Нажмите "Сохранить" .

Развертывание и тестирование шага

Чтобы протестировать шаг, настройте тестовое развертывание для дополнения, добавьте шаг в поток и запустите его.

  1. Настройте тестовое развертывание для дополнения:

    1. Откройте проект скрипта в редакторе Apps Script.
    2. Нажмите Развернуть > Тестовые развертывания.
    3. Нажмите Установить.
    4. Внизу нажмите Готово.

    Вы можете разрешить другим пользователям тестировать дополнение, предоставив им доступ к проекту Apps Script (требуются права на редактирование). Затем попросите пользователей выполнить описанные выше действия.

    После установки дополнение сразу же станет доступно в Flows. Чтобы дополнение появилось, может потребоваться обновить Flows. Прежде чем использовать дополнение, его необходимо авторизовать.

    Подробнее об установке неопубликованного дополнения…

  2. Открыть Flows

  3. Создайте поток, включающий ваш шаг:

    1. Нажмите Новый поток.
    2. Выберите, как будет запускаться поток. Если для шага требуется входная переменная, настройте ее как часть выходных данных условия запуска.
    3. Нажмите Добавить шаг. Выберите созданный или обновленный шаг Вычислить.
    4. Настройте шаг. Для шага вычисления выберите два значения и математическую операцию. Шаг сохраняется автоматически.
    5. Чтобы протестировать выходные данные шага, добавьте ещё один шаг. Например, чтобы добавить выходные данные в сообщение Google Chat, добавьте шаг Отправить уведомление в Chat. В поле Message (Сообщение) нажмите Variables (Переменные) и выберите выходные данные шага. Для шага вычисления выберите Переменные > Шаг 2. Вычисление > Результат вычисления. Переменная появится в виде чипа в поле Сообщение.
    6. Нажмите Включить. Процесс готов к запуску.
  4. Запустите поток, активировав его событие. Например, если поток запускается по расписанию, он будет выполняться в указанные дату и время.

  5. Убедитесь, что поток работает правильно. Проверьте журналы на вкладке Действия в конструкторе процессов. Подробнее о том, как создавать собственные журналы на вкладке "Действия"…

Дальнейшие действия

Вы создали и протестировали пользовательский шаг для Workspace Studio. Вы можете: