Netsuite Userevent Script - netsuite

I have a userevent script to change the Field in Contract record from PO record. The Script is running fine. But whenever I edit a contract record and try to submit it : It throws the error "Another user has updated this record since you began editing it. Please close the record and open it again to make your changes".
May I know the reason behind this ?
/*---------------------------------------------------------------------------------------------------------------
Description : Whenever the PO vendor is changed(due to Split vendor) that should replace the same in Contract page record automatically.
Script type : User Event Script
Script id : customscript452
Version : 1.0
Applied to : Contract
----------------------------------------------------------------------------------------------------------------*/
function srchfield()
{
var stRecordid = nlapiGetRecordId(); //returns the contract id
if(stRecordid== undefined || stRecordid== null || stRecordid==' ')
{
}
else
{
var stRecordtype = nlapiGetRecordType(); //returns the contract record type = jobs
var stRecord = nlapiLoadRecord(nlapiGetRecordType(), stRecordid);
nlapiLogExecution('debug','Load Object',stRecord);
var stContractID = stRecord.getFieldValue('entityid'); //returns the value of the field contractid whose fieldid is = entityid
nlapiLogExecution('debug','stContractID',stContractID);
var stCompanyName = stRecord.getFieldValue('companyname'); //returns the value of the field company name whose fieldid is = companyname
nlapiLogExecution('debug','stCompanyName',stCompanyName);
var stConcatenate = stContractID+" : "+stCompanyName; //Concatenate the two Fields to get the result which needs to be found in PO
var arrFilters = new Array(); // This is Array Filters all the Purchase Order Record Search
arrFilters.push(new nlobjSearchFilter('type', null, 'anyof',
[
'PurchOrd'
]));
arrFilters.push(new nlobjSearchFilter('mainline', null, 'is', 'T')); //This is to exclude line level results
arrFilters.push(new nlobjSearchFilter('custbodycontract', null, 'is', stRecordid)); //This is Filters in Contracts Search
var arrColumns = new Array();
arrColumns.push(new nlobjSearchColumn('entity')); //This is Search Column Field in Records
var arrSearchresults = nlapiSearchRecord('purchaseorder', null, arrFilters, arrColumns); //This is Filters in Search Result Purchase Order
if(arrSearchresults== undefined || arrSearchresults== null || arrSearchresults==' ')
{
}
else
{
var length = arrSearchresults.length;
}
if(length== undefined || length== null || length==' ')
{
}
else
{
for (var i = 0; arrSearchresults != null && i < arrSearchresults.length; i++)
{
var objResult = arrSearchresults[i];
var stRecId = objResult.getId();
var stRecType = objResult.getRecordType();
var stCntrctName = objResult.getValue('entity'); //This is Value are Get Purchase Order Records and Field for Vendor = entity
}
}
//var record = nlapiLoadRecord(nlapiGetRecordType(), stRecordid, stCntrctName);
if (stCntrctName =='custentityranking_vendor_name')
{
}
else
{
var stChangeName = stRecord.setFieldValue('custentityranking_vendor_name', stCntrctName); //This is Value are the Set in Main Vendor Field = custentityranking_vendor_name
nlapiSubmitRecord(stRecord, null, null); // Submit the Field Value in Record Type
}
}
}

The User Event script executes as the Contract record is being saved to the database. At the same time, you are loading a second copy of the record from the database and trying to submit the copy as well. This is causing the error you're seeing.
You fix this by just using nlapiSetFieldValue to set the appropriate field on the Contract.
I might also recommend getting more familiar with JavaScript by going through the JavaScript Guide over at MDN. In particular, take a look at the Boolean description so that you know how JavaScript evaluates Boolean expressions. This will help you greatly reduce the amount of code you've written here, as many of your conditionals are unnecessary.

