Linking System Notes to Transaction Lines

I’m still scratching my head over this one. How can you link system notes to transaction line items? I found it’s possible, but not intuitive.

Since discovering SuiteQL, I’ve tried to use it instead of saved searches. The advantage is it allows multi-level joins, where saved searches only allow single level (one and only one level) of joins.

Querying system notes in SuiteQL looks something like this.

    select as tran_id
        , t.tranid as tran_num
        , case n.type when 2 then 'Set' 
            when 4 then 'Change' 
            else to_char(n.type) 
          end as change_type
        , case n.context 
            when 'SLT' then 'Script (Restlet)' 
            when 'UIF' then 'User Interface' 
            when 'WST' then 'Web Store' 
            else n.context 
          end as change_context 
        , n.field
        , n.oldvalue
        , n.newvalue
    from systemnote n
        inner join transaction t 
        on = n.recordid 
        and t.type = 'SalesOrd' 
        and > '10/23/2022'
        and BUILTIN.DF(t.status) in
            'Sales Order : Pending Fulfillment',
            'Sales Order : Pending Billing/Partially Fulfilled',
            'Sales Order : Partially Fulfilled'
    where 1=1
    and n.oldvalue != n.newvalue
    and n.type in (2,4) -- Set or Changed
) as dtbl
order by tran_num, desc

It works great, but has the limitation of not being able to link the system note directly to the transaction line. I searched to the end of the internet, and I don’t see anyone who’s solved this problem, not even Tim Dietrich, the PL/SQL Guru. However, the relationship exists in a saved search. Marty Zigman points this out in one of his blog articles. Thank you, both of you!

Of course you can always use SuiteQL to query your saved search. However, it sure would be nice if NetSuite shared the secret foreign key relationship between transaction lines and system notes in their Schema Browser. I noticed some views described in the Schema Browser “Connect Browser” tab, but I could not translate that into anything that worked in PL/SQL.

If you know more about this than I do, please share it with the rest of us. Respond to this post and I’ll include it and credit you.

Calling Magento 2 API from NetSuite

I needed a way to move data from NetSuite to Magento. Here is a simple example that creates an attribute set in Magento. This example runs in a NetSuite debugger session. It is written in SuiteScript 2.1.

To create your token in Magento. Login in as admin. Go to
System >> Integrations >> Add New Integration

Once you’ve added your integration, Magento will create an Access Token. This is your Bearer Token.

Use the Bearer Token in your header. Refer to the Magento 2 Admin REST endpoint’s documentation to correctly build the body. Here is example code.

    (https) => {

        var header = {
            'Authorization': 'Bearer [your token here]',
            'Accept': 'application/json',
            'Content-Type': 'application/json; charset=utf-8'

        var body = JSON.stringify(
                "attributeSet": {
                    "attribute_set_name": "[Your attribute set name here]"
                "skeletonId": 4
            url: encodeURI('https://[Your Magento base domain here]/rest/default/V1/products/attribute-sets'),
            body: body,
            headers: header
            .then(function (response) {
                    title: 'Response',
                    details: response
            .catch(function onRejected(reason) {
                    title: 'Invalid Request: ',
                    details: reason


Calculated Fields – A Checklist

I needed away to roll up entries from a custom table to display as a single value under an item record. What a meticulous and tedious pain this was. I can’t think of any more applicable adjectives, or I’d use them. I needed a checklist!

To be fair, NetSuite is great about letting you create a saved search to display summary results in what they call a “Calculated Custom Field”. It displays as if the value was actually stored with the entity, but it’s not, it’s built on the fly. In my case, I needed to show the SuiteCommerce Advanced base image from the list of images associated with any item.

The task at hand presented multiple problems. I’ll spare you the details of the first problem, which was an inability to write a saved search listing only images associated with a single item. I learned this is not supported in NetSuite, so I had to built my own custom table. Note: I used a SuiteQL query against the ItemImage table (Thank you Tim Dietrich) along with a Map/Reduce script. This let me build a copy of the ItemImage table which WAS accessible from a Saved Search.

This brings me to the list of all quirky things required show the one file name under an item. Here is that list!

  • Identify the standard or custom table you wish to pull your value from. In my case it was a custom table called “Item Images”.
  • Create a saved search against your source table.
    • Make your search public.
    • Add any criteria you like. In my case it was “Base Image” = true.
    • Include the entity type as the first field in your results.
    • Make sure the results are “Summary Results”. In my case I used MINIMUM File Name
    • Create an Available filter that limits results to a single entity and make sure to check “Show in Filter Region”.
Add any criteria you like
The first field in results should be the entity, or in my case, Item. Make sure the results are “Summary Results”. I don’t believe you can select “Group” under “Summary Type”. I chose “Minimum” and it works!
Set an available filter that matches your entity type. Again, in my case, it was Item. Be sure to check “Show in Filter Region.”
  • Create a new Custom Field.
    • Pick the field type that is correct for the rolled up value you will display from your saved search.
    • Uncheck “Store Value”. This value will not be stored, but calculated on the fly.
    • Under “Validation and Defaulting”, select the saved search your just created.
Select the proper field type. Uncheck “Store Value” and associate your calculated field with your new saved search.
Be sure to include the parent record reference in your custom table.

Tying up lose ends, I’ll show the definition of my custom table.

Be sure your entity field is also set to “Record is Parent”.

Hopefully, in the future, if we all follow this checklist, we’ll be thinking happy thoughts about NetSuite and not letting fly any uncomplimentary adjectives. Cheers!

Example: Magento API from Node.js with Axios

I feel like every time I post, the answer is simple, but the documentation is terrible. The task: Call Magento API from a JavaScript program in Node.js.

  • Login to your Magento Admin account at https://%5Byour-domain%5D/admin
  • Create an integration: System >> Integrations >> Add New Intgration
  • Copy the Access Token for use later in the header of your get request

Here is the code in a format you can cut and paste.

const axios = require('axios').default;

    method: 'get',
    url: 'https://[My URL Here]/rest/default/V1/products' +
    responseType: 'text/json',
    timeout: 1000,
    headers: {'authorization': 'Bearer [My Access Token Here]'}
    .then(function (response) {
    .catch(function(err) {
        function() {


ES6 got me! The same code in SuiteScript 2.0 passes all syntax checks, but when converted to SuiteScript 2.1 fails to upload to NetSuite. What the heck? I’m not even going to try to explain this. I’m just going to show the problem and the fix with examples.

This PASSES syntax checks but FAILS to upload to NetSuite:

This PASSES syntax checks and SUCCEEDS to upload to NetSuite:

The only difference is moving the reference to N/format inside the main function. Apparently this is something the NetSuite JavaScript compiler frowns upon, but the vsCode syntax checker is OK with.

My complaint is with the NetSuite error message. It’s ugly! I formatted it here to make easier to parse with the eyes. If you are reading this, you already know it comes out as a jumbled mess on the screen. Argh!

Here is the actual text you’d see on the screen, again I formatted it to make it readable. I’m including it in text to help find this article if you experience this error. It’s exactly what you see above.

Fail to evaluate script:
    "type": "error.SuiteScriptError",
    "message": "All SuiteScript API Modules are unavailable while executing your define callback.",
    "stack": [
        "Error\n at /SuiteScripts/Logic/your_suitelet_here.js:24:32"
    "cause": {
        "type": "internal error",
        "details": "All SuiteScript API Modules are unavailable while executing your define callback.",
        "userEvent": null,
        "stackTrace": [
            "Error\n at /SuiteScripts/your_suitelet_here.js:24:32"
        "notifyOff": false
    "id": "",
    "notifyOff": false,
    "userFacing": true

GitHub Local Repository on Microsoft OneDrive – I’m out!

I’m a developer who bounces back and forth between working at the office and working from home. I have a full developer setup in both places. I know… “First world problems!” Because I work in the cloud, publishing JavaScript files to NetSuite, I noticed files were checking in and out of GitHub on both systems, but did not match what I last uploaded to NetSuite. What was going on?

Using remote access from home to my office, I did a couple of tests.

  • I trued up source code at home, in the office, and in NetSuite. (WinMerge will compare files in 3 directories).
  • I modified one JavaScript file at home and checked it in.
  • I pushed changes to the remote repository on GitHub.
  • I pulled from my office computer. Changes came through.
  • I modified the file again in the office, checked back in and pushed to remote repository.
  • Pulled again from home. All was fine. Changes were there.
  • I came back a few minutes later on the same home computer and changes were gone!!!!!
  • Both systems were saying they were fully up to date with the same repository on GitHub (remote).
  • The same file on home and office were not in sync.
  • I deleted the local repository on my office computer, and cloned it again outside of OneDrive.
  • Interestingly enough, my home computer then prompted with a pull request and proceeded to update the file which had been out of sync, and replaced it with the correct version. Again, this was my home computer! Crazy.

This was such an odd situation, I thought I’d document it. I’ll add, and I have no real understanding of this, my new rule is, “I’m already saving updated source code in the remote repository. What again is the point of OneDrive? So I’m now personally steering clear of OneDrive for my local repositories.” I don’t need any more hassles! I have enough writing software for a living.

Avalara’s Avatax Bundle in NetSuite – Demystified (Developer Notes)

I’ve been asked to investigate why our NetSuite system is making so many calls to Avalara to calculate tax. Each call costs, and we make an inordinate number of calls. These notes are mainly for me, but I’m happy to share. If anything in this post is incorrect, please feel free to comment. This is not intended to disparage Avalara, it’s simply notes about how to manage it.

First, I’ve determined that any time transactions (Estimates, Sales Orders and possibly Invoices) are saved, a web service call is made to Avalara to calculate tax. Cha Ching!

Second, and to Avalara’s credit, they offer configuration options for turning off the tax calculation on each type of transaction. So if you don’t need tax on an estimate, just turn it off. However, if you convert an estimate to a sales order, you may want the totals to match, and that requires tax.

Third, if nothing affecting the tax calculation changes, you would expect Avalara to skip the web service call. It does not! Consider this, someone copies an estimate/quote to make a revision. Nothing changes. The shipping address and all items in the quote remain 100% the same as the copied transaction. However, at that instant, the newly created copy isn’t saved until the user clicks Save, Cha Ching! If anything is changed in the transaction, like assigning a second sales rep, anything, Cha Ching! And so on, and so on, and so on. Cha Ching.

Now, here are some notes regarding how to track the web services calls. Open a transaction and save it, without changing anything. NetSuite will prompt to confirm. Say yes. Next, view the AvaTax tab. You’ll see something like this. Check the timestamps, it confirms you just made a webservice call to Avalara! If you click “More…”, you’ll see the response includes your calculated tax amount.

Developer Notes:

Avalara is installed as a bundle and associated scripts live in the file cabinet in “/SuiteBundles/Bundle 1894”.

AvaTax got an upgrade from SuiteScript 1.0 to SuiteScript 2.0 with AvaTax 7.6. If you have not upgraded your Avalara bundle in some time, you should. All code from 7.6 on which affects web services calls has been upgraded and moved to new libraries.

Reviewing Avalara code:

It’s an easy task to browse to “/SuiteBundles/Bundle 1894” and download the entire directly. It comes down as a zipped file which can be expanded and checked into source control.

In AVA_CLI_Transaction.js (the naming conventions make it very easy to find the client-side scripts that handle the Save and Calculate Tax buttons), you’ll find AVA_TransactionSave() and AVA_CalcuateOnDemand() functions. Because they are client-side calls you can evaluate these using Chrome Developer Tools.

Ultimately, calls wind up at TaxLibrary.js AVA_CalculateTax(). It is important to note that this library is not available in VIEW mode, but only in EDIT mode when setting stops in Chrome Developer tools.

And finally, here is where I stopped my research prior to writing this post, you can make a direct call to AVA_CalculateTax() from the console window of Chrome Developer Tools. It looks like this. Open a transaction in EDIT mode. Let it fully load. Then paste this into the console window of Chrome Dev Tools. You can step through the entire process of updating the tax amount, including the web services call.

Snapshot of vsCode sample call to calculate tax
require(['N/currentRecord', '/SuiteBundles/Bundle 1894/utility/AVA_TaxLibrary.js'],
    function (currentRecord, tax_lib) {
        var cRecord = currentRecord.get();
        var connectionStartTime = new Date();
        tax_lib.AVA_CalculateTaxOnDemand(cRecord, connectionStartTime);

This call appears to calculate tax and update your transation (I didn’t actually confirm that the tax amount has been updated). And, it does not log the web services call in the AvaTax tab. That remains to be investigated.

It took time to get this far and I don’t want to lose my research. Thus, this blog article. If anyone picks up here, send me a comment and perhaps you can return the favor by saving me some time. Thanks!

NetSuite Email Capture Example

I wish I’d known this much sooner. NetSuite’s email capture script is a great way to incorporate incoming email directly into NetSuite.

First, my company uses Outlook 365 in the cloud. We set a rule to forward incoming email to a particular address on to NetSuite. The mail remains in the original mailbox in Outlook 365, but also arrives as though sent by the original sender in NetSuite. When it arrives in NetSuite, a custom Email Capture script reads the message, records all the detail such as FROM, TO, SUBJECT, BODY and all ATTACHMENTS into a custom record type. That record type is included in a saved search, which is then displayed as a shared dashlet, accessed by an entire department.

Individuals in the department assign themselves to the incoming emails and set a status letting their colleagues know they have it. That begins a workflow in NetSuite. It’s really slick, and really easy to implement.

First, here is a sample script. It’s written in SuiteScript 1.0. I was unable to find documentation on writing this in any other version of SuiteScript. Feel free to add comments to this article if I’ve missed something.

function process(email) {

    const IS_PRODUCTION = true;

    const valid_types = [

    var fromAddress = email.getFrom();
    nlapiLogExecution('DEBUG', 'Email - from: ' + fromAddress.getName() + ', ' + fromAddress.getEmail());
    nlapiLogExecution('DEBUG', 'subject - ' + email.getSubject());

    var newRec = nlapiCreateRecord('customrecord_xxxxxxxxxxxxxxxxxxxxxxxxxxxx');
    newRec.setFieldValue('custrecord_xxxxxxxxxx', fromAddress.getName());
    newRec.setFieldValue('custrecord_xxxxxxxxxx', fromAddress.getEmail());
    newRec.setFieldValue('custrecord_xxxxxxxxxx', email.getSubject());
    newRec.setFieldValue('custrecord_xxxxxxxxxx', email.getTextBody());
    var newRec_id = nlapiSubmitRecord(newRec, true);

    var attachments = email.getAttachments();

    // This variable is here in case you wanted to add notes about attachments.
    // it is currently unused. 
    var processing_notes = '';

    for (var indexAtt in attachments) {
        var attachment = attachments[indexAtt];
        nlapiLogExecution('DEBUG', 'Attachment: ' + attachment.getName() + ', ' + attachment.getType());

        // If the file name does not have an extension, skip it
        var fileName = attachment.getName();
        if (fileName.indexOf('.') <= 0) continue;

        // add a unique suffix to the file name, but leave the extension as-is
        var fileArray = fileName.split('.');
        var newName = '';
        for (var i = 0; i < fileArray.length; i++) {
            if (i == fileArray.length - 1) {
                newName += ('_' + (new Date().valueOf()).toString());
            newName += ('.' + fileArray[i]);
        // Lookup the file type to see if it is supported, else save as PLAINTEXT
        // This really won't affect being able to open and download the file.
        // It only affects filtering files by type.
        var file_type = attachment.getType().toUpperCase();
        if (valid_types.filter(function (p) { return p == file_type }).length == 0) {
            file_type = 'PLAINTEXT';  // Import nonrecognized file types as Other Binary File

        var file = nlapiCreateFile(newName, file_type, attachment.getValue());

        // Save the file under a selected folder in the file cabinet
        file.setFolder(1111111111); //Internal ID of folder to hold imported attachments
        var file_id = nlapiSubmitFile(file);

        // Attach the file to a custom record type
        nlapiAttachRecord('file', file_id, 'customrecord_xxxxxxxxxxxxxxxxxxxxxxxxxxxx', newRec_id);

    // here is where you'd include notes about attachments, perhaps those that were erroniously
    // saved under the PLAINTEXT type.
    nlapiSubmitField('customrecord_xxxxxxxxxxxxxxxxxxxxxxxxxxxx', newRec_id, 'custrecord_xxxxxxxxxx', processing_notes);

Once you upload your script to the file cabinet, go to Customizations >> Plug-Ins >> Plug-In Implementations >> New

Customizations >> Plug-Ins >> Plug-In Implementations

Select your script. Next, look for it under Manage Plug-Ins.

Your new Email Capture Script shows up here along with the associated NetSuite email address. Be sure to activate your script by checking the box next to your Plug-In.

To test, click the link. It should open your default email client (in my case it is Outlook 365) and address the mail to this address. Send your test message and in a couple of seconds, it will be picked up and processed by the new script. It’s fast!

Once you are happy with your script, set Outlook 365 (the server-side in the cloud) to forward to this address.

It is important to understand that NetSuite will only allow your script to upload known file types. That’s why I’ve supplied an array of file types in the code. However, NetSuite will accept any file of any type as long as you fib and say it’s a known file type. So, my code tries to match the type with a known NetSuite file type. If there is no match, I tell NetSuite the file is type PLAINTEXT. It allows the file to be uploaded and saved. It does not affect downloading the file. It still comes down and is opened based on the file’s extension. The only thing it affects is your ability to filter files. In my case, I’ll have a lot of files of type PLAINTEXT that are actually some other format. And… I can live with that.

The other gotcha is NetSuite thinks files of same name are the same file. So my code adds a suffix based on an integer time stamp. So two files of the same name Kevin.text and Kevin.text will be saved as Kevin_[big unique integer number].text. When these files get attached to two separate custom records, the files are not be overwritten.

And that should be all you need to know about that!

jsTree Control with Multiselect – DblClick to toggle, Click to select

As with most things, this turned out to be a hard problem with a simple solution. I was using jsTree to display a product catalog. Originally, I did not implement multiselect. So when a node in the tree was double clicked, it expanded the node. However, when I went to multiselect, double clicking a node expanded it, but also selected it and every child node under it. I needed to decouple those two behaviors.

Double click to expand. Single click on the checkbox to select.

Here is the code in JSFiddle:
Double click to expand the tree. Click checkbox to select nodes. 
<div id="jstree_div">
    <li id="node_root">root
        <li id="node_1">node 1
            <li id="node_1_1">node 1.1</li>
            <li id="node_1_2">node 1.2</li>
        <li id="node_2">node 2</li>
<br />
<b>Selection: </b><span id="selection"></span>
  function() {

      plugins: ['checkbox', 'changed'],
    }).on('changed.jstree', function(e, data) {
      var t1 = setTimeout(
        function() {
          var selected_nodes = $('#jstree_div').jstree('get_selected');
          if (Array.isArray(selected_nodes) && selected_nodes.length > 0) {
            // Fire whatever asynchronous process you choose here.
            // Like a call to the server to fetch data. 
            $('#selection').text(selected_nodes.join(', '));
          } else {
        }, 500