How-To: Use Script Tasks in SAP Build Process Automation

Estimated read time 19 min read

Motivation

SAP Build Process Automation just got even more powerful with its latest feature that allows users to write executable code in JavaScript. This new feature, introduced in October 2024, enables users to perform specific calculations or data manipulations as part of their business process.

Previously, the ability to write executable code was limited to automation tasks, but now, users have access to the entire context of their business process. This means you can manipulate data and perform calculations at various stages of the process, making it more dynamic and responsive to changing needs.

Creating a business project from scratch may seem like a daunting task, but with the right starting point and guidance, it can be a seamless process. In this blog post, I will guide you through the steps to create a business project that includes an action task, a script task, and an approval form to facilitate a simple approval workflow.

Scenario

Imagine a sales team that wants to offer tailored discounts to repeat customers. They need to present these discount requests to the finance department for review and approval, ensuring discounts align with business policy. Here’s how this process typically unfolds:

The Sales Team Initiates a Discount Request: They select products and propose discounts based on the customer’s purchase history.Data Fetching: Relevant product information is fetched from the backend.Approval by Finance: The finance team reviews the request and either approves or declines the proposed discounts.

Note: The simplified implementation of this scenario is designed to showcase the usage of a script task within a business process.

Prerequisites

Access to Business Technology Platform Admin Console (Trial can be accessed here)Access to SAP Build Process AutomationAccess to SAP Build Lobby       Access to OData Northwind service 

Getting Started

Let’s break down the scenario into its components and examine how to create the necessary artifacts.

Step 1: Create a SAP BTP Destination

The data required for this process will be retrieved from the OData Northwind service, which offers access to a sample database with product and customer information. We need to set up a SAP BTP Destination that will be utilized by an Action Task in the SBPA project. 

Go to BTP Admin Cockpit and create a new Destination and maintain the properties below in the table. PropertyValuesap.applicationdevelopment.actions.enabledtruesap.processautomation.enabledtruesap.build.usage

odata_gen

Name the destination e.g. NorthwindUse the Northwind OData URL: https://services.odata.org/northwind/northwind.svc/Maintain Authentication as NoAuthentication. After creation the destination looks like below:

Step 2: Create, Test and Publish an Action Project in SBPA

In this step, you will create an Action Project that utilizes the BTP destination. This Action Project will be published to the action library and will be accessible in the SAP Build lobby. Later, this Action Project will be used to retrieve products from the OData Northwind service.

In the SAP Build Lobby, under Connectors node choose Actions and click on CreateSelect OData DestinationsSelect the BTP Destination (Northwind) that we previously created and choose Products in the available entities and methods of the OData API. Then click NextUpdate the Project name and Description or let it as it is. Click Create                                             The expected output does not match the actual output according to the OpenAPI specifications. We need to change the UnitPrice Type from Number to StringSave your work

 

Step 3: Test, Release and Publish your Action Project

In the Actions Editor you can choose the methods that you would like to publish as Actions. Choose Get entities from Products.

Before releasing, you can test the Action Project. You should receive a list of products from the OData Northwind service.

Inputs and Outputs can be customized or simplified as needed, but in this simple example, proceed without making any changes.Switch to the test tab to test the action. Notice that the destination is pre-selected as the action was created based on a destination.Click on test. A successful 200:OK response from the Northwind OData API is now displayed at the bottom of the screen.

 

Click on the Release button at the top right and then click on Publish. “Release” creates a non modifiable version of the Action and “Publish” publishes the Action into SAP Build library from where it can be consumed in different Build Artifacts.Now, the destination needs to be made accessible in SAP Build Process Automation. Go to Control Tower –> Destinations in the SAP Build Lobby and add the Northwind Destination to your SAP Build Process Automation environments.

 

Step 4: Create a new Business Process Project

SAP Build Lobby -> Create -> Build an Automated Process -> Business Process -> Enter Project name and Description -> Click CreateClick Create Process -> Enter Name -> Click CreateClick on the (+) icon in the middle of the process -> Actions -> Browse all actionsSearch for the Action “Get entities from Products” and click on Add

Select the added Action in the Process Canvas and create a destination variable with any name. This variable will be used during deployment of the process to link to an actual destination. A destination variable enables linking different destinations in different landscapes ( Dev, Test, Prod) without changing the Process.

.

 

Step 5: Create an API Trigger

We are going to use an API Trigger to initiate the workflow. In the Process Editor click on Add a Trigger select API Trigger add a name and click Create

Add an API trigger to your processIn the Process Builder click on the blank canvas. Choose the Variables tab and select Configure for the Process Inputs section. To start the process we need to two variables. Add input variables productitems and discount.Choose the Variables tab and select Configure for the Custom Variables section. Configure the following variables NameTypeitemresultsget_Products_200_output_schematotalpriceNumbertotaldiscountpriceNumberSelect Apply to finish and Save                                                               

 

Step 6: Add and configure the Action Project

To add the Action Project, click on the (+) icon after the TriggerSelect ActionIn the Browse library page, find the Action project with name Get entities from Products and click on Add.Select the Get entities from Products action task. In the General tab select + Create Destination Variable.A dialog opens up to create a destination variable. Enter the following values and click Create. Input FieldInput ValueIdentifierNorthwindTypeSelect Destination

We want to restrict the number of items from the results that come from the OData Northwind service. Therefore we use the productitems variable. Choose the Input tab and add productitems as value for $top:                                                                                                                                                            

Save your work.

 

Step 7: Create a Script Task

We are now incorporating a simple logic into our process. Our goal is to calculate the total price and the total discounted price for products obtained from the OData Service.

In the Process Editor click on (+) icon after the Action Task. Add a Script Task

Double click on the Script Task to open the Editor. Delete the code and add the following code:

 

 

$.context.custom.totalprice = 0;
var result = $.context.action_get_Products_1.result.value;
var discountprice = 0;

result.forEach(function (value) {
$.context.custom.totalprice += Number(value.UnitPrice);
})

discountprice = ($.context.custom.totalprice * ($.context.startEvent.discount / 100));

$.context.custom.totaldiscountprice = $.context.custom.totalprice – Number(discountprice);

 

 

You have the option to test your JavaScript code locally by using sample values for the context variables, all without having to deploy the project. To do this, simply switch to the Test Variable tab and input default values for the context variables that are being used. For instance:

Variable NameVariable Value$.context.action_get_Products_1.result.value[{“CategoryID”: 1,”Discontinued”: false,”SupplierID”: 1,”UnitPrice”:”18.0000″,”ProductName”: “Chai”,”UnitsOnOrder”: 0,”QuantityPerUnit”: “10 boxes x 20 bags”,”ProductID”: 1,”ReorderLevel”: 10,”UnitsInStock”: 39},
{“CategoryID”: 1,”Discontinued”: false,”SupplierID”: 1,”UnitPrice”:”19.0000″,”ProductName”: “Chang”,”UnitsOnOrder”: 40,”QuantityPerUnit”: “24 – 12 oz bottles”,”ProductID”: 2,”ReorderLevel”: 25,”UnitsInStock”: 17}]$.context.custom.totalprice0$.context.startEvent.discount25$.context.custom.totaldiscountprice0

 

Click Run test

You can find more information about testing: here

Click on Apply and Save

 

Step 8: Create a Approval Form

In the last step, we will design a simple approval form to either approve or reject the product discount.

Navigate back to the Process Builder canvas to create an Approval Form. Click on (+) after the Script Task.Enter the name as Approval Form and click Create.Select Approval Form and under General Select Open Editor.Design the form by dragging and dropping the corresponding form elements as shown below. Form Fields ValueField TypeConfiguration (Read Only)Approve Products and DiscountHeadline1 xA new approval task has been received. Please review and confirm whether the discount can be met or not.Paragraph xProduct listTable xProduct NameText xUnit PriceText xPricesTable xDiscount %Number xTotal PriceNumber xTotal Discount PriceNumber xMessage to SellerText Area The Approval form should be the same as below Save the form.Back in the Process Editor, click on the Approval Form and configure the Subject and Recipients.

In the Subject section:

Enter the subject as: Please review the discountsIn the Recipients/Users section, enter “Process Started By“.Configure the inputs of Approval Form. Navigate to Inputs and map the fields accordingly.

Save your work

Congratulations on successfully completing your project! Your process should look like below:                                                                                     

 

Step 9: Release the Business Process Project

In order to start the process, you must first release the business process project and then deploy it. Releasing the project creates a version or snapshot of the changes, while deploying the project makes it available in runtime for use. It is only possible to deploy a released version of the project, and at any given time, there can be multiple deployed versions of the same project.

In the Process Builder, to release a project, click Release button on the top-right corner of the screen and provide a description in the popup dialog. If you are releasing for the first time, then the version will start with 1.0.0. Next time you release, the version numbers will be automatically updated.Click Release                                                                                  Once the project is released successfully, click Deploy button on the top-right corner of the screen.Select the environment and click Deploy.Select the destination Northwind from the drop down and click Deploy.

 

Step 10: Run the Business Process

Let us test the API Trigger in the Monitoring tab of the SAP Build. Click on the Manage > Process and Workflows tile.Search for your project.Click on Start New Instance.Remove the example payload in the dialog. Use the following JSON in the dialog. 

 

 

{
“productitems”: 6,
“discount”: 35
}​

 

 

  Click Start New Instance and Close.

 

Step 11: Accessing the task

Now it’s time to monitor the process flow and access the tasks.

Tasks are the request for the users to participate in an approval or review process. These tasks appear in the My Inbox application shipped with SAP Build. Users can claim, approve and reject the task from their inbox. You can add a message to the requester.

Users can approve and reject the task from their inbox and you can add a message to the requester. Additionally, you could consider adding more steps to the process, such as sending a notification email to the requester.                                                                                     

 

Additional Read

To learn more about the topic covered in this blog post, please also refer to the following assets & follow us on SAP community.

Related Blog PostsConsume an OData API as Actions using a DestinationTransform Data with Javascript in SAP Build Process AutomationSAP Help guides for more detailshttps://help.sap.com/docs/build-process-automation/sap-build-process-automation/create-and-configure-script-taskLearning https://developers.sap.com/tutorials/spa-custom-variables..html 

​ MotivationSAP Build Process Automation just got even more powerful with its latest feature that allows users to write executable code in JavaScript. This new feature, introduced in October 2024, enables users to perform specific calculations or data manipulations as part of their business process.Previously, the ability to write executable code was limited to automation tasks, but now, users have access to the entire context of their business process. This means you can manipulate data and perform calculations at various stages of the process, making it more dynamic and responsive to changing needs.Creating a business project from scratch may seem like a daunting task, but with the right starting point and guidance, it can be a seamless process. In this blog post, I will guide you through the steps to create a business project that includes an action task, a script task, and an approval form to facilitate a simple approval workflow.ScenarioImagine a sales team that wants to offer tailored discounts to repeat customers. They need to present these discount requests to the finance department for review and approval, ensuring discounts align with business policy. Here’s how this process typically unfolds:The Sales Team Initiates a Discount Request: They select products and propose discounts based on the customer’s purchase history.Data Fetching: Relevant product information is fetched from the backend.Approval by Finance: The finance team reviews the request and either approves or declines the proposed discounts.Note: The simplified implementation of this scenario is designed to showcase the usage of a script task within a business process.PrerequisitesAccess to Business Technology Platform Admin Console (Trial can be accessed here)Access to SAP Build Process AutomationAccess to SAP Build Lobby       Access to OData Northwind service Getting StartedLet’s break down the scenario into its components and examine how to create the necessary artifacts.Step 1: Create a SAP BTP DestinationThe data required for this process will be retrieved from the OData Northwind service, which offers access to a sample database with product and customer information. We need to set up a SAP BTP Destination that will be utilized by an Action Task in the SBPA project. Go to BTP Admin Cockpit and create a new Destination and maintain the properties below in the table. PropertyValuesap.applicationdevelopment.actions.enabledtruesap.processautomation.enabledtruesap.build.usageodata_genName the destination e.g. NorthwindUse the Northwind OData URL: https://services.odata.org/northwind/northwind.svc/Maintain Authentication as NoAuthentication. After creation the destination looks like below:Step 2: Create, Test and Publish an Action Project in SBPAIn this step, you will create an Action Project that utilizes the BTP destination. This Action Project will be published to the action library and will be accessible in the SAP Build lobby. Later, this Action Project will be used to retrieve products from the OData Northwind service.In the SAP Build Lobby, under Connectors node choose Actions and click on CreateSelect OData DestinationsSelect the BTP Destination (Northwind) that we previously created and choose Products in the available entities and methods of the OData API. Then click NextUpdate the Project name and Description or let it as it is. Click Create                                             The expected output does not match the actual output according to the OpenAPI specifications. We need to change the UnitPrice Type from Number to StringSave your work Step 3: Test, Release and Publish your Action ProjectIn the Actions Editor you can choose the methods that you would like to publish as Actions. Choose Get entities from Products.Before releasing, you can test the Action Project. You should receive a list of products from the OData Northwind service.Inputs and Outputs can be customized or simplified as needed, but in this simple example, proceed without making any changes.Switch to the test tab to test the action. Notice that the destination is pre-selected as the action was created based on a destination.Click on test. A successful 200:OK response from the Northwind OData API is now displayed at the bottom of the screen. Click on the Release button at the top right and then click on Publish. “Release” creates a non modifiable version of the Action and “Publish” publishes the Action into SAP Build library from where it can be consumed in different Build Artifacts.Now, the destination needs to be made accessible in SAP Build Process Automation. Go to Control Tower –> Destinations in the SAP Build Lobby and add the Northwind Destination to your SAP Build Process Automation environments. Step 4: Create a new Business Process ProjectSAP Build Lobby -> Create -> Build an Automated Process -> Business Process -> Enter Project name and Description -> Click CreateClick Create Process -> Enter Name -> Click CreateClick on the (+) icon in the middle of the process -> Actions -> Browse all actionsSearch for the Action “Get entities from Products” and click on AddSelect the added Action in the Process Canvas and create a destination variable with any name. This variable will be used during deployment of the process to link to an actual destination. A destination variable enables linking different destinations in different landscapes ( Dev, Test, Prod) without changing the Process.. Step 5: Create an API TriggerWe are going to use an API Trigger to initiate the workflow. In the Process Editor click on Add a Trigger select API Trigger add a name and click Create. Add an API trigger to your processIn the Process Builder click on the blank canvas. Choose the Variables tab and select Configure for the Process Inputs section. To start the process we need to two variables. Add input variables productitems and discount.Choose the Variables tab and select Configure for the Custom Variables section. Configure the following variables NameTypeitemresultsget_Products_200_output_schematotalpriceNumbertotaldiscountpriceNumberSelect Apply to finish and Save                                                                Step 6: Add and configure the Action ProjectTo add the Action Project, click on the (+) icon after the TriggerSelect ActionIn the Browse library page, find the Action project with name Get entities from Products and click on Add.Select the Get entities from Products action task. In the General tab select + Create Destination Variable.A dialog opens up to create a destination variable. Enter the following values and click Create. Input FieldInput ValueIdentifierNorthwindTypeSelect DestinationWe want to restrict the number of items from the results that come from the OData Northwind service. Therefore we use the productitems variable. Choose the Input tab and add productitems as value for $top:                                                                                                                                                            Save your work. Step 7: Create a Script TaskWe are now incorporating a simple logic into our process. Our goal is to calculate the total price and the total discounted price for products obtained from the OData Service. In the Process Editor click on (+) icon after the Action Task. Add a Script TaskDouble click on the Script Task to open the Editor. Delete the code and add the following code:  $.context.custom.totalprice = 0;
var result = $.context.action_get_Products_1.result.value;
var discountprice = 0;

result.forEach(function (value) {
$.context.custom.totalprice += Number(value.UnitPrice);
})

discountprice = ($.context.custom.totalprice * ($.context.startEvent.discount / 100));

$.context.custom.totaldiscountprice = $.context.custom.totalprice – Number(discountprice);  You have the option to test your JavaScript code locally by using sample values for the context variables, all without having to deploy the project. To do this, simply switch to the Test Variable tab and input default values for the context variables that are being used. For instance:Variable NameVariable Value$.context.action_get_Products_1.result.value[{“CategoryID”: 1,”Discontinued”: false,”SupplierID”: 1,”UnitPrice”:”18.0000″,”ProductName”: “Chai”,”UnitsOnOrder”: 0,”QuantityPerUnit”: “10 boxes x 20 bags”,”ProductID”: 1,”ReorderLevel”: 10,”UnitsInStock”: 39},{“CategoryID”: 1,”Discontinued”: false,”SupplierID”: 1,”UnitPrice”:”19.0000″,”ProductName”: “Chang”,”UnitsOnOrder”: 40,”QuantityPerUnit”: “24 – 12 oz bottles”,”ProductID”: 2,”ReorderLevel”: 25,”UnitsInStock”: 17}]$.context.custom.totalprice0$.context.startEvent.discount25$.context.custom.totaldiscountprice0 Click Run testYou can find more information about testing: hereClick on Apply and Save Step 8: Create a Approval FormIn the last step, we will design a simple approval form to either approve or reject the product discount.Navigate back to the Process Builder canvas to create an Approval Form. Click on (+) after the Script Task.Enter the name as Approval Form and click Create.Select Approval Form and under General Select Open Editor.Design the form by dragging and dropping the corresponding form elements as shown below. Form Fields ValueField TypeConfiguration (Read Only)Approve Products and DiscountHeadline1 xA new approval task has been received. Please review and confirm whether the discount can be met or not.Paragraph xProduct listTable xProduct NameText xUnit PriceText xPricesTable xDiscount %Number xTotal PriceNumber xTotal Discount PriceNumber xMessage to SellerText Area The Approval form should be the same as below Save the form.Back in the Process Editor, click on the Approval Form and configure the Subject and Recipients.In the Subject section:Enter the subject as: Please review the discountsIn the Recipients/Users section, enter “Process Started By”.Configure the inputs of Approval Form. Navigate to Inputs and map the fields accordingly.Save your workCongratulations on successfully completing your project! Your process should look like below:                                                                                      Step 9: Release the Business Process ProjectIn order to start the process, you must first release the business process project and then deploy it. Releasing the project creates a version or snapshot of the changes, while deploying the project makes it available in runtime for use. It is only possible to deploy a released version of the project, and at any given time, there can be multiple deployed versions of the same project.In the Process Builder, to release a project, click Release button on the top-right corner of the screen and provide a description in the popup dialog. If you are releasing for the first time, then the version will start with 1.0.0. Next time you release, the version numbers will be automatically updated.Click Release                                                                                  Once the project is released successfully, click Deploy button on the top-right corner of the screen.Select the environment and click Deploy.Select the destination Northwind from the drop down and click Deploy. Step 10: Run the Business ProcessLet us test the API Trigger in the Monitoring tab of the SAP Build. Click on the Manage > Process and Workflows tile.Search for your project.Click on Start New Instance.Remove the example payload in the dialog. Use the following JSON in the dialog.   {
“productitems”: 6,
“discount”: 35
}​    Click Start New Instance and Close. Step 11: Accessing the taskNow it’s time to monitor the process flow and access the tasks.Tasks are the request for the users to participate in an approval or review process. These tasks appear in the My Inbox application shipped with SAP Build. Users can claim, approve and reject the task from their inbox. You can add a message to the requester.Users can approve and reject the task from their inbox and you can add a message to the requester. Additionally, you could consider adding more steps to the process, such as sending a notification email to the requester.                                                                                      Additional ReadTo learn more about the topic covered in this blog post, please also refer to the following assets & follow us on SAP community.Related Blog PostsConsume an OData API as Actions using a DestinationTransform Data with Javascript in SAP Build Process AutomationSAP Help guides for more detailshttps://help.sap.com/docs/build-process-automation/sap-build-process-automation/create-and-configure-script-taskLearning https://developers.sap.com/tutorials/spa-custom-variables..html   Read More Technology Blogs by SAP articles 

#SAP

#SAPTechnologyblog

You May Also Like

More From Author