What userevent do you have? It is happening depending on what type of user event and API you are using. Looking at your code, you are trying to load contract record that is already updated at the database. So you might consider below to address your issue. Hope, it helps.
If it is a before submit, you don't need to load the record where the script is deployed.
Just use nlapiGet* and nlapiSet* to get and set values. You also don't need to use nlapiSubmitRecord to reflect the change. With before submit, it executes before the record is being saved to the database. So your changes will still be reflected.
Then if it is after submit, it will be executed after the record has been saved to the database, Thus you might use the following API depending on your needs. Actually, this is the best practice to make sure the solution .
nlapiGetNewRecord - only use this if the script only needs to retrieve info from header and sublists. And nothing to set.
nlapiLookupField - use this if the script only needs to get value/s at the header and nothing from the line.
nlapiSubmitField - the script don't need to load and submit record if the changes only on header. Just use this API.
nlapiLoadRecord and nlapiSubmitRecord- use the former if the script will have changes at the line and then use the latter api to commit it on the database.

Being a user event script code, The code you showed is very not good considering performance.
Here is the sample you can merge
var stRecordid = nlapiGetRecordId(); //returns the contract id
// Every record has an internal id associated with it. No need to add condition explicitly to check if its null
var stRecordtype = nlapiGetRecordType();
var fields = ['entityid','companyname'];
var columns = nlapiLookupField(stRecordtype, stRecordid, fields);
var stContractID = columns.entityid;
var stCompanyName = columns.companyname;
nlapiLogExecution('debug','stContractID/stCompanyName',stContractID+'/'+stCompanyName);
var stConcatenate = stContractID+" : "+stCompanyName; //Concatenate the two Fields to get the result which needs to be found in PO
//
//your code of search
//you can improve that code also by using nlapilook up
nlapiSubmitField(stRecordtype, stRecordid, 'custentityranking_vendor_name', 'name to be updated');

Related

setting context with list of objects as prameters in dialogflow

