Rules Examples

This section shows the source code for the three rules you will add.

If you have completed Adding the BadCreateAccount Rule and Adding the CreateAccount Rule, you will be familiar with adding rules.

In addition, a screenshot of the ApplyDebit rule is shown below.

ApplyDebit Rule Form View

The main purpose for showing the form view is so you can compare it with the source view when creating your own rule.

ApplyDebit Rule Source View Code

Copy

ApplyDebit Rule Source Code

/**
 * @description Debits the matching account by the specified amount
 * @author 
 */
rule Rules.ApplyDebit {
    attribute {
        priority = 1;
        forwardChain = true;
    }
    declare {
        Events.Debit    debit;
        Concepts.Account    account;
        
    }
    when {
        //Checks whether the extId of an Account instance in working memory  
        //matches the incoming event's account ID
        account@extId == debit.AccountId;
    }
    then {
        //If Account Status is not Suspended, debits the account
        if (account.Status !="Suspended") {
               account.Debits=debit.Amount;
               System.debugOut("#### Debiting account " +account@extId+ " by $" +debit.Amount);
               account.Balance=account.Balance - debit.Amount;
               System.debugOut("#### New balance: $" + account.Balance);
            }
         else {
               System.debugOut("#### Cannot debit the suspended account " +account@extId );
        }
        
        Event.consumeEvent(debit);
    }
}

BadApplyDebit Rule Source View Code

Copy

BadApplyDebit Rule Source Code

/**
 * @description
 * @author 
 */
rule Rules.BadApplyDebit {
    
    attribute {
        priority = 5;
        forwardChain = true;
    }
    
    declare {
        Events.Debit    debit;
    }
    
    when {    
    }
    
    then {
        System.debugOut("#### Debit not applied, account not found: " + debit.AccountId);    
        Event.consumeEvent(debit);    
    }
    
}

CheckNegativeBalance Rule Source View Code

Copy

CheckNegativeBalance Rule Source Code

/**
 * @description 
 * @author 
 */
rule Rules.CheckNegativeBalance {
    
    attribute {
        priority = 5;
        forwardChain = true;
    }
    
    declare {
        Concepts.Account account;        
    }
    
    when {
        // Checks that the balance is less than zero
        account.Balance < 0;
        // Checks that Account status is not set to Suspended
        account.Status != "Suspended";
    }
    
    then {
        account.Status = "Suspended";
        System.debugOut("#### Account ID " + account@extId
            + " STATUS set to Suspended. Balance "
            + account.Balance + " is less than zero");
    }
    
}