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

}

Saturday, 23 January 2016

Creating CSV Import in Netsuite

Inserting and Updating  Records In To The NetSuite System Using CSV Import:

 

CSV File Creation:

  •  Create the Fields for you want insert or update values of the Netsuite Systems Concern Records. For Example:1.Customer Record 2.Employee Record.

  • If you are Creating the CSV  Import Files for Inserting New Records in to the System means add all the Mandatory Fields for that Records as well as for the fields you want to insert data otherwise it show error while running the Insert CSV Import.

  • If you are Creating the CSV Import Files for Updating the Existing Record you add the Field Called "Internal ID" for that Particular Record otherwise it show error while running the Update CSV Import.

  • While creating the Fields in the CSV File, it is best practice to create the field name same as the field name available on the Netsuite System Concern Records. For Example .If you are creating the CSV Import the Inserting (or) Updating the Customer Record. create field's in CSV File as Same in the Customer Record.

  • while creating the mapping of fields Netsuite System  Automatically Recognize the similar field  or else we have to manually map the fields to the available matching Fields in the Netsuite Systems Records.

 

CSV Import Benefits: 

  • CSV Import are used to import large files in to the Netsuite System with one Click.

  •    CSV Import saves the time by avoiding manually entries of  the new record using automatic inserting or updating the record.  

   Following steps are used to create an CSV Import       

          1.Navigation

          2.Scan and Upload CSV File.

          3.Import Options

          5.File Mapping

          6.Filed Mapping

          5.Save Mapping and Start Import 

1.Navigation : 

  •      For Creating the CSV Import we have to Navigate Setup --> Import/Export --> Import   CSV  Records.    

Navigation for Creating CSV Import
Navigation for Creating CSV Import

 2.Scan and Upload CSV File.

  •     Choose the IMPORT TYPE as you want.  In our Example I have chosen the import type "Relationship" for importing the Customers Records in the Netsuite System
  •     Choose the RECORD  TYPE as you like. I have chosen the record as "Customers Only" for importing the Customers Record Only.
  •      Choose the CHARACTER ENCODING which suits to your Netsuite System. I have chosen the "WESTERN(Windows 1252)"  Format.
  •   Choose the CSV COLUMN DELIMITER as you want .
  •     Choose  the  CSV Files you want to Upload,we Upload Single File or Multiple Files at an Time.
  •     Then Click Next Button to Proceed.

Selecting Import Type,Record Type,Character Encoding,CSV Column Delimiter
Selecting Import Type,Record Type,Character Encoding,CSV Column Delimiter


Uploading CSV Files
Uploading CSV Files

  3.Import Options

  •     Choose the type of import option as you want:

    •           Add:

                   Using Add option you can new records in to the Netsuite System

    •           Update:

                 Using Update option you can modify existing  records in the Netsuite   System.  

    •         Add and Update :

                 Using Add and Update option you can add new records as well as update existing records in  the Netsuite System.

     

    Import Option
    Import Option

     

   4.File Mapping :          

  •  File Mapping is nothing but the Mapping of your uploaded file to concert records  in the Netsuite System.
  • Netsuite System will automatically takes care of the File Mapping. 

  5.Field Mapping :

  •   Filed Mapping is process of mapping the fields of what we created in CSV File to the Fields Available in Netsuite System Records
  •  Field Mapping consist of three Columns namely:                 
                          1.Your Fields Column (Left Column)
                                    This Column contains the fields of what we have created in the  CSV File.
                          2.  Matched Fields Column  (Center Column)
                                    This  Column it display all the matching  from Your Fields Column an Netsuite Fields Column.
                         3.Netsuite Fields (Right Column).
                                     This Column contains all the fields of the Netsuite Systems Concern Record.
  •      Click Next Button to proceed.
Field Mapping
Field Mapping

 6.Save Mapping and Start Import 

  •   Give the Name for the CSV Import 
  •   Give the Description for the CSV Import if you want (Optional)
  •   Click   Start&Run Button .
    

Saving Import CSV
Saving Import CSV


Import CSV Finished
Import CSV Finished

 7.Viewing CSV Import Status:

  •        we can view the status of the CSV Import status by Navigating Setup --> Import/Export --> View CSV Import Status. 

    Navigation for Viewing Status of CSV Import
    Navigation for Viewing Import CSV Status.



    • We can also check the CSV Import is done correctly are not by checking the Inserted an Updated Records 
    • In our example we have created the CSV Import for Inserting and Updating Records to the Customer Record
    • For checking the Customer Record Go to List --> Relationship -->Customer
     
Navigation for Customer Record
Navigation for Customer Record


List Of Customers Record

Customer Record
Customer Record


                   

Thursday, 21 January 2016

Parent Child Relationship In Netsuite

Parent Child Relationship In Netsuite:

we can create an Parent Child Relationship in Netsuite  with help of Custom Record Types.

For Creating New Record Type,Go To Customization --> List,Records&Entities -->Record Types --> New


Navigation for creating new Record Type


Parent Record Creation:

  1. Enter the Name for the Record . In our  example we create an record called "Degree".
  2. Enter the Id for the Record. If you forget to create an Id ,the Netsuite default functionality will create an numeric id automatically. we can create the id in text for our easy understanding.
  3. To make the custom record as an Parent Record click the "check box Allow Child Record Editing".
  4. Click Fields Tab to add an custom fields to the record.
  5. Click Subtabs Tab to add an Subtab to the record
  6. Click Links Tab to create an custom link to the record for easy access of that record.
  7. Click Save Button.

Step 1,Step 2 & Step 3:


Parent Record Creation



Step 4:


Creating Custom Field In Parent Record

Step 5:

Creating Subtab In Parent Record



Step 6:


Creating Custom Link to Parent Record

Child Record Creation:

  1. Enter the Name for the Record . In our  example we create an record called "Branch".
  2. Enter the Id for the Record.
  3. Click Save Button.
  4. Click Fields Tab to add an custom fields to the record.
  5. To make the custom record as Child Record,Create one custom field,give the Name and Id for that field as you like and choose the TYPE as List/Record ,LIST/RECORD as Degree and click the Check Box "RECORD IS PARENT".
  6. Click Display Tab in the same custom field and choose the value "Branch"  in the List Field PARENT SUBTAB  and Click Save.
  7. Click Links Tab to create an custom link to the record for easy access of that record.
  8. Click Save Button.

Step 1,Step 2 & Step 3:

Creating Custom Child Record.

Step 4 & Step 5:

Creating Custom Field In Child Record

Step 6:

Mapping the Parent Record Subtab to the Child Record

Step 7:

Creating Custom Link to the Child Record

Verifying the Output:

  •      Verifying the Parent Record:
                  1. Go To Customization --> List,Records&Entities -->Record Types 
                  2. Click the "Degree Record" from the List of Displaying Record.
                  3.Click Child Records Tab.
                  4.In that Child Records you will see the values "Branch" in Name Field and 
                   " Branch" in  Tab field.
                  5.The Value "Branch" in Name Field Represents the Custom record Branch
                      (Child Record).
                  6.The Value "Branch" in Tab Field Represents the Subtab in Created Degree 
                      Record(Parent Record).

              Step 1:

Child Records Tab 
  •          Verifying the Child Record         
                     1. Go To Customization --> List,Records&Entities -->Record Types 
                     2. Click the "Branch Record" from the List of Displaying Record.
                     3.Click Parent Records Tab.
                     4. In that Parent Record Tab you will see the value "Degree" in Name Field.
                     5.The Value "Branch" in Name Field Represents the Custom record Degree
                      (Parent Record).

           Step 2:

        
Parent Records Tab

  If both verification are correct,you have successfully created an Parent Child Relationship.