I have a list of values each having another KEY value corresponding to it, when i present this list to user, user has to select a value and agent has to call an external api with selected value's KEY. how can i achieve this in dialogflow?
I tried to send the entire key value pair in the context and access it in the next intent but for some reason when i set a list(array) to context parameters dialogflow simply ignoring the fulfillment response.
What is happening here and is there any good way to achieve this? I am trying to develop a food ordering chatbot where the category of items in menu is presented and list items in that menu will fetched when user selects a category, this menu is not static thats why i am using api calls to get the dynamic menu.
function newOrder(agent)
{
var categories = []
var cat_parameters = {}
var catarray = []
const conv = agent.conv();
//conv.ask('sure, select a category to order');
agent.add('select a category to order');
return getAllCategories().then((result)=>{
for(let i=0; i< result.restuarantMenuList.length; i++)
{
try{
var name = result.restuarantMenuList[i].Name;
var catid = result.restuarantMenuList[i].Id;
categories.push(name)
//categories.name = catid
cat_parameters['id'] = catid;
cat_parameters['name'] = name
catarray.push(cat_parameters)
}catch(ex)
{
agent.add('trouble getting the list please try again later')
}
}
agent.context.set({
name: 'categorynames',
lifespan: 5,
parameters: catarray, // if i omit this line, the reponse is the fultillment response with categories names, if i keep this line the reponse is fetching from default static console one.
})
return agent.add('\n'+categories.toString())
})
function selectedCategory(agent)
{
//agent.add('category items should be fetched and displayed here');
var cat = agent.parameters.category
const categories = agent.context.get('categorynames')
const cat_ob = categories.parameters.cat_parameters
// use the key in the catarray with the parameter cat to call the external API
agent.add('you have selected '+ cat );
}
}
The primary issue is that the context parameters must be an object, it cannot be an array.
So when you save it, you can do something like
parameters: {
"cat_parameters": catarray
}
and when you deal with it when you get the reply, you can get the array back with
let catarray = categories.parameters.cat_parameters;
(There are some other syntax and scoping issues with your code, but this seems like it is the data availability issue you're having.)

How to access 'Abbreviation' field of a custom list in NetSuite custom lists

I have a custom list that is used as a matrix option of Inventory item. Its 'Color'. This custom list has an abbreviation column. I am creating a saved search on item and using Color field(join) and trying to access 'Abbreviation' field of color.
Abbreviation on custom list is available on when 'Matrix Option List' is checked.
Can someone please help me achieve this? I tried to do this through script and it seems like we cannot access 'Abbreviation' column through script. I also tried to use script to write a search directly on 'Color' - custom list and get the 'abbreviation' through search columns. It did not work. Is there a way to access 'Abbreviation' from custom lists?
Thanks in Advance
You can access it via suitescript by using the record type "customlist" and the internal id of the list like so:
var rec = nlapiLoadRecord('customlist', 5);
var abbreviation = rec.getLineItemValue('customvalue', 'abbreviation', 1);
nlapiLogExecution('DEBUG', 'abbreviation', abbreviation);
Keep in mind that the third argument of getLineItemValue is the line number, not the internal ID of the item in the list. If you want to find a specifc line item, you may want to use rec.findLineItemValue(group, fldnam, value).
Unfortunately, it doesn't look like this translates to saved searches. The suiteanswer at https://netsuite.custhelp.com/app/answers/detail/a_id/10653 has the following code:
var col = new Array();
col[0] = new nlobjSearchColumn('name');
col[1] = new nlobjSearchColumn('internalid');
var results = nlapiSearchRecord('customlist25', null, null, col);
for ( var i = 0; results != null && i < results.length; i++ )
{
var res = results[i];
var listValue = (res.getValue('name'));
var listID = (res.getValue('internalid'));
nlapiLogExecution('DEBUG', (listValue + ", " + listID));
}
However, whatever part of the application layer translates this into a query doesn't handle the abbreviation field. One thing to keep in mind is that the 'custom list' record is basically a header record, and each individual entry is it's own record that ties to it. You can see some of the underlying structure here, but the takeaway is that you'd need some way to drill-down into the list entries, and the saved search interface doesn't really support it.
I could be wrong, but I don't think there's any way to get it to execute in a saved search as-is. I thought the first part of my answer might help you find a workaround though.
Here is a NetSuite SuiteScript 2.0 search I use to find the internalId for a given abbreviation in a custom list.
/**
* look up the internal id value for an abbreviation in a custom list
* #param string custom_list_name
* #param string abbreviation
* #return int
* */
function lookupNetsuiteCustomListInternalId( custom_list_name, abbreviation ){
var internal_id = -1;
var custom_list_search = search.create({
type: custom_list_name,
columns: [ { name:'internalId' }, { name:'abbreviation' } ]
});
var filters = [];
filters.push(
search.createFilter({
name: 'formulatext',
formula: "{abbreviation}",
operator: search.Operator.IS,
values: abbreviation
})
);
custom_list_search.filters = filters;
var result_set = custom_list_search.run();
var results = result_set.getRange( { start:0, end:1 } );
for( var i in results ){
log.debug( 'found custom list record', results[i] );
internal_id = results[i].getValue( { name:'internalId' } );
}
return internal_id;
}
Currently NetSuite does not allows using join on matrix option field. But as you mentioned, you can use an extra search to get the result, you could first fetch color id from item and then use search.lookupFields as follows
search.lookupFields({ type: MATRIX_COLOR_LIST_ID, id: COLOR_ID, columns: ['abbreviation'] });
Note: Once you have internalid of the color its better to use search.lookupFields rather than creating a new search with search.create.

Email template netsuite

I have really big problem, i mean im working in a company where we are using NetSuite as our business platform and now they updated our account with new APIs.
Developer before me wrote this code
for(var k = 0; k < ResultsPPCI.length; k++){
EmployeePPCI = ResultsPPCI[k].getValue('internalid'); //get the value
// log('Internal ID', EmployeePPCI);
// Merge, send, and associate an email with Purchase Order record (id=1000)
var mergeValuesPPCI = {};
mergeValuesPPCI.NLEMPFIRST = nlapiLookupField('employee', EmployeePPCI, 'firstname');
mergeValuesPPCI.NLEMPLAST = nlapiLookupField('employee', EmployeePPCI, 'lastname');
mergeValuesPPCI.NLSUPPLIER = nlapiLookupField('customer', cust, 'companyname');
mergeValuesPPCI.NLPRODUCTCODE = productcodehtml;
var emailBodyPPCI = nlapiMergeRecord(65, 'purchaseorder', poID, null, null, mergeValuesPPCI);
var recordsPPCI = {};
recordsPPCI['transaction'] = poID;
nlapiSendEmail(EmployeePPCI, EmployeePPCI, emailBodyPPCI.getName(), emailBodyPPCI.getValue(), null, null, recordsPPCI);
// log('EmployeePPCI',EmployeePPCI);
nlapiLogExecution('AUDIT', 'Potentional Problem', 'Email Sent');
}
I have problem now because nlapiMergeRecord is deprecated and it wont work. But i really cant find any working example online for hours... The most important part here is actually body of this email that has to be sent. In this case it is productcodehtml or mergeValuesPPCI.NLPRODUCTCODE.
This is how my template looks like :
<p>The QA Release has been submitted by <nlsupplier> for ${transaction.tranId}.</nlsupplier></p>
<p>The following item(s) have a short shelf life:</p>
<nlproductcode></nlproductcode>
Please can you help me with converting this code to new method? How can i connect nlproductcode from template with mergeValuesPPCI.NLPRODUCTCOD from my code?
Thanks in advance!
You can use kotnMergeTemplate as a drop in replacement for nlapiMergeRecord
e.g.:
kotnMergeTemplate(65, 'purchaseorder', poID, null, null, mergeValuesPPCI);
the nlobjEmailMerger does not take custom values so you'd have to post process the results. Again you can look at the example in my script where you'd get the merged string and then run:
var oldCustFieldPatt = /<(nl[^ >]+)>(\s*<\/\1>)?/ig;
content = content.replace(oldCustFieldPatt, function(a,m){
return mergeValuesPPCI[m.toUpperCase()] || mergeValuesPPCI[m.toLowerCase()] || '';
});
You can use the new nlapiCreateEmailMerger(templateId)
First you need to create your email template in netsuite and get the internal id.
Then:
Use nlapiCreateEmailMerger(templateId) to create an nlobjEmailMerger object.
var emailMerger = nlapiCreateEmailMerger(templateId);
Use the nlobjEmailMerger.merge() method to perform the mail merge.
var mergeResult = emailMerger.merge();
Use the nlobjMergeResult methods to obtain the e-mail distribution’s subject and body in string format.
var emailBody = mergeResult.getBody();
Send your email
nlapiSendEmail(senderInternalId, 'receiver#email.com','subject',emailBody, null, null, null);
Good luck!

Validate In-Line Edits in Netsuite

I need to validate inline editing in NetSuite.
I already have a Client Script in place that works great when editing the record normally.
I tried adding a User Event script that on the before save function that validates the record, but it appears this is ignored with inline editing.
Has anybody ran into this before?
Any insight you can provide would be helpful. Thanks!
Edits:
The relevant code from the UE script:
function beforeSubmit(type){
if (type == "create" || type == "edit" || type == "xedit") {
var status = nlapiGetContext().getSetting("SCRIPT", "...");
var amount = Number(nlapiGetContext().getSetting("SCRIPT", "..."));
var nr = nlapiGetNewRecord();
var entitystatus = nr.getFieldValue("entitystatus");
var projectedtotal = Number(nr.getFieldValue("projectedtotal"));
if (entitystatus == status && projectedtotal >= amount) {
var statusText = nr.getFieldText("entitystatus");
var message = "ERROR...";
throw nlapiCreateError("...", message, true);
}
}
}
This applies to the opportunity record.
The field being validated is Projected Total with id projectedtotal.
My mistake, I misunderstood how xedit handled nlapiGetNewRecord(). Calling nlapiGetNewRecord when in xedit only returns the edited fields, not the entire record. Thus, the if statement was never true in xedit mode, because either the amount or the status would be null (it was very unlikely the user would edit both at the same time, and validation relies on both these fields' values).
I edited the code to lookup the field value if it is not present in the new record. Now everything works as expected!
Thanks everyone for the help!
For reference, the corrected code is below.
function beforeSubmit(type){
if (type == "create" || type == "edit" || type == "xedit") {
var status = nlapiGetContext().getSetting("SCRIPT", "...");
var amount = Number(nlapiGetContext().getSetting("SCRIPT", "..."));
var nr = nlapiGetNewRecord();
//Attempt to get values normally
var entitystatus = nr.getFieldValue("entitystatus");
var projectedtotal = Number(nr.getFieldValue("projectedtotal"));
var id = nr.getId();
//If values were null, it's likely they were not edited and
//thus not present in nr. Look them up.
if(!entitystatus){
entitystatus = nlapiLookupField("opportunity", id, "entitystatus");
}
if(!projectedtotal){
projectedtotal = Number(nlapiLookupField("opportunity", id, "projectedtotal"));
}
if (entitystatus == status && projectedtotal >= amount) {
var message = "ERROR...";
throw nlapiCreateError("101", message, true);
}
}
}
In your user event are you checking the value of the type parameter. For inline editing, the value of the type is 'xedit'.

Xpages java script server side does not update the field in form

case : Update field after select the customer name:
setting : 1 setting view that consist of database path :
DbServer: ServerOne/pcs
Directory: office
Database name : Customer.nsf
this xpages have a datasource inside, it call "document1"
// get the database path :
var vw3:NotesView=database.getView("Setting Path");
var doc3:NotesDocument=vw3.getFirstDocument();
var server:string = doc3.getItemValueString("DbServer");
var DName:string=doc3.getItemValueString("DbName");
var Directory:string=doc3.getItemValueString("Directory");
var DBName:string= Directory+"\\" +DName;
var db:NotesDatabase = session.getDatabase(server, DBName, false);
var vw:NotesView = db.getView("All Customer");
var doc:NotesDocument=vw.getDocumentByKey(document1.getValue("Customer"),true);
if (doc !=null) {
document1.setValue("Contact", doc.getItemValueString("Contact"));
document1.setValue("Telephone", doc.getItemValueString("Phone"));
document1.setValue("Fax", doc.getItemValueString("Fax"));
document1.setValue("Email", doc.getItemValueString("Email"));
}
Problem :
The field doesn't update and get the value from "customer" database.
I see a series of problems in your code:
Bind your input field to a scope variable, not to the document itself. It is a search string in the beginning, not part of the new document.
You don't check for the case that the customer wasn't found, so you never know if that was the issue.
I would rather use an URL and resolve instead of server / path / database (but that's a little style
So something like (typed off my head, will contain typos):
var vw3:NotesView=database.getView("Setting Path");
var vwe3 = vw3.getFirstEntry();
var db = session.resolve(vwe.entries[0]);
var vw:NotesView = db.getView("All Customer");
var doc:NotesDocument=vw.getDocumentByKey(viewScope.customer,true);
if (doc !=null) {
viewScope.result = doc.getUniversalID();
document1.setValue("Contact", doc.getItemValueString("Contact"));
document1.setValue("Telephone", doc.getItemValueString("Phone"));
document1.setValue("Fax", doc.getItemValueString("Fax"));
document1.setValue("Email", doc.getItemValueString("Email"));
doc.recycle()l
} else {
viewScope.result = "Not found!";
}
// ADD recycle() calls here!!!
Bind a display only field to viewScope.result, so you have a better idea what is happening. Your view must be sorted and indexed by customer name.
Of course you could use the OpenNTF dialog list control instead.

Resources