Implementing Business Logic

Objectives

After completing this lesson, you will be able to:

  • Implement business logic to control the behavior of business objects

Create Script for the Event AfterModify

We've defined our business object and designed its screens in the previous two lessons. In this lesson, let’s finally bring the BO alive and implement some business logic. We'll implement a sample script for the defined action and the AfterModify event for our business object’s Root node. 

Further information can be found in SAP Help.

Implementing the Account Lookup 

Our business object allows the user to assign an account. We’ve already implemented the object value selectors (OVS) for this field, so that users can look up accounts with a convenient selection dialog. 

Whenever we want to access the data of a related object, we need more than just the object’s ID. We need an object reference. That makes the fields of the respective object accessible in scripts and in the UI Designer when binding controls. Our business object definition contains associations that serve as object references. However, assigning the right object reference to an association is a task that we must take care of. The sample use case demonstrates how to use the AccountID to retrieve the respective object reference from the database and assign it to the ToAccount association.  

Retrieving the object reference should happen as soon as the user enters an account ID, or selects an entry from the OVS. The AfterModify event is triggered after every change to a field and hence is perfectly suited for that job. However, we have to keep in mind that the AfterModify event is triggered after any field has been changed. There’s no specific AccountID-AfterModify event. Thus, we always need to evaluate the currently entered data and determine whether the changed field was the account ID. 

In the following video we will: 

  1. Create the scripts for the AfterModify event and the CalculateReportAmount action.  
  2. Implement and explain the script for the AfterModify event to retrieve the account object reference. 
  3. Modify the Thing Inspector to display the name of the account instead of its ID. 

You can find the script shown in the video here:

Code snippet
/*
    Add your SAP Business ByDesign scripting language implementation for:
        Business Object: SimpleContract
        Node: Root
        Event: AfterModify 

    Note: 
        - To access the elements of the business object node, 
          use path expressions, for example, this.<element name>. 
        - To use code completion, press CTRL+J. 
        - The solution uses this script if:
        - the value of any field in the node in which this script is contained is modified.
        - the node itself is modified by another business object within the same solution.
*/

import ABSL;
import AP.FO.BusinessPartner.Global;

if (this.AccountID.IsInitial())
{
    if (this.ToAccount.IsSet())
    {
        this.ToAccount.Reset();
    }
}
else
{
    if (!this.ToAccount.IsSet() || (this.ToAccount.IsSet() && this.AccountID != this.ToAccount.InternalID))
    {
        var rCustomer = Customer.Retrieve(this.AccountID);
        if (rCustomer.IsSet())
        {
            this.ToAccount = rCustomer;
        }
    }
}
Expand

Our business object definition contains further associations for the contract owner and the product at the item level. Assigning object references to them isn’t a part of the demonstrations, but it works similarly to the script above.

Create the Script for the Action CalculateReportAmount

In this section, we’ll concentrate on our custom action, CalculateReportAmount. In contrast to events triggered by the framework, actions are either triggered by the user by clicking a button or by an event as a subroutine. The action calculates the overall price for all items considering their quantity and unit price and stores the result in the ContractAmount field at the header level. 

The script shows how a for-each loop can be used to go through all items, read their price and amount, and calculate the total sum. 

The following video covers:

https://cdnapisec.kaltura.com/p/1921661/sp/192166100/embedIframeJs/uiconf_id/35919811/partner_id/1921661?iframeembed=true&playerId=kaltura_player_2145168470&entry_id=1_jazo46l6&wid=_1921661&flashvars[sideBarContainer.plugin]=true&flashvars[sideBarContainer.position]=left&flashvars[sideBarContainer.clickToClose]=true&flashvars[chapters.plugin]=true&flashvars[chapters.layout]=vertical&flashvars[chapters.thumbnailRotator]=false&flashvars[streamSelector.plugin]=true&flashvars[EmbedPlayer.SpinnerTarget]=videoHolder&flashvars[dualScreen.plugin]=true&flashvars[hotspots.plugin]=true

  1. Maintaining the script for the CalculateReportAmount button 
  2. Adding a button and an event handler to the Thing Inspector to execute the action 
  3. Making the ContractAmount field read-only 

This is the script snippet:

Code snippet
/*
    Add your SAP Business ByDesign scripting language implementation for:
        Business Object: SimpleContract
        Node: Root
        Action: CalculateReportAmount 

    Note: 
        - To access the elements of the business object node, 
          use path expressions, for example, this.<element name>. 
        - To use code completion, press CTRL+J. 
*/

import ABSL;

var totalAmount = 0;

// loop over items and sum up the contract amount
foreach (var item in this.Items)
{
    // make sure that price and quantity are maintained, otherwise we can't add the amount for this item
    if (!item.Price.IsInitial() && !item.Quantity.IsInitial())
    {
        var itemAmount = item.Price.content * item.Quantity.content;
        totalAmount = totalAmount + itemAmount;
    }
}


// store the result on header level; for simplicity we set the currency to USD; however we don't check the item price currency!
this.ContractAmount.content = totalAmount;
this.ContractAmount.currencyCode = "USD";
Expand

The script's main purpose is to demonstrate how to implement a custom action and make it available to end users. Besides that, it allows us to show a for-each loop in action.

In a real-world scenario, you would probably handle the calculation differently. For instance, you might call the action from within an event to ensure it is always executed before the business object instance is saved.

When you’re about to implement scripts but unsure where to start, the following points might help you decide:

  • When should the logic be executed? Triggered manually or by an event?
  • In case of an event, which event and on what node?
  • Keep in mind that AfterModify is triggered for any change to a field on the same node. You will still need to check which field was modified.

Log in to track your progress & complete quizzes