Scenario
Mass update lines in a Sales Order which contain a particular value by using Map/Reduce script.
Solution
The script is searching for lines on Sales Orders containing letter 'x' in a custom column. Sample Map/Reduce code with comments inside:
/**
*@NApiVersion 2.x
*@NScriptType MapReduceScript
*/
define(['N/search', 'N/record'], function (search, record) {
function getInputData() {
log.debug('START', 'Set Searh');
//Set search for lines with values you want to change. It is recommended to test the search in UI to see results.
var inputSearch = search.create({
type: 'transaction',
filters: [
['mainline', 'is', 'F'], 'and',
['type', 'anyof', 'SalesOrd'], 'and',
['custcol4', 'contains', 'x']
],
columns: [
'lineuniquekey' //This field is used to identify particular line
]
});
//Search result is only for first 1000 lines for more you need implement floating logic or run script multiple times.
var result = inputSearch.run().getRange({ start: 0, end: 1000 });
//getInputData step returning results to next step.
return result;
}
function map(context) {
//Sales order id is set in key and line unique key in value
context.write({
key: JSON.parse(context.value).id, //salesorder id as key
value: JSON.parse(context.value).values.lineuniquekey //line identificators
});
}
//after map step are values reduce to one key = Sales Order id and values array with all lines stored by previous map function
//in reduce step we execute our logic on records
function reduce(context) {
//Loading record, in my case Sales Order and Id is get from context.key (id of SO)
var recSO = record.load({
type: 'salesorder',
id: context.key,
isDynamic: false
});
//Here the script loops through array of lines to be modified.
var i;
for (i = 0; i < context.values.length; i++) {
//looking for number of line with uniqueKey
var lineNum = recSO.findSublistLineWithValue({
sublistId: 'item',
fieldId: 'lineuniquekey',
value: context.values[i]
});
//update line with new value
recSO.setSublistValue({
sublistId: 'item',
fieldId: 'custcol4',
line: lineNum,
value: 'MapReduced'
});
};
//saving the record
recSO.save();
log.debug('saved', 'END');
}
function summarize(summary) {
}
return {
getInputData: getInputData,
map: map,
reduce: reduce,
summarize: summarize
}
});