Execute Script

Definition:

The Zenphi Execute Script action is a powerful feature that allows you to write and run custom JavaScript or TypeScript code within your Zenphi workflows. This essentially lets you extend Zenphi's built-in functionality to perform actions that are not available as pre-built actions.

Here's a breakdown of what it enables you to do:

Execute custom logic: Implement your own proprietary calculations, data manipulations, or any other custom logic that you need for your specific workflow.

Extend Zenphi's capabilities: Go beyond the standard actions and integrate with external APIs, services, or databases.

Handle complex scenarios: Address unique automation requirements that might not be covered by Zenphi's pre-built actions.


Example Use Cases:

  1. Performing complex calculations: Implement a proprietary pricing algorithm or financial model within your workflow.
  2. Validating data: Write custom validation rules to ensure data integrity before proceeding with other actions.
  3. Generating custom reports: Create reports tailored to your specific needs by processing and formatting data with your script.

Inputs:

  1. JavaScript/TypeScript support: You can write your code in either JavaScript or TypeScript, giving you flexibility and the advantage of type safety with TypeScript.
  2. Output schema: The action allows you to define an output schema, which structures the data that your script returns. This output can then be used in subsequent actions within your workflow.
  3. Dynamic parameters: You can pass data from your workflow (like variables, trigger outputs, or outputs from other actions) into your script as parameters, making your code dynamic and adaptable.

Available Libraries:

The below libraries are available to be used in your script:

  1. date-fns version 2.23.0: import { format, formatDistance, formatRelative, subDays } from 'date-fns';
  2. node-fetch version 2.6.1: import fetch from 'node-fetch';

Step-by-Step Guide:

Step 1: Add the "Execute Script" Action

Before you can unleash the power of scripting in your Zenphi flows, you'll need to add the Execute Script action, In the Zenphi toolbox, under the Operations category. If you're new to adding actions in Zenphi, you can find a complete guide here.

Step2: Define Input Parameters (Optional)

The "Execute Script" action allows you to define input parameters, which can make your scripts more flexible and reusable. Here's how to specify them:

  1. Access Parameter Settings: In the "Execute Script" action settings, you'll find a section specifically for managing input parameters.
  2. Add a Parameter: Click the "Add Parameter" button to create a new input parameter.
  3. Name the Parameter: Provide a descriptive name for your parameter. Important note: Parameter names cannot contain spaces. Use underscores (_) or camelCase as needed (e.g., firstName, user_email).
  4. Set the Value: You have two options for setting the parameter's value:
    • Static Value: Enter a fixed value directly. This is useful for constants or settings that don't change.
    • Dynamic Value: Click the chain link icon (the token picker) to insert a dynamic value. This could be data from a previous step in your flow, a form submission, a flow variable, or even a value stored securely in Zenphi Vault.

Key Considerations:

  1. Planning: Think about the data your script needs to work with. This will help you determine which input parameters to define.
  2. Data Types: Zenphi automatically handles common data types (text, numbers, etc.). If you're working with more complex data, you might need to do some type conversion within your script.
  3. Organization: Use clear and consistent naming conventions for your parameters to keep your scripts organized and easy to understand.

Step 3: Write Your Script

Now it's time to bring your automation to life with code! The "Execute Script" action in Zenphi provides a powerful code editor where you can write custom JavaScript or TypeScript code to enhance your flows.

Code Editor Features

  1. Language Support: Write your code in either JavaScript or TypeScript. Zenphi's editor recognizes both languages and provides helpful features for each.
  2. Intelligent Assistance: The code editor includes features like:
    Syntax Highlighting: Color-coding helps you visually distinguish different parts of your code (keywords, variables, etc.), making it easier to read and understand.
  3. Code Suggestions: As you type, the editor suggests possible completions for your code, speeding up development and reducing errors.
  4. Parameter use: Remember those input parameters you defined in the previous step? You can use the defined parameter by typing parameters. and choose the parameter you want from the showing list.

Important Notes

  1. Console Output: Use console.log() to print messages and values to log information into the flow run's history. This can be helpful for debugging your scripts. Example: console.log("Hello World").
  2. Error Handling: Include error handling in your scripts to gracefully manage unexpected situations.
  3. Security: Be mindful of security best practices when writing your code, especially if you are handling sensitive data.

Step 4: Return Results from Your Script

Your scripts can do more than just perform actions—they can also return data back to your Zenphi flow! This allows you to use the results of your script in subsequent actions.

Returning Values

To return data from your "Execute Script" action, use the export keyword. Here's how it works:

  1. Single Value: To return a single value (like a string, number, or boolean), use export followed by the value:
    example:
    export const myString = "Hello, Zenphi!";
    export const myNumber = 42;
  2. Complex Objects: You can also return more complex data structures, like objects:
    example:
    export const person = {
    firstName: "John",
    lastName: "Doe"
    };
  3. Multiple Values: To return multiple values, use multiple export statements:
    example:
    export const result1 = "Value 1";
    export const result2 = 123;
    export const result3 = { message: "Success!" };
  4. Using export default: If you want to export a single function or value as the primary output of your script, you can use export default:
    example:
    export default function calculateArea(width, height) {
    return width * height;
    }
    In this case, the calculateArea function would be the main output of your script.

Accessing Output in Your Flow

Each value you export from your script becomes a property of the "Execute Script" action's output. You can then use these output properties in other actions within your flow. To access an output property, use the chain link icon (the token picker) and select the "Execute Script" action followed by the name of the exported value.

Important Notes

  1. Naming: Use descriptive names for your exported values to make your flows easier to understand.
  2. Data Types: Zenphi handles various data types, but be mindful of how these types are used in subsequent actions.
  3. Error Handling: Consider returning specific values or error messages in case your script encounters issues. This can help with troubleshooting your flows.

Step 5: Define the Output Schema

To ensure that the data returned from your "Execute Script" action is used correctly in your Zenphi flow, you need to define its output schema. This schema acts as a blueprint, describing the structure and data types of the values your script exports.

Zenphi can automatically infer the output schema based on a sample JSON output from your script. Here's how:

  • Test Run: Execute a test run of your flow.
  • Log Output: Within your script, use console.log() to print the JSON output you want to use as a sample.
  • Copy and Paste: Copy the sample JSON output from the console.
  • Infer Schema: In the "Execute Script" action settings, paste the copied JSON into the "Export Schema" field. Then, click the "Infer from sample" button. Zenphi will analyze the JSON and automatically generate the output schema.

Using the Output Schema

Once the output schema is defined, Zenphi uses it to:

  • Validate Data: Ensure that the data returned by your script matches the expected structure and types.
  • Enable Token Picker: Make the output properties available in the token picker, so you can easily use them in other actions within your flow.

Example:



Zenphi Setup:

  1. Create a Flow with Form Trigger: In Zenphi, create a new flow and select "Zenphi Form" as the trigger.
  2. Add a Date Question: In the form builder, add a question of type "Date" and label it "Select a Date". This will allow users to input a specific date.
  3. Add "Execute Script" Action: Add an "Execute Script" action to your flow.
  4. Define Input Parameter: In the "Execute Script" action settings, define an input parameter named "givenDate" and map it to the "Select a Date" question from your form trigger.
    Code:
import { getWeek } from 'date-fns';

// Get the date from the input parameter  
const date = new Date(parameters.givenDate);

// Calculate the week number  
const weekNumber = getWeek(date);

// Return the week number  
export const weekNumberOutput = weekNumber;

Explanation:

This script imports the getWeek function from the date-fns library.
It retrieves the givenDate from the input parameter, which is the date selected by the user in the Zenphi form, and converts it to a Date object.
It calculates the week number using getWeek(date).
Finally, it exports the weekNumberOutput variable, making it available as an output of the "Execute Script" action.
Usage:

You can use the weekNumberOutput output in subsequent actions within your Zenphi flow. For example, you could include it in an email or store it in a Google Sheet. This allows you to dynamically calculate the week number of any date provided by the user through the form.