Panduan memulai: Membangun langkah kalkulator dengan Google Apps Script

Panduan memulai ini mengajarkan cara membuat langkah kustom untuk Workspace Studio menggunakan Google Apps Script. Langkah kustom ini menggunakan dua angka dan operasi aritmetika sebagai input, melakukan penghitungan, dan menghasilkan output.

Kartu langkah kalkulator Workspace Studio yang menampilkan dua kolom input angka dan menu drop-down operasi aritmetika.
Gambar 1: Pengguna mengonfigurasi langkah kalkulator sebagai bagian dari alur.

Tujuan

  • Membuat langkah kustom untuk Workspace Studio dengan Google Apps Script.
  • Men-deploy langkah kustom ke organisasi Google Workspace Anda sendiri.
  • Uji langkah kustom di Workspace Studio.

Prasyarat

  • Akun Google dengan akses ke Workspace Studio.

Menyiapkan skrip

Untuk menyiapkan skrip, buat project Apps Script baru dan tambahkan kode panduan memulai:

  1. Klik tombol berikut untuk membuat project Apps Script baru:

    Membuat project

  2. Beri nama project Apps Script:

    1. Klik Project tanpa judul.

    2. Di Project title, ketik Calculator quickstart.

    3. Klik Ganti nama.

  3. Di samping file Code.gs, klik Lainnya > Ganti nama. Beri nama file Calculator.

  4. Ganti konten Calculator.gs dengan kode berikut. File ini menentukan langkah kustom untuk Google Workspace Studio bernama "Calculate" yang menggunakan dua angka dan satu operasi sebagai input dan menampilkan hasil penghitungan.

    Lihat kode 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. Klik Setelan project dan pilih kotak centang Show "appsscript.json" file manifes di editor.

  6. Klik Editor , buka file manifes appsscript.json, dan ganti kontennya dengan kode berikut:

    Lihat kode 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. Klik Simpan .

Men-deploy dan menguji langkah Anda

Untuk menguji langkah Anda, siapkan deployment pengujian untuk add-on Anda, tambahkan langkah ke alur, lalu jalankan alur.

  1. Siapkan deployment pengujian untuk add-on Anda:

    1. Buka project skrip di editor Apps Script.
    2. Klik Deploy > Test deployments.
    3. Klik Instal.
    4. Di bagian bawah, klik Selesai.

    Anda dapat mengizinkan pengguna lain menguji add-on dengan membagikan project Apps Script ke akun mereka (diperlukan akses edit). Kemudian, minta pengguna untuk mengikuti langkah-langkah sebelumnya.

    Setelah diinstal, add-on akan langsung tersedia di Flows. Anda mungkin perlu memuat ulang Flows sebelum add-on muncul. Anda juga harus memberikan otorisasi pada add-on sebelum menggunakannya.

    Untuk mempelajari lebih lanjut deployment pengujian, lihat Menginstal add-on yang tidak dipublikasikan.

  2. Buka Flows.

  3. Buat alur yang menyertakan langkah Anda:

    1. Klik New flow.
    2. Pilih cara alur dimulai. Jika langkah Anda memerlukan variabel input, konfigurasikan variabel input sebagai bagian dari output pemicu.
    3. Klik Tambahkan langkah. Pilih langkah yang Anda buat atau perbarui, yang disebut Calculate.
    4. Konfigurasikan langkah Anda. Untuk langkah penghitungan, pilih dua nilai dan operasi matematika. Langkah akan disimpan secara otomatis.
    5. Untuk menguji output langkah Anda, tambahkan langkah lain. Misalnya, untuk menambahkan output ke pesan Google Chat, tambahkan langkah Beri tahu saya di Chat Chat. Di Pesan, klik Variabel dan pilih output langkah Anda. Untuk langkah penghitungan, pilih Variables > Step 2: Calculate > Calculated result. Variabel akan muncul sebagai chip di kolom Pesan.
    6. Klik Aktifkan. Alur Anda siap dijalankan.
  4. Jalankan alur dengan memicu pemicu alur Anda. Misalnya, jika alur Anda dimulai sesuai jadwal, alur akan berjalan pada tanggal dan waktu yang ditentukan.

  5. Pastikan alur berjalan seperti yang diharapkan. Periksa log dengan membuka tab Activity di flow builder. Untuk mempelajari cara membuat log kustom di tab Aktivitas, lihat Log aktivitas.

Langkah berikutnya

Anda telah berhasil membuat dan menguji langkah kustom untuk Workspace Studio. Kini Anda dapat: