Create and Submit a Task with Dependent Scripts

The following sample creates a scheduled script task and a map/reduce script task. It then creates an asynchronous search task and adds the scheduled script task and the map/reduce script task to the search task as dependent scripts. These scripts are processed when the search task is complete. For more information, see SuiteCloud Processors.

This sample refers to two script parameters: custscript_ss_as_srch_res for the scheduled script, and custscript_mr_as_srch_res for the map/reduce script. These parameters are used to pass the location of the CSV file to the dependent scripts, which is shown in the second and third code samples below. Before using this sample, create these parameters in the script record. For more information, see Creating Script Parameters.

Note:

This sample script uses the require function so that you can copy it into the SuiteScript Debugger and test it. You must use the define function in an entry point script (the script you attach to a script record and deploy). For more information, see SuiteScript 2.x Script Basics and SuiteScript 2.x Script Types.

          /**
 * @NApiVersion 2.x
 */

require(['N/task'], function(task) {
    // Specify a file for the search results
    var asyncSearchResultFile = 'SuiteScripts/ExportFile.csv';

    // Create a scheduled script task
    var scheduledScript = task.create({
        taskType: task.TaskType.SCHEDULED_SCRIPT
    });
    scheduledScript.scriptId = 'customscript_as_ftr_ss';
    scheduledScript.deploymentId = 'customdeploy_ss_dpl';
    scheduledScript.params = {
        'custscript_ss_as_srch_res' : asyncSearchResultFile
    };

    // Create a map/reduce script task
    var mapReduceScript = task.create({
        taskType: task.TaskType.MAP_REDUCE
    });
    mapReduceScript.scriptId = 'customscript_as_ftr_mr';
    mapReduceScript.deploymentId = 'customdeploy_mr_dpl';
    mapReduceScript.params = {
        'custscript_mr_as_srch_res' : asyncSearchResultFile
    };

    // Create the search task
    var asyncTask = task.create({
        taskType: task.TaskType.SEARCH
    };
    asyncTask.savedSearchId = 'customsearch35';
    asyncTask.filePath = asyncSearchResultFile;

    // Add dependent scripts to the search task before it is submitted
    asyncTask.addInboundDependency(scheduledScript);
    asyncTask.addInboundDependency(mapReduceScript);

    // Submit the search task
    var asyncTaskId = asyncTask.submit();
}); 

        

To read the contents of the search results file in a dependent scheduled script, consider the following script sample:

          /**
 * @NApiVersion 2.x
 * @NScriptType ScheduledScript
 */
define(['N/file', 'N/log', 'N/email', 'N/runtime'], function(file, log, email, runtime) {
    // Load the search results file and send an email with the file attached and
    // the number of rows in the file

    function execute(context) {
        // Read a CSV file and return the number of rows minus the header row
        function numberOfRows(csvFileId) {
            var invoiceFile = file.load({
                id: csvFileId
            });
            var iterator = invoiceFile.lines.iterator();
            var noOfLines = 0;

            // Skip the first row (the header row)
            iterator.each(function() {
                return false;
            });

            // Process the rest of the rows
            iterator.each(function() {
                noOfLines++;
                return true;
            });

            return noOfLines;
        }

        // Send an email to the user who ran the script, and attach the
        // CSV file with the search results
        function sendEmailWithAttachment(csvFileId) {
            var noOfRows = numberOfRows(csvFileId);
            var userId = runtime.getCurrentUser().id;
            var fileObj = file.load({
                id: csvFileId
            });

            email.send({
                author: userId,
                recipients: userId,
                subject: 'Search completed',
                body: 'CSV file attached, ' + noOfRows + ' record(s) found.',
                attachments: [fileObj]
            });
        }

        // Retrieve the ID of the search results file
        //
        // Update the name parameter to use the script ID of the original
        // search task
        var resFileId = runtime.getCurrentScript().getParameter({
            name: 'custscript_ss_as_srch_res'
        });

        if (!resFileId) {
            log.error('Could not obtain file content from the specified ID.');
            return;
        }

        log.debug({
            title: 'search - numberOfRows',
            details: numberOfRows(resFileId)
        });
        sendEmailWithAttachment(resFileId);
    }

    return {
        execute: execute
    };
}); 

        

To read the contents of the search results file in a dependent map/reduce script, consider the following script sample:

          /**
 * @NApiVersion 2.x
 * @NScriptType MapReduceScript
 * @NModuleScope SameAccount
 */
define(['N/runtime', 'N/file', 'N/log', 'N/email'], function(runtime, file, log, email) {
    // Load the search results file, count the number of letters in the file, and
    // store this count in another file

    function getInputData() {
        // Retrieve the ID of the search results file
        //
        // Update the completionScriptParameterName value to use the script
        // ID of the original search task
        var completionScriptParameterName = 'custscript_mr_as_srch_res';
        var resFileId = runtime.getCurrentScript().getParameter({
            name: completionScriptParameterName
        });

        if (!resFileId) {
            log.error({
                details: 'resFileId is not valid. Please check the script parameter stored in the completionScriptParameterName variable in getInputData().'
            });
        }

        return {
            type: 'file',
            id: resFileId
        };
    }

    function map(context) {
        var email = context.value.split(',')[1];
        if ("Email" !== email) {
            var splitEmail = email.split('@');
            context.write(splitEmail[splitEmail.length-1], 1);
        }
    }

    function reduce(context) {
        context.write(context.key, context.values.length);
    }

    function summarize(summary) {
        var type = summary.toString();
        log.audit({title: type + ' Usage Consumed ', details: summary.usage});
        log.audit({title: type + ' Concurrency Number ', details: summary.concurrency});
        log.audit({title: type + ' Number of Yields ', details: summary.yields});

        var contents = '';
        summary.output.iterator().each(function(key, value) {
            contents += (key + ' ' + value + '\n');
            return true;
        });

        // Create the output file
        //
        // Update the name parameter to use the file name of the output file
        var fileObj = file.create({
            name: 'domainCount.txt',
            fileType: file.Type.PLAINTEXT,
            contents: contents
        });

        // Specify the folder location of the output file, and save the file
        //
        // Update the fileObj.folder property with the ID of the folder in
        // the file cabinet that contains the output file
        fileObj.folder = -15;
        fileObj.save();
    }

    return {
        getInputData: getInputData,
        map: map,
        reduce: reduce,
        summarize: summarize
    };
}); 

        

General Notices