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.1
 * @NScriptType ScheduledScript
 */
define(['N/search', 'N/record'], (search, record) => {
    const execute = () => {
        const filters = [
            search.createFilter({
                name: 'mainline',
                operator: search.Operator.IS,
                values: true
            }),
            search.createFilter({
                name: 'custbody_processed_flag',
                operator: search.Operator.IS,
                values: false
            })
        ];

        const salesOrderSearch = search.create({
            type: search.Type.SALES_ORDER,
            filters,
            columns: []
        });

        const pagedResults = salesOrderSearch.runPaged();

        pagedResults.pageRanges.forEach((pageRange) => {
            const currentPage = pagedResults.fetch({ index: pageRange.index });

            currentPage.data.forEach((result) => {
                const salesOrder = record.load({
                    type: record.Type.SALES_ORDER,
                    id: result.id
                });

                // Update sales order fields.
                salesOrder.setValue({
                    fieldId: 'custbody_processed_flag',
                    value: true
                });
                salesOrder.save();
            });
        });
    };

    return { execute };
}); 

        

General Notices