Creating Summarized Error Records and Sending Email Using Map/Reduce Script in NetSuite

Introduction

NetSuite’s Map/Reduce script is a powerful tool for processing large datasets efficiently. This guide will help you understand how to create a script that summarizes error records and sends an email notification with the error details.

Steps to Create a CSV File of Error Records

  1. Get Input Data:
  • Retrieve the data you need to process. This can be done using a search or any other method to gather records.
  1. Process Records:
  • Iterate through each record and identify errors based on your specific conditions. Collect these error records in an array.
  1. Format Error Data:
  • Convert the collected error data into CSV format. You can use a library like PapaParse to handle the conversion from JSON to CSV.
  1. Create and Save CSV File:
  • Create a CSV file using NetSuite’s file.create method. Specify the file name, type, and contents, and save the file to a designated folder.
  1. Send Email with CSV Attachment:
  • Load the created CSV file and send an email with the file attached using NetSuite’s email.send method.

Example Workflow

Get Input Data

Retrieve the data to be processed. This can be done using a search or any other method to gather records.

const getInputData = () => {

    // Example: Retrieve data using a search

    return search.create({

        type: ‘customrecord_your_record_type’,

        filters: [],

        columns: [‘type’, ‘orderNum’, ‘refID’]

    }).run().getRange({ start: 0, end: 1000 }).map(result => ({

        type: result.getValue(‘type’),

        orderNum: result.getValue(‘orderNum’),

        refID: result.getValue(‘refID’)

    }));

};

Process Records

Iterate through each record and identify errors based on your specific conditions. Collect these error records in an array.

const reduce = (reduceContext) => {

    try {

        let data = JSON.parse(reduceContext.values);

        let errorData = {};

        // Example: Identify errors based on conditions

        if (/* your error conditions */) {

            errorData = /* process error */;

        }

        if (Object.keys(errorData).length > 0) {

            reduceContext.write({

                key: ‘error_data’,

                value: errorData

            });

        }

    } catch (e) {

        log.error(‘error @reduce’, e);

    }

};

Format Error Data

Convert the collected error data into CSV format. Note: I used Papa.unparse method because I used Papa.parse to parse the data in my getInputData function. You can use your preferred method to create the record.

const summarize = (summaryContext) => {

    try {

        let errorData = [];

        summaryContext.output.iterator().each(function (key, value) {

            if (key === ‘error_data’) {

                errorData.push(JSON.parse(value));

            }

            return true;

        });

        if (errorData.length > 0) {

            let timestamp = new Date().toISOString();

            let csvContent = Papa.unparse(errorData, {

                header: false

            });

            let fileObj = file.create({

                name: ‘error_data_’ + timestamp + ‘.csv’,

                fileType: file.Type.CSV,

                contents: csvContent,

                folder: ERROR_FOLDER_ID

            });

            let fileId = fileObj.save();

            log.audit(‘csvFile created’, ‘fileId: ‘ + fileId);

            sendErrorEmail(fileId);

        }

    } catch (e) {

        log.error(‘error @summarize’, e);

    }

};

Send Email with CSV Attachment

Send an email with the CSV file attached.

const sendErrorEmail = (fileId) => {

    try {

        let fileObj = file.load({ id: fileId });

        email.send({

            author: -5,

            recipients: EMAIL_ID,

            subject: ‘Error Report – eBay Fee Upload’,

            body:

                ‘Dear Team,nn’ +

                ‘The eBay fee upload process completed with some errors.n’ +

                ‘Please find the attached error report.nn’ +

                ‘Regards,nNetSuite Automation’,

            attachments: [fileObj]

        });

        log.audit(‘Error email sent’, `To: ${EMAIL_ID}, File ID: ${fileId}`);

    } catch (e) {

        log.error(‘Error sending email’, e);

    }

};

Leave a comment

Your email address will not be published. Required fields are marked *