Free Code – Wrapper for searches in NetSuite

About a year ago I wrote a SuiteScript 1.0 class as a wrapper around the search functionality in NetSuite. I have updated the code over time, and I want to share the latest version. Among the new features is support for formulas and search expressions. The class should be backwards compatible with the original version, but in addition you can also pass an object to most functions, instead of passing separate parameters. This makes it more flexible and allows me to add more functionality.

Enjoy!

 

/**
 * Encapsulate NetSuite search functionality in an easy-to-use object for SuiteScript 1.0.
 *  
 * Version    Date            Author           Remarks
 * 1.0        11 Nov 2016     kmartinsson      Initial version
 * 1.5        06 Jul 2017     kmartinsson      Added record type to constructor
 * 2.0        23 Aug 2017     kmartinsson      Added Search2 function, with support for objects and adding multiple columns/filters
 * 2.0.1      01 Sep 2017     kmartinsson      Bug-fixes
 * 2.0.2      01 Sep 2017     kmartinsson      Fixed issue with join not being null, added hasOwnProperty check 
 * 3.0        20 Nov 2017     kmartinsson      Removed v1.x code stream, renamed Search2 to Search
 * 3.0.1      06 Dec 2017     kmartinsson      Added JSDoc style comments, updated comments to new JSDoc style
 * 3.0.2      28 Feb 2018     kmartinsson      Fixed bug in sort key which prevented proper sorting. Added alternative keys.
 * 3.0.3      15 Jul 2018     kmartinsson      Added filter expression support
 * 3.0.4      01 Oct 2018     kmartinsson      Added method removeColumns() for use on (external) saved search
 * 
 */

/**
 * Search object
 * @constructor
 * @param {string} recordtype - Optional NetSuite recordtype (internalid)
 */
function Search(recordtype) {
    this.recordType = null;
    this.columns = [];
    this.filters = [];
    this.filterExpressions = [];
    // Set internal id of saved search to null
    this.internalId = null;
    this.noSavedColumns = false;
    // If record type/ID is supplied, set it now, otherwise default to null
    if (recordtype != null && recordtype != "") {
        this.recordType = recordtype;
    }

    // Helper function to verify the value is empty or null
    function isNullOrEmpty(val) {
        if (val == null || val == '' || val ==[] || val == {}) {
            return true;
        } else {
            return false;
        }
    }

    
    /**
     * Remove all columns included in the search
     * @param none
     * 
     */
    this.removeColumns = function() {
        this.noSavedColumns = true;
    }

    /**
     * Add a column to include in the search
     * @param {object}|{string} column - Object specifying a column to return or string containing columnId
     * @param {string} join - Joined record (internalid) (optional)
     * @param {boolean}|{string} sorting - Sorting (optional)
     *         Options: true = descending, false = ascending, empty/null = no sorting, "yes" (ascending), 
     *         "no", "ascending", "descending" (can be abbreviated "a" and "d" respectively).
     */
    this.addColumn = function(column, join, sorting) {
            var nsSearchColumn = null;
            var paramColName = null;
            var paramJoin = null;
            var paramSummary = null;
            var paramSorted = null;
            // Check if first argument is string or object
            if (typeof column == "string") {
                paramColName = column;
                // Check if second argument is null (for no join)
                if (isNullOrEmpty(join)) {
                    paramJoin = null;
                    // Check if arguent for sorting was provided
                    if (!isNullOrEmpty(sorting)) {
                        paramSorted = sorting;
                    }
                } else {
                    // Check if second argument is boolean, then it is not 'join' but 'sorting'
                    if (typeof join == "boolean") {
                        paramSorted = join;
                        paramJoin = null;
                    } else {
                        paramSorted = sorting;//sorted;
                        paramJoin = join;
                    }
                }
                // Now paramJoin and paramSorted are assigned properly
                if (typeof paramSorted == "boolean") {
                    if (paramSorted == true) {
                        paramSorted = "des";
                    } else {
                        paramSorted = "asc";
                    }
                } else if (typeof paramSorted == "string") {
                    // Get first character of string, in lower case
                    var tmp = paramSorted.slice(0, 1).toLowerCase();
                    // y = ascending sorting, n = no sorting, a = ascending, d = descending
                    if (tmp == 'y' || tmp == 'a') {
                        paramSorted = "asc";
                    } else if (tmp == 'd') {
                        paramSorted = "des";
                    } else {
                        paramSorted = null;
                    }
                }

            } else {
                if (column.hasOwnProperty("name") && column.name != null) {
                    paramColName = column.name;
                } else if (column.hasOwnProperty("columnName") && column.columnName != null) {
                    paramColName = column.columnName;
                } else if (column.hasOwnProperty("columnname") && column.columnname != null) {
                    paramColName = column.columnname;
                } else if (column.hasOwnProperty("column") && column.column != null) {
                    paramColName = column.column;
                } else {
                    throw nlapiCreateError('search.addColumn() - Required Argument Missing', 'The required argument <em>columnName</em> is missing. This argument is required.<br>Received: ' + JSON.stringify(column));
                }
                if (column.hasOwnProperty("join") && column.join != null) {
                    paramJoin = column.join;
                }
                if (column.hasOwnProperty("summary") && column.summary != null) {
                    paramSummary = column.summary;
                }
            }
            nsSearchColumn = new nlobjSearchColumn(paramColName, paramJoin, paramSummary);
            // Check if 'sorted' value exists in object
            if (column.hasOwnProperty("sorted") && column.sorted != null) {
                // Get first 3 characters as lower case
                paramSorted = column.sorted.toLowerCase().substring(0, 3);
            } else if (column.hasOwnProperty("sorting") && column.sorting != null) {
                // Get first 3 characters as lower case
                paramSorted = column.sorting.toLowerCase().substring(0, 3);
            } else if (column.hasOwnProperty("sort") && column.sort != null) {
                // Get first 3 characters as lower case
                paramSorted = column.sort.toLowerCase().substring(0, 3);
            }
            if (paramSorted!= null && paramSorted!="") {
                if (paramSorted == "asc") {
                    nsSearchColumn.setSort(false);
                } else if (paramSorted == "des") {
                    nsSearchColumn.setSort(true);
                } else {
                }
            }
            // Check if 'formula' value exists in object, then add to column object
            if (column.hasOwnProperty("formula") && column.formula != null) {
                nsSearchColumn.setFormula(column.formula);
            }
            // Check if 'functionId' value exists in object, then add to column object
            if (column.hasOwnProperty("functionId") && column.functionId1 != null) {
                nsSearchColumn.setFunction(column.functionId);
                // Push new nlobjSearchColumn into array
            }
            // Check if 'label' value exists in object, then add to column object
            if (column.hasOwnProperty("label") && column.label != null) {
                nsSearchColumn.setLabel(column.label);
            }
            this.columns.push(nsSearchColumn);
            return nsSearchColumn;
        } // end function addColumn


    /**
     * Add multiple columns to include in the search
     * @param {array} columns - array of column objects
     */
    this.addColumns = function(columns) {
            for (var i = 0; i < columns.length; i++) {
                this.addColumn(columns[i]);
            }
        } // end function addColumns

    /**
     * Add a search filter
     * @param {object}|{string} filter - filter object or string containing fieldId
     * @param {string} fieldJoinId - field to use for join (optional)
     * @param {string} operator - operator for filter (optional)
     * @param {string} value - value to filter for (optional)
     */
    this.addFilter = function(filter, fieldJoinId, operator, value) {
            if (typeof filter == "object") {
                var obj = filter;
                var fieldId = obj.field;
                var fieldJoinId = null;
                if (filter.hasOwnProperty("join")) {
                    fieldJoinId = obj.join;
                }
                var operator = obj.operator;
                var value = obj.value;
                // Create filter object
                var nsSearchFilter = new nlobjSearchFilter(fieldId, fieldJoinId, operator, value);
                // Check if 'formula' value exists in object, then add to filter object
                if (obj.hasOwnProperty("formula") && obj.formula != null) {
                    nsSearchFilter.setFormula(obj.formula);
                }
                // Check if 'functionId' value exists in object,then add to filter object
                if (obj.hasOwnProperty("functionId") && obj.functionId != null) {
                    nsSearchFilter.setFunction(obj.functionId);
                }
                this.filters.push(nsSearchFilter);
            } else {
                var fieldId = filter;
                this.filters.push(new nlobjSearchFilter(fieldId, fieldJoinId, operator, value));
            }
        } // end function addFilter


    /**
     * Add multiple search filters
     * @param {array}filters - array of filter objects
     */
    this.addFilters = function(filters) {
            for (var i = 0; i < filters.length; i++) {
                this.addFilter(filters[i]);
            }
        } // end function addFilters

    /**
     * Add filter expression
     * @param {array} expression - array structure describing search expression
     */
    this.addFilterExpression = function(expression) {
        this.filters.push(JSON.parse(expression));
    }

    /**
     * Set filter expression - Replaces any existing filters
     * @param {array} expression - array structure describing search expression
     */
    this.setFilter = function(filterArray) {
        this.filters = filterArray;
    }
    
    /**
     * Set the type of record to search for
     * @param {string} type - internalid of record type to search for
     */
    this.setRecordType = function(type) {
            this.recordType = type;
        } // end function setRecordType


    /**
     * Use an existing saved search as starting point for this search
     * @param {string} internalid - internalid of existing saved search
     */
    this.useSavedSearch = function(internalid) {
        if (!isNullOrEmpty(internalid)) {
            this.internalId = internalid;
            // If internal id of a saved search is provided, load that saved search
            this.savedsearch = nlapiLoadSearch(this.recordType, this.internalId);
        }
    } // end function useSavedSearch


    /**
     * Return search results as a nlobjSearchResult object
     * @param {string} recordtype - Optional NetSuite recordtype (internalid)
     */
    this.getResults = function(recordtype) {
            var results = [];
            if (recordtype != null && recordtype != "") {
                this.recordType = recordtype;
            }
            if (this.internalId != null) {
                // If internal id of a saved search is provided, load that saved search
                var savedsearch = nlapiLoadSearch(this.recordType, this.internalId);
                // Add new filters to saved search filters
                var newfilters = savedsearch.getFilters().concat(this.filters);
                // If existing columns in saved search should not be use, replace then
                var newcolumns = [];
                if (this.noSavedColumns) {
                    savedsearch.setColumns(this.columns);
                    newcolumns = this.columns;
                } else {
                    // Add new columns to saved search columns
                    newcolumns = savedsearch.getColumns().concat(this.columns);
                }
                // Perform the search
                var newsearch = nlapiCreateSearch(savedsearch.getSearchType(), newfilters, newcolumns);
                // 
            } else {
                // Otherwise build the search ad-hoc and set columns and filters
                var newsearch = nlapiCreateSearch(this.recordType, this.filters, this.columns);
            }
            var resultset = newsearch.runSearch();
            // Loop through the search result set 900 results at a time and build an array
            // of results. This way the search can return more than 1000 records.
            var searchid = 0;
            do {
                var resultslice = resultset.getResults(searchid, searchid + 900);
                for (var rs in resultslice) {
                    results.push(resultslice[rs]);
                    searchid++;
                }
            } while (resultslice != null && resultslice != undefined && resultslice.length >= 900);
            return results;

        } // end function getResults

} // end class search
0 Comments

Load and Modify External File in NetSuite

When building a suitelet in NetSuite you can either inject HTML, CSS and Javascript in a field, or generate a full HTML page and render it into the suitelet. No matter which method you use, you normally have to write line after line of SuiteScript code where you build the HTML using string concatenation. This is not only difficult and tedious to write, making sure you match all the single and double quotes and semi colons, it also makes the code much harder to maintain.

What if you could just create a regular HTML file, put it in the File Cabinet and then render it into a suitelet? And what if you could use one line of code to inject values from NetSuite in the correct place in the HTML? This could be search results from the use of my search function.

That is what the function looks like:

/**
 * Load file from NetSuite File Cabinet and replace placeholders with actual values
 * 
 * Version    Date            Author           Remarks
 * 1.00       07 Nov 2016     kmartinsson      Created class/function
 * 1.01       08 Nov 2016     kmartinsson      Consolidated setValue and setHTML into
 *                                             one method and added noEscape parameter
 */
// ***** Read and process external file, replacing placeholders with proper values *****
function ExternalFile(filename) {
   //Get the file by path/name, can also be internal id
   var fileId = filename;
   // Load file content and store data
   var file = nlapiLoadFile(fileId);
   var data = file.getValue();
   this.content = data;

   this.setValue = function(placeholder, value, noEscape) {
      // Check if noEscape is passed, if it is and if true then don't escape value.
      // This is needed when value contains HTML code.
      if (typeof noEscape == "undefined") {
         this.content = this.content.replace(new RegExp(placeholder, 'g'), nlapiEscapeXML(value));
      } else {
         if (noEscape == true) {
            this.content = this.content.replace(new RegExp(placeholder, 'g'), value);
         } else {
            this.content = this.content.replace(new RegExp(placeholder, 'g'), nlapiEscapeXML(value));
         }
      }
   }

   this.getContent = function() {
      return this.content;
   }
}

Reference this function in your Suitescript 1.0 code like this:

// Load extrenal HTML file
var html = new ExternalFile("SuiteScripts/BinTransfer.html");
// Insert NetSuite URL for CSS files
var cssFileName = nlapiLoadFile("SuiteScripts/css/drop-shadow.css").getURL();
html.setValue("%cssDropShadow%", cssFileName, true);
cssFileName = nlapiLoadFile("SuiteScripts/css/animate.css").getURL();
html.setValue("%cssAnimate%", cssFileName, true);
// Insert array returned from a search
html.setValue("%binarray%", JSON.stringify(binArray), true);
// Replace placeholders with values
html.setValue("%showAll%", "false");
html.setValue("%company%", companyName);

The last (optional) argument “noEscape” decides if the value should be URL encoded (false/omitted) or not (true) using the function nlapiEscapeXML(). In most cases you don’t need to specify this argument, but if you need to pass HTML or other code into the function you need to set it to true to avoid the code being modified.

As you can see in my example above, I get the NetSuite URL for my CSS files as well. Instead of hard coding the NetSuite URL into the HTML page, I calculate it and insert it when the page is loaded. Not only does it make the page easier to read the code, it also makes it much easier to maintain.

This is a snippet from the HTML file:

<!-- Load plugins/drop-shadow.css from File Cabinet -->
<link href="%cssDropShadow%" rel="stylesheet">
<!-- Load bootstrap-notify.js and animate.css from File Cabinet -->
<script src="%jsBootstrapNotify%"></script>
<link href="%cssAnimate%" rel="stylesheet">

Much easier to read!

Thanks to this little function I have built suitelets who does nothing but load a traditional HTML file with Bootstrap, jQuery, even jQuery Mobile for mobile devices. The page contains Javascript/jQuery that call RESTlest to read and write data. Now I can build suitelets with all the power I have in traditional web development at the same time as I get access to the full NetSuite functionality!

This can also be used to generate XML files to convert into PDF.

Happy coding!

 

0 Comments

Easy NetSuite Search

In an attempt to expand my knowledge to other platforms than Notes and Domino, I have now been working with NetSuite for a number of months. I have mainly been working with the ERP part of the cloud based system.

The language used is called SuiteScript, and it is Javascript with a NetSuite-specific API to work directly with the databases. Knowing Javascript makes it easy to get started, just like knowing Visual Basic makes it easy to learn Lotusscript. And just like with Lotusscript, you have to learn the NetSuite specific functions.

Since I like my code clean and easy to read (which will make future maintenance easier), I have created a number of functions to encapsulate NetSuite functionality.

The first one I created was to search the database. The search in NetSuite is done by defining the columns (i.e. fields) to return as an array of search column objects. Then an array of search filters is created, and finally the search function is called, specifying what record type to search and passing the two arrays to it as well. This is a lot of code, and with several searching in a script it can be very repetetive, not to mention hard to read.

Here is an example of a traditional NetSuite search:

var filters = [];
filters.push(new nlobjSearchFilter('item', null, 'anyof', item));
filters.push(new nlobjSearchFilter('location', null, 'noneof', '@NONE@'));
var columns = [];
columns.push(new nlobjSearchColumn('internalid'));
columns.push(new nlobjSearchColumn('trandate').setSort());
columns.push(new nlobjSearchColumn('location'));
var search = nlapiSearchRecord('workorder', '', filters, columns);

Using my function, the code wold be simplified to this:

var search = new Search('workorder');
search.addFilter('item', null, 'anyof', item);
search.addFilter('location', null, 'noneof', '@NONE@');
search.addColumn('internalid'));
search.addColumn('trandate',true);  // Sort on this column
search.addColumn('location');
var search = search.getResults();

The function also support saved searches. Simply add the following line:

search.useSavedSearch('custsearch123');

There is a limitation in SuiteScript so that a maximum of 1000 records can be returned by a normal search. There is a trick to bypass this, but it requires some extra coding. So I thought why not add this into the function as default? So I did.

Below is the code for the search function. I usually put it in a separate file and reference it as a library in the scripts where I want to use it. This first version does not support more advanced functionality like formulas in the filters. But for most searches this function will be usable.

/**
 * Module Description
 * 
 * Version    Date            Author           Remarks
 * 1.00       11 Nov 2016     kmartinsson
 * 1.05       27 May 2017     kmartinsson      Added support for record type in constructor
 *
 */
//***** Encapsulate search functionality *****
function Search(recordtype) {
   this.columns = [];
   this.filters = [];
   // If record type/ID is passed, no need to set it later
   if (recordtype == null || recordtype == "") {
      this.recordType = null;
   } else {
      this.recordType = recordtype;
   }
   // Set internal id of saved search to null
   this.internalId = null;
   // *** Set array of column names to return
   this.setColumns = function(columnArray) {
      for (var i = 0; i < columnArray.length; i++) { // Check if we have an array, used for joins and sorts if (columnArray[i].isArray()) { // We have an array. Now we need to figure out what it contains if (columnArray[i].length > 2) {
               // We have 3 values, must be id, join and sort
               this.addColumnJoined(columnArray[i][0], columnArray[i][1], columnArray[i][2]);
            } else {
               // We have 2 values, can be id + join or id + sort. Let's find out!
               if (typeof(columnArray[i][1]) == "boolean") {
                  // Boolean value in second parameter means sorting
                  this.addColumn(columnArray[i][0], columnArray[i][1]);
               } else {
                  // Not boolean means a join
                  this.addColumnJoined(columnArray[i][0], columnArray[i][1]);
               }
            }
         } else {
            this.addColumn(columnArray[i]);
         }
      }
   } // end function setColumns

   // *** Add column to existing array of column names
   this.addColumn = function(columnName, sorted) {
      if (sorted == undefined || sorted == null) {
         this.columns.push(new nlobjSearchColumn(columnName));
      } else {
         if (sorted) {
            this.columns.push(new nlobjSearchColumn(columnName)).setSort(true);
         } else {
            this.columns.push(new nlobjSearchColumn(columnName));
         }
      }
   } // end function addColumn

   // *** Add joined column with to existing array of column names
   this.addColumnJoined = function(columnName, joinName, sorted) {
      if (sorted == undefined || sorted == null) {
         this.columns.push(new nlobjSearchColumn(columnName, joinName));
      } else {
         if (sorted) {
            this.columns.push(new nlobjSearchColumn(columnName, joinName)).setSort(true);
         } else {
            this.columns.push(new nlobjSearchColumn(columnName, joinName));
         }
      }
   } // end function addColumnJoined

   // *** Add a filter for the search results
   this.addFilter = function(fieldId, fieldJoinId, operator, value) {
      this.filters.push(new nlobjSearchFilter(fieldId, fieldJoinId, operator, value));
   } // end function addFilter

   // *** Set the type of record to search for (default is null)
   this.setRecordType = function(recordType) {
      this.recordType = recordType;
   } // end function setRecordType

   // *** Set the saved search to use (internal id, default is null)
   this.useSavedSearch = function(internalId) {
      this.internalId = internalId;
   } // end function useSavedSearch

   // *** Return search results, supports >1000 results through nlapiCreateSearch
   this.getResults = function() {
      var results = [];
      if (this.internalId != null) {
         // If internal id of a saved search is provided, load 
         // that saved search and create a new search based on it
         var savedsearch = nlapiLoadSearch(this.recordType, this.internalId);
         // Add new filters to saved filters
         var newfilters = savedsearch.getFilters().concat(this.filters);
         // Add new columns to saved columns
         var newcolumns = savedsearch.getColumns().concat(this.columns);
         // Perform the search
         var newsearch = nlapiCreateSearch(savedsearch.getSearchType(), newfilters, newcolumns);
         // 
      } else {
         // Otherwise build the search ad-hoc and set columns and filters
         var newsearch = nlapiCreateSearch(this.recordType, this.filters, this.columns);
      }
      var resultset = newsearch.runSearch();
      // Loop through the search result set and build a result array
      // so the search can return more than 1000 records.
      var searchid = 0;
      do {
         var resultslice = resultset.getResults(searchid, searchid + 800);
         for (var rs in resultslice) {
            results.push(resultslice[rs]);
            searchid++;
         }
      } while (resultslice.length >= 800);
      return results;

   } // end function getResults

} // end class search

 

1 Comment

End of content

No more pages to load