Hi Guys, I have the following data in the Reduce F...
# suitescript
n
Hi Guys, I have the following data in the Reduce Function of MapReduce Script. [ "{\"line\": 1, \"memoText\": \"Memo for Line 1\"}", "{\"line\": 2, \"memoText\": \"Memo for Line 2\"}" ... "{\"line\": 80, \"memoText\": \"Memo for Line 80\"}" ] I just want to update the lines of a JE. I loaded the record one time and Trying to setSublistValue in FOR loop, to update the Memo field on each line. I get the "Script Execution Usage Limit Exceeded" Even at the first line. Tested the remaining Usage BEFORE load & after load like this log.debug('Remaining Usage Before Load', runtime.getCurrentScript().getRemainingUsage()); 5000 Load log.debug('Remaining Usage After Load', runtime.getCurrentScript().getRemainingUsage()); 4990 Can someone help ?
e
share your script
n
Copy code
/**
 * @NApiVersion 2.x
 * @NScriptType MapReduceScript
 */
define(['N/record', 'N/search', 'N/log', 'N/runtime'], function (record, search, log, runtime) {

    function getInputData() {
        log.debug('Get Input Data Stage', 'Fetching Journal Entry lines to process');

        // Hardcoded Journal Entry ID for testing
        var journalEntryId = '123456';
        log.debug('Journal Entry ID', journalEntryId);

        // Load the Journal Entry and prepare line data
        var jeRecord = record.load({
            type: record.Type.JOURNAL_ENTRY,
            id: journalEntryId
        });

        var lineCount = jeRecord.getLineCount({ sublistId: 'line' });
        var inputData = [];
        for (var i = 0; i < lineCount; i++) {
            var scheduleId = jeRecord.getSublistValue({
                sublistId: 'line',
                fieldId: 'schedulenum',
                line: i
            });
            if (scheduleId) {
                inputData.push({
                    line: i,
                    journalEntryId: journalEntryId,
                    scheduleId: scheduleId
                });
            }
        }

        log.debug('Lines with Schedule IDs', inputData.length);
        return inputData;
    }

    function map(context) {
        var lineData = JSON.parse(context.value);
        log.debug('Map Stage - Processing Line', lineData);

        try {
            var scheduleRecord = record.load({
                type: 'amortizationschedule',
                id: lineData.scheduleId
            });

            var sourceTranId = scheduleRecord.getValue('sourcetran');
            var startDate = scheduleRecord.getText('startdate');
            var endDate = scheduleRecord.getText('enddate');

            var sourceTranMemo = '';
            var sourceTranText = '';

            if (sourceTranId) {
                var sourceData = search.lookupFields({
                    type: 'transaction',
                    id: sourceTranId,
                    columns: ['memo', 'tranid']
                });

                sourceTranMemo = sourceData.memo || '';
                sourceTranText = sourceData.tranid || '';
            }

            var memoText = 'Source Transaction: ' + sourceTranText + ', Start Date: ' + startDate + ', End Date: ' + endDate + ', Source Transaction Memo: ' + sourceTranMemo;

            context.write({
                key: lineData.line,
                value: {
                    journalEntryId: lineData.journalEntryId,
                    line: lineData.line,
                    memoText: memoText
                }
            });
        } catch (error) {
            log.error('Error Processing Line in Map Stage', error);
        }
    }
    function reduce(context) {
        try {
            // Parse the context.values array (each value is a JSON string)
            var updates = context.values.map(JSON.parse);
            var journalEntryId = JSON.parse(context.values[0]).journalEntryId;

            log.debug('Before Loading JE', 'Remaining Governance: ' + runtime.getCurrentScript().getRemainingUsage());
            // Load the Journal Entry in non-dynamic mode
            var journalEntry = record.load({
                type: record.Type.JOURNAL_ENTRY,
                id: journalEntryId,
                isDynamic: false
            });

            // Track governance usage and batch size
            var governanceThreshold = 100; // Adjust based on your script type's governance limit
            var governanceUsage = 0;

            updates.forEach(function(update, index) {
                var lineIndex = journalEntry.findSublistLineWithValue({
                    sublistId: 'line',
                    fieldId: 'line',
                    value: update.line
                });

                if (lineIndex !== -1) {
                    // Update memo field
                    journalEntry.setSublistValue({
                        sublistId: 'line',
                        fieldId: 'memo',
                        line: lineIndex,
                        value: update.memoText
                    });
                } else {
                    log.error('Line Not Found', 'Line number: ' + update.line);
                }

                // Check governance usage
                governanceUsage += runtime.getCurrentScript().getRemainingUsage();
                if (governanceUsage >= governanceThreshold || index === updates.length - 1) {
                    // Save the JE in batches
                    journalEntry.save();
                    log.debug('Batch Saved', 'Saved JE after processing batch of updates');

                    // Reload JE for further updates
                    if (index < updates.length - 1) {
                        journalEntry = record.load({
                            type: record.Type.JOURNAL_ENTRY,
                            id: journalEntryId,
                            isDynamic: false
                        });
                    }

                    // Reset usage counter
                    governanceUsage = 0;
                }
            });

        } catch (e) {
            log.error('Error in Reduce Function', e.message);
        }
    }

    function summarize(summary) {
        var totalTime = summary.seconds + ' seconds';
        log.audit('Summary Stage', 'Processing Complete in ' + totalTime);

        summary.mapSummary.errors.iterator().each(function (key, error) {
            log.error('Map Error', error);
            return true;
        });

        summary.reduceSummary.errors.iterator().each(function (key, error) {
            log.error('Reduce Error', error);
            return true;
        });

        log.audit('Summary Stage', 'All processing completed successfully.');
    }

    return {
        getInputData: getInputData,
        map: map,
        reduce: reduce,
        summarize: summarize
    };
});
Open to complete rewrite of Reduce function
intent is to update the lines
e
What are you trying to do in the map phase? You would be better off building your object in getInputData so that you just need to pass the object to reduce for processing and avoid that many record.loads which is resource intensive.