شروع سریع: ساختن مرحله ماشین‌حساب با Google Apps Script

این شروع سریع به شما آموزش می‌دهد که چگونه بااستفاده از Google Apps Script یک مرحله سفارشی برای Workspace Studio ایجاد کنید. مرحله سفارشی دو عدد و یک عملیات ریاضی را به‌عنوان ورودی می‌گیرد، محاسبه را انجام می‌دهد، و نتیجه را برمی‌گرداند.

کارت مرحله ماشین‌حساب Workspace Studio که دو فیلد ورودی عدد و یک منوِ کرکره‌ای عملیات ریاضی را نمایش می‌دهد.
شکل ۱: کاربر مرحله ماشین‌حساب را به‌عنوان بخشی از جریان پیکربندی می‌کند.

اهداف اصلی

  • با Google Apps Script، مرحله‌ای سفارشی برای Workspace Studio ایجاد کنید.
  • مرحله سفارشی را در سازمان Google Workspace خودتان مستقر کنید.
  • مرحله سفارشی را در Workspace Studio آزمایش کنید.

پیش‌نیازها

  • «حساب Google» با دسترسی به Workspace Studio.

راه‌اندازی دستورگان

برای راه‌اندازی اسکریپت، پروژه Apps Script جدیدی ایجاد کنید و کد شروع سریع را اضافه کنید:

  1. برای ایجاد پروژه Apps Script جدید، روی دکمه زیر کلیک کنید:

    ایجاد کردن پروژه

  2. نام‌گذاری پروژه Apps Script:

    1. روی پروژه بی‌عنوان کلیک کنید.

    2. در عنوان پروژه، 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 دردسترس قرار می‌گیرد. ممکن است لازم باشد «جریان‌ها» را بازآوری کنید تا برافزا نشان داده شود. همچنین باید پیش‌از استفاده از برافزا، آن را مجاز کنید.

    برای کسب اطلاعات بیشتر درباره پیاده‌سازی‌های آزمایشی، به نصب برافزای منتشرنشده مراجعه کنید.

  2. ‫Flows را باز کنید.

  3. جریان کاری ایجاد کنید که شامل مرحله شما باشد:

    1. روی جریان کار جدید کلیک کنید.
    2. نحوه شروع گردش کار را انتخاب کنید. اگر مرحله شما به متغیر ورودی نیاز دارد، متغیر ورودی را به‌عنوان بخشی از برونداد آغازگر پیکربندی کنید.
    3. روی افزودن مرحله کلیک کنید. مرحله‌ای را که ساخته‌اید یا به‌روز کرده‌اید و محاسبه نام دارد انتخاب کنید.
    4. مرحله را پیکربندی کنید. برای مرحله محاسبه، دو مقدار و یک عملیات ریاضی انتخاب کنید. مرحله به‌طور خودکار ذخیره می‌شود.
    5. برای آزمایش کردن خروجی مرحله، مرحله دیگری اضافه کنید. برای مثال، برای افزودن خروجی به پیام Google Chat، مرحله در Chat به من اطلاع داده شود را به Chat اضافه کنید. در پیام، روی متغیرها کلیک کنید و برونداد مرحله‌تان را انتخاب کنید. برای مرحله محاسبه، متغیرها > مرحله ۲: محاسبه > نتیجه محاسبه‌شده را انتخاب کنید. متغیر به‌صورت تراشه در فیلد پیام نشان داده می‌شود.
    6. روی روشن کردن کلیک کنید. جریان شما آماده اجرا است.
  4. جریان را با فعال کردن آغازگر جریان اجرا کنید. برای مثال، اگر جریان شما طبق زمان‌بندی شروع شود، در تاریخ و زمان مشخص‌شده اجرا می‌شود.

  5. بررسی کنید که جریان طبق انتظار اجرا شود. با رفتن به برگه فعالیت در سازنده جریان، گزارش‌ها را بررسی کنید. برای آشنایی با نحوه ایجاد گزارش‌های سفارشی در برگه «فعالیت»، گزارش‌های فعالیت را ببینید.

مراحل بعدی

مرحله سفارشی را باموفقیت برای Workspace Studio ایجاد و آزمایش کردید. اکنون می‌توانید این کارها را انجام دهید: