Advertisement
borncorp

Netsuite Highcharts Suitelet.js

Mar 2nd, 2018
449
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. *   Suitelet hack to load a custom html page within a Netsuite Form. Created by Adolfo Garza (borncorp)
  3. */
  4.  
  5. var ENCODEMODULE, RUNTIMEMODULE, UIMODULE, URLMODULE, DEPLOYMENT_URL; //I like loading my modules as globals so I can access them whenever I want
  6.  
  7. /**
  8.  *@NApiVersion 2.x
  9.  *@NScriptType Suitelet
  10.  *@NModuleScope Public
  11.  */
  12. define(["N/encode", "N/runtime", 'N/ui/serverWidget', 'N/url'], runSuitelet);
  13.  
  14. //********************** MAIN FUNCTION **********************
  15. function runSuitelet(encode, runtime, ui, url){
  16.     ENCODEMODULE= encode;
  17.     RUNTIMEMODULE= runtime;
  18.     UIMODULE = ui;
  19.     URLMODULE = url;
  20.    
  21.     var returnObj = {};
  22.     returnObj.onRequest = execute;
  23.     return returnObj;
  24. }
  25.  
  26. function execute(context){
  27.     DEPLOYMENT_URL = getDeploymentURL();
  28.    
  29.     try {
  30.         if (context.request.method == 'GET') {
  31.             var form = getInjectableForm();
  32.             context.response.writePage(form);
  33.             return;
  34.         }
  35.        
  36.         return;
  37.     } catch (e) {
  38.         log.error("ERROR", e.toString());
  39.         context.response.write(e.toString());
  40.     }
  41.    
  42.     return;
  43. }
  44.  
  45. function getInjectableForm(){
  46.     //*********** Create Form ***********
  47.     var form = UIMODULE.createForm({
  48.             title: ' '
  49.         });
  50.     var bodyAreaField = form.addField({
  51.         id : 'custpage_bodyareafield',
  52.         type : UIMODULE.FieldType.INLINEHTML,
  53.         label : 'Body Area Field'
  54.     });
  55.  
  56.     //*********** Prepare HTML and scripts to Inject ***********
  57.     var body = getBody();
  58.     clientCode = clientCode.replace('$PAGEBODY$', body).replace('$DEPLOYMENT_URL$', DEPLOYMENT_URL);
  59.     var base64ClientCode = toBase64(clientCode);
  60.     var scriptToInject = 'console.log(\'Added bottom script element\');';
  61.     scriptToInject += "eval( atob(\'" + base64ClientCode + "\') );";
  62.  
  63.     //*********** Injecting HTML and scripts into an the Body Area Field ***********
  64.     bodyAreaField.defaultValue = '<script>var script = document.createElement(\'script\');script.setAttribute(\'type\', \'text/javascript\');script.appendChild(document.createTextNode(\"' + scriptToInject + '\" ));document.body.appendChild(script);</script>';
  65.     return form;
  66. }
  67.  
  68. /**
  69.  * Gets HTML that will be injected into the Suitelet. Use an HTML minifier tool to achieve this one string output.
  70.  * @returns {string} HTML String
  71.  */
  72. function getBody(){
  73.     return "<div style='width:100%' class='container-fluid'> " +
  74.         //Replace with your HTML
  75.         "<div id='container' style='min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto'></div>"
  76.        
  77.         + "</div>";
  78. }
  79.  
  80. var clientCode  = 'run(); ' + function run() {
  81.     console.log('Running client code');
  82.    
  83.     //*********** GLOBAL VARIABLES ***********
  84.     $ = jQuery;
  85.     DEPLOYMENT_URL = '$DEPLOYMENT_URL$';
  86.     THISURL = $(location).attr('href');
  87.    
  88.     //*********** After DOM loads run this: ***********
  89.     $(function() {
  90.         injectHeaderScripts(); //Loads Libraries that will be placed on header (Optional)
  91.         $(window).bind('load', injectHTML); //Replaces Suitelet's body with custom HTML once the window has fully loaded(Required)
  92.         waitForLibraries(['Highcharts'], runCustomFunctions); //Runs additional logic after required libraries have loaded (Optional)
  93.        
  94.     });
  95.    
  96.     return;
  97.     //*********** HELPER FUNCTIONS ***********
  98.    
  99.    
  100.     /**
  101.      * Loads Libraries that will be placed on header (Optional)
  102.      */
  103.     function injectHeaderScripts(){
  104.         console.log('loadHeaderLibraries START');
  105.         loadjscssfile( "https://code.jquery.com/jquery-3.1.1.min.js" );
  106.         loadjscssfile( "https://code.highcharts.com/highcharts.js");
  107.         loadjscssfile("https://code.highcharts.com/modules/exporting.js");
  108.         console.log('loadHeaderLibraries END');
  109.  
  110.         //*********** HELPER FUNCTION ***********
  111.          function loadjscssfile(filename) {
  112.             var filetype = filename.substr(filename.lastIndexOf('.') + 1).toLowerCase();
  113.             if (filetype == "js") { //if filename is a external JavaScript file
  114.                 var fileref = document.createElement('script')
  115.                 fileref.setAttribute("type", "text/javascript")
  116.                 fileref.setAttribute("src", filename)
  117.             } else if (filetype == "css") { //if filename is an external CSS file
  118.                 var fileref = document.createElement("link")
  119.                 fileref.setAttribute("rel", "stylesheet")
  120.                 fileref.setAttribute("type", "text/css")
  121.                 fileref.setAttribute("href", filename)
  122.             }
  123.             if (typeof fileref != "undefined"){
  124.                 document.getElementsByTagName("head")[0].appendChild(fileref)
  125.             }
  126.             console.log(filename + ' plugin loaded');
  127.         }
  128.     }
  129.  
  130.     function runCustomFunctions() {
  131.         console.log('clientFunctions START');
  132.         var DEPLOYMENT_URL = '$DEPLOYMENT_URL$';
  133.         buildChart();
  134.        
  135.         function buildChart(){
  136.  
  137.             // Build the chart
  138.             Highcharts.chart('container', {
  139.                 chart: {
  140.                     plotBackgroundColor: null,
  141.                     plotBorderWidth: null,
  142.                     plotShadow: false,
  143.                     type: 'pie'
  144.                 },
  145.                 title: {
  146.                     text: 'Browser market shares January, 2015 to May, 2015'
  147.                 },
  148.                 tooltip: {
  149.                     pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
  150.                 },
  151.                 plotOptions: {
  152.                     pie: {
  153.                         allowPointSelect: true,
  154.                         cursor: 'pointer',
  155.                         dataLabels: {
  156.                             enabled: false
  157.                         },
  158.                         showInLegend: true
  159.                     }
  160.                 },
  161.                 series: [{
  162.                     name: 'Brands',
  163.                     colorByPoint: true,
  164.                     data: [{
  165.                         name: 'Microsoft Internet Explorer',
  166.                         y: 56.33
  167.                     }, {
  168.                         name: 'Chrome',
  169.                         y: 24.03,
  170.                         sliced: true,
  171.                         selected: true
  172.                     }, {
  173.                         name: 'Firefox',
  174.                         y: 10.38
  175.                     }, {
  176.                         name: 'Safari',
  177.                         y: 4.77
  178.                     }, {
  179.                         name: 'Opera',
  180.                         y: 0.91
  181.                     }, {
  182.                         name: 'Proprietary or Undetectable',
  183.                         y: 0.2
  184.                     }]
  185.                 }]
  186.             });
  187.         }
  188.     }
  189.    
  190.     function waitForLibraries(libraries, functionToRun){
  191.         var loadedLibraries = 0;
  192.         for (var i in libraries) {
  193.             var library = libraries[i];
  194.             if(eval('typeof ' + library)!='undefined'){
  195.                 loadedLibraries++;
  196.             }
  197.         }
  198.        
  199.         window.setTimeout(function(){
  200.             if(loadedLibraries != libraries.length){
  201.                 waitForLibraries(libraries, functionToRun);
  202.             } else{
  203.                 console.log(library + ' loaded');
  204.                 functionToRun();
  205.             }
  206.           },500);
  207.     }
  208.    
  209.     function injectHTML(){
  210.         var html = ' $PAGEBODY$ '; //This string will be replaced by the Suitelet
  211.         jQuery("#main_form")[0].outerHTML = html;
  212.     }
  213. }
  214.  
  215. /**
  216.  * Gets deployment URL. Useful for sending POST requests to this same suitelet.
  217.  * @returns {string} Deployment URL
  218.  */
  219. function getDeploymentURL(){
  220.     return URLMODULE.resolveScript({
  221.         scriptId: RUNTIMEMODULE.getCurrentScript().id,
  222.         deploymentId: RUNTIMEMODULE.getCurrentScript().deploymentId,
  223.         returnExternalUrl: false,
  224.     });
  225. }
  226.  
  227. function toBase64(stringInput){
  228.     return ENCODEMODULE.convert({
  229.         string: stringInput,
  230.         inputEncoding: ENCODEMODULE.Encoding.UTF_8,
  231.         outputEncoding: ENCODEMODULE.Encoding.BASE_64
  232.     });
  233. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement