快速入門導覽課程:使用 Google Apps Script 建構計算機步驟

本快速入門導覽課程說明如何使用 Google Apps Script,為 Workspace Flows 建立自訂步驟。這個自訂步驟會接收兩個數字和一個算術運算做為輸入內容,執行計算並輸出結果。

使用者在流程中設定計算機步驟。

圖 1:使用者在流程中設定計算機步驟。

目標

  • 使用 Google Apps Script 為 Workspace Flows 建立自訂步驟。
  • 將自訂步驟部署至您自己的 Google Workspace 機構。
  • 在 Workspace Flows 中測試自訂流程步驟。

必要條件

設定指令碼

如要設定指令碼,請建立新的 Apps Script 專案,然後連結至 Cloud 專案。

  1. 按一下下列按鈕,開啟流程計算機快速入門 Apps Script 專案。

    開啟專案

  2. 按一下「總覽」

  3. 在總覽頁面中,按一下 建立副本的圖示「建立副本」

  4. 為複製的 Apps Script 專案命名:

    1. 按一下「Copy of Flows calculator quickstart」(流程計算機快速入門導覽課程副本)。

    2. 在「專案標題」中輸入 Flows calculator quickstart

    3. 按一下 [重新命名]

選用:查看快速入門程式碼

在上一節中,您已複製整個 Apps Script 專案,其中包含流程自訂步驟的所有必要應用程式程式碼,因此不必複製及貼上每個檔案。

您也可以在這裡查看先前複製的每個檔案:

appsscript.json

資訊清單檔案。這個特殊的 JSON 檔案會指定 Apps Script 執行指令碼時所需的基本專案資訊。

查看 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"
                }
              },
              {
                "id": "log",
                "description": "Logged result of flow event.",
                "cardinality": "SINGLE",
                "dataType": {
                  "basicType": "STRING"
                }
              }
            ],
            "onConfigFunction": "onConfigCalculateFunction",
            "onExecuteFunction": "onExecuteCalculateFunction"
          }
        }
      ]
    }
  }
}
Calculator.gs

定義 Google Workspace Flows 的自訂步驟。這個步驟名為「Calculate」,會將兩個數字和一項運算做為輸入內容,並傳回計算結果。

查看 Calculator.gs 程式碼

/**
 * This script defines a custom step for Google Workspace Flows.
 * 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/workflows/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 workflow.
 *
 * This function generates a button definition that, when clicked, triggers
 * a save action for the current workflow 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 workflow.
 *
 * The input fields are configured to let the user select outputs from previous
 * workflow steps as input values using the `hostAppDataSource` property.
 * This function is called when the user adds or edits the "Calculate" step in the Flows 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];
}

/**
 * Executes the calculation action based on the inputs from a workflow event.
 *
 * This function retrieves input values ("value1", "value2") and the "operation"
 * from the workflow event, performs the calculation, and returns the "result" and
 * "log" as output variables.
 * This function is called when the workflow execution reaches this custom step.
 * @param {Object} event The event object passed by the Flows runtime.
 * @return {Object} The output variables object.
 */
function onExecuteCalculateFunction(event) {
  console.log("output: " + JSON.stringify(event));
  var calculatedValue = 0;
  var value1 = getIntValue(event.workflow.actionInvocation.inputs["value1"]);
  var value2 = getIntValue(event.workflow.actionInvocation.inputs["value2"]);
  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;
  }
  var renderAction = {
    "hostAppAction" : {
      "workflowAction" : {
        "returnOutputVariablesAction" : {
          "variableValues" : [
            {
              "variableId": "result",
              "integerValues": [
                calculatedValue
              ]
            }
          ]
        }
      }
    }
  };
}

部署及測試步驟

如要測試步驟,請為外掛程式設定測試部署作業,將步驟新增至流程,然後執行流程。

  1. 為外掛程式設定測試部署作業:

    1. 在 Apps Script 編輯器中開啟指令碼專案。
    2. 依序點選「部署」>「測試部署作業」
    3. 按一下 [安裝]
    4. 按一下底部的「完成」

    您可以與其他使用者的帳戶共用 Apps Script 專案 (必須具備編輯權限),讓他們測試外掛程式。然後提示使用者按照先前的步驟操作。

    安裝完畢後,外掛程式會立即顯示在 Flows 中。您可能需要重新整理 Flows,外掛程式才會顯示。您也必須先授權外掛程式,才能使用。

    如要進一步瞭解測試部署,請參閱「安裝未發布的外掛程式」。

  2. 開啟「流程」。

  3. 建立包含步驟的流程:

    1. 按一下 「新流程」
    2. 選取流程的啟動方式。測試步驟時,請選擇可自行觸發的啟動條件,例如傳送電子郵件給自己。如果步驟需要輸入變數,請將輸入變數設定為啟動器的輸出內容。
    3. 按一下「新增步驟」。選取您建立或更新的步驟,稱為「計算」
    4. 設定步驟。在計算步驟中,選擇兩個值和數學運算。系統會自動儲存步驟。
    5. 如要測試步驟的輸出內容,請新增另一個步驟。舉例來說,如要在電子郵件中新增輸出內容,可以新增 Gmail 的「傳送郵件」步驟。在「訊息」中,按一下「變數」,然後選取步驟的輸出內容。在計算步驟中,依序選取「變數」 >「步驟 2:計算結果」 >「計算結果」。變數會以方塊形式顯示在「訊息」欄位中。
    6. 按一下「開啟」。流程已可執行。
  4. 如要執行流程,請啟動流程的啟動條件。舉例來說,如果流程會在收到電子郵件時啟動,請傳送電子郵件給自己。

  5. 確認流程是否正常運作。前往流程建構工具的「活動」分頁,即可查看記錄。如要瞭解如何在「活動」分頁中建立自訂記錄,請參閱活動記錄

後續步驟

您已成功建立及測試 Workspace Flows 的自訂流程步驟。您現在可以進行下列操作: