Example: A Robust Scheduled Script

The following example shows how to prevent duplicate processing if your script restarts. This script uses custbody_processed_flag on the sales order. It is a custom boolean field that must be previously created in the UI. When a sales order is processed, the field is set to true, so your search skips flagged sales orders. If the script restarts, only unprocessed sales orders are handled.

          /**
 * @NApiVersion 2.x
 * @NScriptType ScheduledScript
 */
define(['N/search', 'N/record'], 
    function(search, record){
        return {
            execute: function (context)
            {
                var filter1 = search.createFilter({
                    name: 'mainline', 
                    operator: search.Operator.IS,
                    values: true
                });
                var filter2 = search.createFilter({
                    name: 'custbody_processed_flag', 
                    operator: search.Operator.IS, 
                    values: false
                });
                var srch = search.create({
                    type: search.Type.SALES_ORDER, 
                    filters: [filter1, filter2], 
                    columns: []
                });
 
                var pagedResults = srch.runPaged();
 
                pagedResults.pageRanges.forEach(function(pageRange){
                    var currentPage = pagedResults.fetch({index: pageRange.index});
                    currentPage.data.forEach(function(result){
                        var so = record.load({
                            type: record.Type.SALES_ORDER, 
                            id: result.id
                        });
                    // UPDATE so FIELDS
                    so.setValue({
                        fieldID: 'custbody_processed_flag', 
                        value: true
                    });
                    so.save()
                  });
               });
            }
        }
    }); 

        

General Notices