Oneworld (multiple subsidiaries, multiple customers), Sales Orders: We are attempting to, after the customer has been selected by the user, to set the Subsidiary to replace the primary subsidiary on the customer record with the subsidiary on the most recent sales order for the customer (same with currency). I've attempted several approaches: fieldedit, postsourcing. In all cases NetSuite, in the UI, will flash the subsidiary from the subscript, then will immediately over-ride it with the primary subsidiary. ClientScript. Script is here. Any ideas are super welcome here. Thank you!
/**
* @NApiVersion 2.1
* @NScriptType ClientScript
* @NModuleScope SameAccount
*/
define(['N/search', 'N/record', 'N/log'], (search, record, log) => {
function fieldChanged(scriptContext) {
const sublistId = scriptContext.sublistId;
const fieldId = scriptContext.fieldId;
const currentRecord = scriptContext.currentRecord;
// Check if the field change occurs at the record level (headers)
if (!sublistId && fieldId === 'entity') {
const entityId = currentRecord.getValue({
fieldId: 'entity'
});
// Check if the "Entity" field has a value (not empty)
if (entityId) {
// Proceed with the Sales Order search
const salesOrderSearch = search.create({
type: search.Type.SALES_ORDER,
filters: [
search.createFilter({ name: 'entity', operator: search.Operator.ANYOF, values: [entityId] })
],
columns: [
{ name: 'subsidiary' },
{ name: 'currency' },
{ name: 'datecreated', sort: search.Sort.DESC } // Sort by Date Created in descending order
],
title: 'Recent Sales Order Search'
});
// Run the search and retrieve the results
const searchResults = salesOrderSearch.run().getRange({ start: 0, end: 1 });
if (searchResults.length > 0) {
// Get the subsidiary and currency from the most recent Sales Order
const mostRecentSubsidiaryId = searchResults[0].getValue({ name: 'subsidiary' });
const mostRecentCurrencyId = searchResults[0].getValue({ name: 'currency' });
// Log the "Currency" and "Subsidiary" values from the search results
log.debug('Most Recent Subsidiary ID', mostRecentSubsidiaryId);
log.debug('Most Recent Currency ID', mostRecentCurrencyId);
// Set the Subsidiary and Currency fields on the current transaction
try {
currentRecord.setValue({
fieldId: 'subsidiary',
value: mostRecentSubsidiaryId
});
currentRecord.setValue({
fieldId: 'currency',
value: mostRecentCurrencyId
});
} catch (e) {
log.error({
title: 'Error updating subsidiary and currency fields',
details: e.toString()
});
}
}
}
}
}
return {
fieldChanged: fieldChanged
};
});