Saturday, 15 June 2024

Practical applications of the N/runtime Module


N/runtime Module

  • A more straightforward and potent module is NetSuite N/Runtime.

  • We can create a reliable, secure, and effective business solution or feature by combining the runtime module with other SuiteScript modules. 
  • Using a real-world example, I will attempt to demonstrate the practical use of a runtime module in this blog post.

  • Business Use Case: 
    Imagine that we are constructing a tool in the NetSuite system for tracking employee leaves. This tool allows employees to delegate work to their peer coworkers, apply for new leaves, track leaves that they have already submitted,  check their remaining leave balance, cancel their already-submitted leave request, etc.

  • The N/runtime module allows us to obtain the information below :
    •  The script's runtime settings,
    •  The session info, 
    • The user's current log-in details.
    • The information about NetSuite accounts, including the Account Id, Version, Environment, and Processor Count
    • Context of Execution

  • Let's create an employee leave tracking app using each of the possible aforementioned runtime module features.

  • Method: runtime.getCurrentUser()

runtime.getCurrentSession()
  • Assume that the following fields are included in the Leave Tracking Application (LTA):
    • Requested By
    • Next Approver (Manager)
    • Leave Start Date  & Leave End Date
    • Reason
    • Any Supporting Documents

  • Use Case 1 :

    Once the user enters the LTA screen for applying leave, we can automatically default the Requested By Field and Next Approver values using the below syntax.

    • Get current logged-in user information
      • let currentLoggedInUserDetails = runtime.getCurrentUser();
        
    • Get current logged-in user Id i.e. (NetSuite employee record internal id)
      • let userId = currentLoggedInUserDetails.id;

        //Record.setValue('customrecord_requested_by,
        userId);
    • Then use the N/search module to get the employee's manager id.

      • let fieldLookUp = search.lookupFields({
            type: search.Type.Employee,
            id:  userId ,
            columns: ['custentity_manager']
        });
        
        let empManager = fieldLookUp.custentity_manager;
        
        //Record.setValue('customrec ord_req_by_manager', empManager);
    • Use Case 2 : 

      In a similar way, we can use the employee's logged-in user ID to display the Cancel button to the employee who filed the leave request and the "Approve/Reject" button to the employee  manager so they can approve the leave request of their subordinates.

    • Use Case 3 : 

      Assuming the employee requests a leave of absence longer than thirty (30) working days, they must submit the necessary documentation and obtain further HR department permission.

    • let userDepartment = currentLoggedInUserDetails.department;
      
      if(userDepartment === 'HR Department'){
      
         //Show the Approve/Reject Button to the HR, for approving employee leave request.
         //When the employee taking leave more than 30 days.
      
      }

    • Use Case 4 : 

      Assume for the moment that the organisation has employed more than 50,000 people and is spread out across several different nations. The HR team head for the employee region must then approve the secondary request.

      For example, the HR department in America needs to approve or reject a leave request submitted by an employee from the United States; the same goes for Asia, Africa, Europe, Oceania, etc.

    • let defaultEmployeeRegions = [`America's`,`Asia`,'Africa',`Europe`,`Oceania`];
      
      let userDepartment = currentLoggedInUserDetails.department;
      
      let userLocation = currentLoggedInUserDetails.location;
      
      if(userDepartment === 'HR Department' && defaultEmployeeRegions.includes(userLocation)){ //Show the Approve/Reject Button to the HR }

  • Method : runtime.getCurrentScript()


Runtime Script Properties

    • We can obtain the details of the currently executing script using the below syntax,
       
      let scriptObj = runtime.getCurrentScript();

    • Method:  script.getParameter() : 

    • Use Case 5 :  This is a technique to pass a changeable or dynamic value to a script without having to hardcode it there.

    • let scriptObj = runtime.getCurrentScript();
      
      let paramDepartment = scriptObj.getParameter({name: 'custscript_department'});
      
      In the script deployment --> Script Parameter field page: will store the Department value i.e. "HR Department"; 
      
      
      if(userDepartment === paramDepartment){
      
         //Show the Approve/Reject Button to the HR
      
      }

    • Property: Script Id, Script Deployment Id

      • Use Case 6 : 

        Instead of viewing each request individually, the HR Department would prefer to see the list of pending leave requests associated with their region on a single screen. They use this screen to examine and approve all of the leave requests at once.

      • We provide the HR department with a confirmation message once every leave request has been examined and submitted for approval.

        let scriptObj = runtime.getCurrentScript();
        
        let currentScriptId = scriptObj.id;
        
        let currentScriptDeploymentId = scriptObj.deploymentId;
        
        Using the N/Redirect module we can redirect it to "Status" Page.
        
        redirect.toSuiteLet({
          scriptId: currentScriptId,
          deploymentId: currentScriptDeploymentId,
          parameters: {
             'custparam_show_status_page' : 'YES'
        });
        
    • Method: script.getRemainingUsage() : 
      • There is a defined governor usage limit for each script.
      • For instance, a scheduled script can have 10,000 usage points, a RestLet script can have 5000 usage points, a client script, a user event, and a SuiteLet script can have 1000 usage points, and so on.
      • The script governance limit will be lowered.if the script makes use of SuiteScript APIs such as email.send(), record.create(), record.load(), search.create(), and so on.

      • Use Case 7 : 

        We can obtain the remaining governance usage limit of the currently running script and create efficient solutions by using the script.getRemainingUsage().

      • var scriptObj = runtime.getCurrentScript();
        
        For Scheduled Script : 10000 Usage Points
        
        if(scriptObj.getRemainingUsage() >= 200){
        
           // Do you business logic here
        
        }else{
        
          ReTrigger the same Scheduled Script to resume it's operation
          
          let currentScriptId = scriptObj.id;
        let currentScriptDeploymentId = scriptObj.deploymentId;
        let schScriptTask = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT, scriptId: currentScriptId, deploymentId: currentScriptDeploymentId, params: {lastRunLTARecordId: 12345} }); let scheduledScriptTaskId = schScriptTask.submit(); }

  • Property: runtime.executionContext

NetSuite Execution Contexts

    • Details about how a script is triggered to run are provided by execution contexts. A NetSuite application activity or an action taking place in a different context, such as a web services integration, CSV import, user interface, or client, for instance, causes a script to be activated. 
    • To make sure that your scripts run only when necessary, you can use execution context filtering. 

    • Use Case 8 : 

      Assume for the moment that an employee should only submit a leave request while logged into NetSuite.
    • if (runtime.executionContext === runtime.ContextType.USER_INTERFACE) {
          //Do the scripting solution
      }else{
      
        //Throw validation error message using N/error module
      
      
      var custom_error = error.create({
          name: 'YOU_ARE_NOT_ALLOWED_CREATE_NEW_LTA_RECORD',
          message: 'Invalid LTA Request',
          notifyOff: false
      });
      
      throw custom_error;
      }
                              

  • Property: runtime.accountId
    • Use Case 9 :

      Let's assume that the LTA app has been released as the NetSuite Suite App. This SuiteAPP is a paid version. To utilise this SuiteApp within their firm, one must purchase it from the developed company. It has a one-year license usage policy. Organisations must renew annually. Assume that in the event that the organisation fails to renew, we will be able to block them from using the LTA App.
  • let companyId = runtime.accountId;
    
    //Using the N/https module we can validate the company's license in our
    company's license portal.
    
    var headerObj = {
        name: 'Accept-Language',
        value: 'en-us'
    };
    var response = https.post({
        url: 'https://www.your_organisation.com',
        body: companyId,
        headers: headerObj
    });
    
    var response_body = response.body; // see https.ClientResponse.body
    
    var response_code = response.code; // see https.ClientResponse.code
    
    if(response_code === 200){
    
     if(response_body === `LICENSE_IS_VALID`){
    
         //If the license is valid then allow the user to use the LTA app.  
    
     }else{
    
     var custom_error = error.create({
        name: 'LICENSE_EXPIRED_FOR_THE_LTA_APP_USAGE',
        message: 'Please renew at the earliest, for more details contact accounts team.',
        notifyOff: false
    });
    
    throw custom_error;
    } }



  • Property: runtime.envType

runtime.envType

    • Use Case 10 : 

      Assume that the LTA application should only be used in the production environment. 


let currentEnvironmentType = runtime.envType;

if(currentEnvironmentType === 'PRODUCTION'){

//Then allow the user to use the LTA App

}else{

  //Throw validation error message to the User

  //LTA APP can only be used in the PROD environment

}

No comments:

Post a Comment