Execute Scripts in Business Rules

Execute Scripts in Business Rules

With Execute Script action in business rules, you can validate requests and update field values to automate request workflows. You can use scripts for validation of requests that involve complex conditions or requests that use third-party application inputs. 

You can execute business rule scripts on requests incoming through browser, API, mobile, and mail.

Use cases   

Update request fields based on field values in a different module or an application.   
  1. A user logs a request.
  2. You can write a script to check the solution module
  3. If a solution is found containing the request subject as keywords, copy the solution to as request resolution.
  4. Update the request status as Resolved.
Stop a request operation at any point in time.  
Define unsupported operations for a contact or support rep, whether it's data modification or the operation itself in any given stage of the request processing.
A user request for a product demo. During this request processing, execute the business rules in the following cases:
  1. After the approver approves the request, support rep or contact should not be able to change the request's input.
  2. The support rep shouldn't be allowed to change the request status to Waiting for Demo unless the request is approved.
  3. After the support rep delivers the demo to the contact, the support rep should only be allowed to change the request status as Resolved and not Closed. Only the contact should be allowed to close the request.   
Stop a request from being created.   
Prevent request duplication when the same contact raises a request for the same category, sub-category, and item.
 
Support Rep mustn't be allowed to change the request status to Waiting For Demo unless the request is approved.
List of Packages used in the script:
import sys, requests
import json,os
import datetime
################ Method Definition Starts #############
# ------------------ Function to parse input from Request JSON file----------------------
def read_file(file_Path, key=None):
    with open(file_Path) as data_file:
        data = json.load(data_file)
    if key==None:
        return data
    else:
        dataObj = data[key]
        return dataObj
#----------- Function to get diff json old value FOR V3 Format -------------------
# Will return old value present in the diff json
def getValueFromDiffJSON_V3(diffJSON,key):
    try:
        if key in diffJSON['old']:
            if(isinstance(diffJSON['old'][key],dict)):
                return diffJSON['old'][key]['name']
            else:
                return diffJSON['old'][key]
        else:
                print("No value present in Diff JSON")
    except:
        print("Unexpected error in parsing diff json"+diffJSON)
#------------ Constructing the Json Object for updating the request.---------
# data is Json that will have the Field Name/Value that needs to be updated in the request
# data = {"LEVEL":"TIER 1","PRIORITY":"High","IMPACT":"High"}
# Need to pass the data to actionPlugin_constructReqJSON to vet the full json
# UPDATE,Negate are supporting for V3.
def actionPlugin_UpdateRequest(data,OperationName="EDIT_REQUEST",module=None,additionalParams=""):
     if module is not None:
         temp={}
         temp[module]=json.loads(data)
         tempString=json.dumps(temp)
         data=tempString
     json_data = '''{
         "INPUT_DATA": [''' + data +    '''],
         "OPERATIONNAME": "''' + OperationName + '''",
        ''' + additionalParams + '''
     },'''
     return json_data
#------------ Constructing the Json for default return functionality.---------
# Use a combination of above two functions to construct the data parameter
# data = actionPlugin_AddNote("Ticket has been created in JIRA and information populated in SCP")
def actionPlugin_constructReqJSON(data, message="Request Updated Successfully"):
     json_data = '''{
              "message":"''' +message + '''",
              "result":"success",
              "operation":[''' + data + ''']
              }'''
     return json_data
################ Method Definition ends #############
# File containing request details will be stored as json object and the file path will be passed as argument to the script replacing the $COMPLETE_JSON_FILE argument
file_Path = sys.argv[1]
# Load the json content which contains request details (Changed)
requestObj = read_file(file_Path,'request')
diffObj = read_file(file_Path,'diff')
status=requestObj['status']['name']
appr_status=requestObj['approval_status']['name']
if  appr_status!=None and appr_status!="Approved" and status=="Waiting For Demo":
     #Constructing the Json Object for updating the request.
    #The following is a Sample of the JSON structure for Updating a Request.
     '''{
         "result": "success",
         "operation": [
         {
              "OPERATIONNAME": "NEGATE",
             "REASON": "Negate Reason"
              }
         ]
         }'''
     message = "Cannot change the request status to "+status+" unless the request is approved"
     #Creating the Json that will have the Field Name/Value that needs to be updated in the request
     updatejson = actionPlugin_UpdateRequest("","NEGATE",additionalParams='''"REASON":"'''+message+'''"''')
     returnJson = actionPlugin_constructReqJSON(updatejson,message)
     #Returning the Constructed Json Object
     print(returnJson)
elif  appr_status!=None and appr_status=="Pending Approval":
    #The following is a Sample of the JSON structure for Updating a Request.
     '''{
       "result": "success",
       "message": "Sample Python script",
       "operation": [
         {
           "OPERATIONNAME": "UPDATE",
           "INPUT_DATA": [
             {
               "request": {
                 "urgency": {
                   "name": "High"
                 },
                 "group": {
                   "name": "Network"
                 },
                 "priority": {
                   "name": "High"
                 }
               }
             }
           ]
         }
       ]
     }'''
     message = "Set priority to High when approval status is Pending approval"
     #Creating the Json that will have the Field Name/Value that needs to be updated in the request.
     updatejson = actionPlugin_UpdateRequest('''{"priority":{"name":"High"}}''',"UPDATE","request")
     returnJson = actionPlugin_constructReqJSON(updatejson,message)
     #Returning the Constructed Json Object.
     print(returnJson)
else :
     print("No changes found") # This message will be printed in the History if not of the Conditions in the Script was matched.

Add Command in a Business Rule   

  1. Go to Actions, click Select Custom Actions > Execute Script.
  2. On the displayed text box, enter the file name containing the script and click Save.
Sample configuration  
Consider the case to raise a Jira ticket from SupportCenter Plus. To configure a custom script for this action,
  1. Create a text file with the given command: py CreateJiraTicket.py $COMPLETE_V3_JSON_FILE
  2. Save the file as create-jira-ticket.txt and place it under [SCP_HOME]/integration/custom_scripts/executor_files directory.
  3. When configuring the custom action, enter the file name in the executor field.
  4. Click Save.

During execution, the application will fetch the command from the given text file.

Parameter supported—$COMPLETE_V3_JSON_FILE   

$COMPLETE_V3_JSON_FILE denotes the path of a file that has complete request details, previous and updated field values in the JSON format. The file is temporary and it will be automatically deleted after the script is executed.

The temporary JSON file is created in SCP_Home\integration\custom_scripts\request\ directory, file name being <requestid_timestamp>.json.

$COMPLETE_V3_JSON_FILE structure
{
  "request": {
    <all request properties in V3 format>
  },
  "diff": {
    "old": {
      "request": {
        "priority": {
          "id": "4",
          "name": "High"
        },
        "urgency": {
          "id": "3",
          "name": "Normal"
        },
        "impact_details": "High impact for servers"
      }
    },
    "new": {
      "request": {
        "priority": {
          "id": "1",
          "name": "Low"
        },
        "urgency": {
          "id": "4",
          "name": "Low"
        },
        "impact_details": "Low impact for servers"
      }
    }
  },
  "LOGIN_NAME": "administrator",
  "LOGGEDIN_USER_TYPE": "technician",
  "LOGGEDIN_USER_NAME": "administrator",
  "OPERATION_TYPE": "add"
} 

Input provided to $COMPLETE_V3_JSON_FILE temp file  
Input is in JSON. Here the request key contains the user given fields and fields filled by system in V3 API format.

Additional information given in the input file  
  1. LOGIN_NAME
  2. LOGGEDIN_USER_NAME
  3. LOGIN_USER_ID
  4. LOGGEDIN_USER_TYPE
  5. OPERATION_TYPE

Output JSON format for Custom Scripts   

The script for requests file should return a JSON which has the success/failure status and a message which will be displayed in the history tab of the request.

General format:
 {
  "result": "success",
  "message": "Message"
  1. Result denotes the success/failure status of the action.
  2. Message is the information to be displayed in the request's history tab.
The server script must write the output JSON (if any) to the same temp file that is provided to the script. You must not invoke external API calls to update the same request because this will not allow the updated values to be carried forward to the cascading business rules.

Operations Supported   

You can perform Update and Negate operations using the JSON return.
All fields that can be updated via request API can also be updated using custom scripts. 
Example (for Update operation)
 {
  "result": "success",
  "message": "Sample Python script",
  "operation": [
    {
      "OPERATION_NAME": "UPDATE",
      "INPUT_DATA": [
        {
          "request": {
            "urgency": {
              "name": "High"
            },
            "group": {
              "name": "Network"
            },
            "priority": {
              "name": "High"
            }
          }
        }
      ]
    }
  ]
} 

Example (for Negate operation)
 {
  "result": "success",
  "operation": [
    {
      "OPERATION_NAME": "NEGATE",
      "REASON": "Negate Reason"
    }
  ]
} 

 To learn more about writing a custom script, click here

    • Related Articles

    • Business Rules for Notes

      Business rules are used to automate certain actions for notes that fulfill certain incoming criteria. Some of the actions that can be automated using business rules for notes include making the notes public for all users or making the notes available ...
    • Business Rules for Notifications

      Business rules are used to automate certain actions for notifications that fulfill certain incoming criteria. Some of the actions that can be automated using business rules for notifications include pausing specific notifications or turning them off ...
    • Business Rules for Request

      Business rules are used to automate certain actions for requests that fulfill certain incoming criteria. Some of the actions that can be automated using business rules include assigning groups, support reps, status, and priority. You can now create ...
    • Business Rules

      Business rules are used to automate certain actions for requests or records that fulfill certain incoming criteria. Some of the actions that can be automated using business rules include assigning groups, support reps, status, and priority, besides ...
    • Executing Custom Function in Business Rule

      By executing custom functions in business rules, you can manipulate data in SupportCenter plus and other external applications. requestObj and context are the arguments supported in custom functions. Choose the required custom function from the list ...