Hello. I'm running a script on the Invoice record. This script's aim is to take the value of the line field "custcol_altsales_invoice" from the invoice and map it to the corresponding SO line in a field called "custcol_ccaw_test_field_1". The issue is that this works if everything is invoiced at once (all the lines from the SO are present on the invoice). It will map incorrectly if, say, I only invoice some lines from the SO. Is there a way to map each line from the invoice to its exact line on the SO?
/**
* @NApiVersion 2.x
* @NScriptType UserEventScript
* @NModuleScope SameAccount
*/
define(['N/record'], function(record) {
function updateCommissionOnSalesOrder(context) {
//only run if it's edit or create
if (context.type == 'create' || context.type == 'edit') {
//reference the current invoice
var invoiceRecord = context.newRecord;
// Get the Sales Order ID from the Invoice record's "Created From" field
var salesOrderId = invoiceRecord.getValue({ fieldId: 'createdfrom' });
// Get the line count on the Invoice record
var lineCount = invoiceRecord.getLineCount({
sublistId: 'item'
});
// Update the "Commission Calculated" field on the Sales Order from the "%commissions" field on the Invoice
if(salesOrderId){
for (var line = 0; line < lineCount; line++) {
var salesOrderRecord = record.load({
type: record.Type.SALES_ORDER,
id: salesOrderId,
isDynamic: true
});
//get the value of the field "custcol_altsales_invoice" so we can map it onto the SO
var commissionPercentage = invoiceRecord.getSublistValue({
sublistId: 'item',
fieldId: 'custcol_altsales_invoice',
line: line
});
//select the line on the sales order
salesOrderRecord.selectLine({
sublistId: 'item',
line: line
});
// Update the Sales Order record with the commission percentage from the field "custcol_altsales_invoice" above
salesOrderRecord.setCurrentSublistValue({
sublistId: 'item',
fieldId: 'custcol_ccaw_test_field_1',
value: commissionPercentage
});
//commi the lines on the SO
salesOrderRecord.commitLine({
sublistId: 'item'
});
// Save the updated Sales Order record so that the mapped changes are refelected.
salesOrderRecord.save();
}
}
}
}
return {
afterSubmit: updateCommissionOnSalesOrder
};
});