Hi There
I have the following script:
/**
*@NApiVersion 2.x
*@NScriptType MapReduceScript
*/
define(["N/record", "N/search", "N/runtime"], function (
record,
search,
runtime
) {
function getInputData() {
try {
var scriptObj = runtime.getCurrentScript();
var recordId = scriptObj.getParameter("custscript_recordid");
var salesOrderid = recordId;
log.debug("recordid", salesOrderid);
var salesorderSearchObj = search.create({
type: "salesorder",
filters: [
["type", "anyof", "SalesOrd"],
"AND",
["internalid", "anyof", [salesOrderid]],
"AND",
["shipping", "is", "F"],
"AND",
["taxline", "is", "F"],
"AND",
["mainline", "is", "F"],
"AND",
[
"formulanumeric: {quantitypacked}-{quantitybilled}",
"greaterthan",
"0",
],
],
columns: [
search.createColumn({ name: "internalid", label: "Internal ID" }),
search.createColumn({ name: "source", label: "Source" }),
search.createColumn({ name: "salesrep", label: "Sales Rep" }),
search.createColumn({ name: "trandate", label: "Date" }),
search.createColumn({ name: "postingperiod", label: "Period" }),
search.createColumn({ name: "type", label: "Type" }),
search.createColumn({
name: "tranid",
sort: search.Sort.DESC,
label: "Document Number",
}),
search.createColumn({ name: "entity", label: "Name" }),
search.createColumn({ name: "account", label: "Account" }),
search.createColumn({ name: "memo", label: "Memo" }),
search.createColumn({ name: "amount", label: "Amount" }),
search.createColumn({ name: "item", label: "Item" }),
search.createColumn({ name: "rate", label: "Item Rate" }),
search.createColumn({ name: "fxrate", label: "Item Rate" }),
search.createColumn({ name: "line", label: "Line ID" }),
search.createColumn({ name: "quantity", label: "Quantity" }),
search.createColumn({
name: "quantitybilled",
label: "Quantity Billed",
}),
search.createColumn({
name: "quantitycommitted",
label: "Quantity Committed",
}),
search.createColumn({
name: "quantityshiprecv",
label: "Quantity Fulfilled/Received",
}),
search.createColumn({
name: "quantitypacked",
label: "Quantity Packed",
}),
search.createColumn({
name: "quantitypicked",
label: "Quantity Picked",
}),
search.createColumn({ name: "taxcode", label: "Tax Item" }),
search.createColumn({
name: "formulanumeric",
formula: "{quantitypacked}-{quantitybilled}",
label: "Qty_to_invoice",
}),
],
});
return salesorderSearchObj;
} catch (error) {
log.error({
title: "get input data error",
details: error.message + " line id: " + error.lineNumber,
});
}
}
/**
* @param {MapReduceContext.map} context
*/
function map(context) {
try {
var result = JSON.parse(context.value);
var resultObj = JSON.stringify(context.values);
log.debug("map-result:", JSON.stringify(result));
var internalId = result.id;
log.debug("internalId", internalId);
var lineId = result.values.line;
var itemRate = result.values.rate;
var soItem = result.values.item;
var description = result.values.memo;
var quantityPacked = result.values["quantitypacked"];
var quantityBilled = result.values["quantitybilled"];
var quantity = quantityPacked - quantityBilled;
var lineData = {
line: lineId,
item: soItem,
rate: itemRate,
quantity: quantity,
memo: description,
};
log.debug("lineData", lineData);
var lineDataString = JSON.stringify(lineData);
// Pass the JSON string as the value in context.write()
context.write({
key: internalId,
value: lineDataString,
});
log.debug("context-end of map", context);
} catch (error) {
log.error("map error", error.message + " lineID: " + error.lineNumber);
}
}
/**
* @param {MapReduceContext.reduce} context
*/
function reduce(context) {
try {
var mapData = context.values;
log.debug("mapData", mapData);
log.debug("internalID", context.key);
try {
var foundLineIds = mapData.map(function (value) {
var perValue = JSON.parse(value);
return perValue.line;
});
log.debug("foundLineIds", foundLineIds);
} catch (error) {
log.error({
title: "foundlineIds-error",
details: error.message + " line id: " + error.lineNumber,
});
}
var invoiceRecord = record.transform({
fromType: record.Type.SALES_ORDER,
fromId: context.key,
toType: record.Type.INVOICE,
isDynamic: true,
});
var lineCount = invoiceRecord.getLineCount({ sublistId: "item" });
log.debug("lineCount", lineCount);
var linesToRemove = [];
try {
// Iterate through the lines in the invoice record
for (var lineIndex = lineCount - 1; lineIndex >= 0; lineIndex--) {
// Get the line ID of the current line in the invoice record
var lineId = invoiceRecord.getSublistValue({
sublistId: "item",
fieldId: "line",
line: lineIndex,
});
log.debug("lineId", lineId);
// Check if the line ID is found in the "foundLineIds" array
if (foundLineIds.indexOf(lineId) !== -1) {
// Retrieve the line data from the context's map data
var lineDataString = mapData[foundLineIds.indexOf(lineId)];
// Directly parse and use line data
var lineData = JSON.parse(lineDataString);
if (lineData.line == lineId) {
// Set the updated values for the retained line
invoiceRecord.setCurrentSublistValue({
sublistId: "item",
fieldId: "item",
value: lineData.line.value,
ignoreFieldChange: false,
});
invoiceRecord.setCurrentSublistValue({
sublistId: "item",
fieldId: "quantity",
line: lineIndex,
value: lineData.quantity,
});
invoiceRecord.setCurrentSublistValue({
sublistId: "item",
fieldId: "rate",
line: lineIndex,
value: lineData.rate,
});
invoiceRecord.setCurrentSublistText({
sublistId: "item",
fieldId: "memo",
text: "memo",
ignoreFieldChange: true,
});
// Update other fields as needed (amount, taxcode, etc.)
// Commit the line with updated values
invoiceRecord.commitLine({ sublistId: "item" });
}
} else {
linesToRemove.push(lineIndex);
// Remove the lines in reverse order to avoid issues with indexing
linesToRemove.reverse();
linesToRemove.forEach(function (lineIndex) {
invoiceRecord.removeLine({
sublistId: "item",
line: lineIndex,
});
});
}
// Check if the line ID is not found in the "lineids" array
if (foundLineIds.indexOf(lineId) === -1) {
// Add the line index to the "linesToRemove" array
log.debug("found line Ids to remove", foundLineIds.indexOf(lineId));
}
}
} catch (error) {
log.error({
title: "lines to remove",
details: error.message + " " + "line Id " + error.lineNumber,
});
}
// Save the updated invoice record
var invoiceId = invoiceRecord.save();
log.debug(
"invoiceRecord",
"invoice record: " + invoiceRecord + " invoice id: " + invoiceId
);
// Emit the invoiceRecord data as a key-value pair
context.write({
key: "InvoiceRecord_" + invoiceRecord.id,
value: JSON.stringify({
type: "InvoiceRecord",
data: {
/* Your invoiceRecord data */
},
}),
});
log.debug("reduce-context after write", context);
} catch (error) {
log.error(
"error-reduce",
error.message + " lineId: " + error,
lineNumber
);
}
/* ToDO:
1 load invoice record once saved
2 loop through all lines. if line id is not same as linedata ids (may need to to extract the line ids and/or change context/write to be key: lineid, values:values)
removeline
if line id is found, check all quantity value and set rate to recalculate amount. commit line
*/
}
/**
* @param {MapReduceContext.summarize} context
*/
function summarize(summary) {}
return {
getInputData: getInputData,
map: map,
reduce: reduce,
summarize: summarize,
};
});
This works as expected for the most part (at least with the example I have tested) where the lines not matching from the returned search are removed.
However, the part that isn't working correctly is:
In the reduce function:
if the line id on the invoice record matches a line returned in the map function, then the field values of the invoice record line need to be updated to match what was returned from the map function.
For example, I have a quantity returned in the map stage of 2 for line id 4
on record transform (invoiceRecord object), the quantity for line id 4 is 3
I want this to be updated to 2 to match the data returned for the same line in the map stage.
Where am I going wrong in my code?
thanks