NetSuite: Create WorkOrder and Sublist with SuiteScript - netsuite

NetSuite newbie here.
I have a SuiteScript that loads the results of a sales order query and then creates a work order for each of those results.
Is it possible to also create sublist items in the same stroke or will I have to load each new workorder and then create it that way? If so, any code samples for that? My little script is below.
I have attempted things with insertLineItem and nlapiSelectNewLineItem but no luck so far.
Thanks!
function example1() {
var arrSearchResults = nlapiSearchRecord(null, 'searchID', null,
null);
for ( var i in arrSearchResults) {
var searchResult = arrSearchResults[i];
// create work order records
var recWorkOrder = nlapiCreateRecord('workorder');
recWorkOrder.setFieldValue('quantity', '8');
recWorkOrder.setFieldValue('assemblyitem', itemInternalId);
// recWorkOrder.setFieldValue('options', internalId);
nlapiSubmitRecord(recWorkOrder);
//Create sublist items here?
}
var kilroy = 'was here';
}

Your approach is pretty good and there is no way to update everything in one shot analogous to a SQL statement or something.
The only thing I see about your SuiteScript is that two parts would be in a different order. You'd create your sublist records then you have to submit the sublist. After submitting the sublist then you submit the work order.
So like this:
... snipped above no changes
// recWorkOrder.setFieldValue('options', internalId);
//Create sublist items here?
//Submit the sublist records
//Submit the work order last to finalize the transaction
nlapiSubmitRecord(recWorkOrder);
}
var kilroy = 'was here';
}

Related

Mongoose needs 2 times excecution to update collection

Something strange is going on or something idiotic I did but I got the following problem.
I got aenter code here web app where I have an online menu for a restaurant.
The structure of the products is as follows.
Facility->Category->Item->Name
So all item models have saved the name of the category they belong to as a string.
But sometimes you want to change the name of the category. What I wanted to do was find all the items in this category and change the name of the assigned category to the new one. Everything looked great until I saw that it took two times to run the controller that changed the name of the category and on the items to fully save the new name to the items.
The category changed the name but the items updated to the new name on the second run. Weird right?
So, what is that you can see that I don't and I implemented the silliest way of bugfix in the history of bugfixes.
Here is the controller - route.
module.exports.updateCtg = async(req,res)=>{
const {id} = req.params;
for(i=0;i<2; i++){
category = await CategoryModel.findByIdAndUpdate(id,{...req.body.category});
await category.save();
items = await ItemModel.find({});
for(item of items){
if(item.facility === category.facility){
item.category = category.name;
await single.save();
}
}
}
res.render('dashboard/ctgview', {category._id});
}
The findByIdAndUpdate function returns the found document, i.e. the document before any updates are applied.
This means that on the first run through category is set to the original document. Since the following loop uses category.name, it is setting the category of each item to the unmodified name.
The second iteration find the modified document, and the nested loop uses the new value in category.name.
To get this in a single pass, use
item.category = req.category.name;
or if you aren't certain it will contain a new name, use
item.category = req.category.name || category.name;
Or perhaps instead of a loop, use updateMany
if (req.category.name) {
ItemModel.updateMany(
{"item.facility": category.facility},
{"item.category": req.category.name}
)
}

SuiteScript Updating Search Result Fields

I have a search in SuiteScript 2.0 that's working fine. But for each record the search brings back, I want to update a particular field (I use it elsewhere to determine that the record has been examined). It's potentially a very large result set, so I have to page it. Here's my code:
var sResult = mySearch.runPaged({pageSize: 10});
for (var pageIndex = 0; pageIndex < sResult.pageRanges.length; pageIndex++)
{
var searchPage = sResult.fetch({ index: pageRange.index });
searchPage.data.forEach(function (result)
{
var name = result.getValue({ name: "altname"})
result.setValue({
name: 'tracker',
value: new Date()
})
});
}
You can see where I have a call to result.setValue(), which is a non-existent function. But it shows where I want to update the 'tracker' field and what data I want to use.
Am I barking up the wrong tree entirely here? How do I update the field for each result returned?
As Simon says you can't directly update a search result, but you can use submitFields method.
This example is from NetSuite documentation:
var otherId = record.submitFields({
type: 'customrecord_book', //record Type
id: '4', // record Id
values: {
'custrecord_rating': '2'
}
});
This approach will save more governance than load and save the record.
AFAIK You can't directly update a search result and write the value back to the record, the record needs to be loaded first. The snippet doesn't say what the type of record it is you're searching for or want to load, but the general idea is (in place of your result.setValue line):
var loadedRecord = Record.load({type:'myrecordtype', id:result.id});
loadedRecord.setValue( {fieldId:'tracker', value: new Date() });
loadedRecord.save();
Keep in mind SuiteScript governance and the number of records your modifying. Load & Save too many and your script will terminate earlier than you expect.
Bad design: instead of using result.setValue inside the iteration, push those to an "update" array then after the data.forEach have another function that loops thru the update array and processes them there with record.submitFields()
Be careful of governance....

NetSuite Suite script - all columns for object

Is there a function in Suitescript using which we would get all the fields or columns belonging to the object (i.e. location, account, transaction etc.)
You can use the function getAllFields() of the record to retrieve all the fields for that record.
var fields = nlapiGetNewRecord().getAllFields()
// loop through the returned fields
fields.forEach(function(fieldName){
var field = record.getField(fieldName);
var fieldlabel = field.getLabel();
if(fieldlabel=='something'){
//do something here
return;
}
}
you can also get the list of available fields for a record here

querying the System Notes in Netsuite

I have been looking for a way to pull the records in the System Notes in NetSuite. The lines below throw an 'INVALID_RCRD_TYPE' error:
var columns = new Array();
columns[0] = new nlobjSearchColumn('internalid').setSort();
var results = nlapiSearchRecord('systemnote', null, null, columns);
I wonder how to reference the System Notes as the first argument of nlapiSearchRecord API. Obviously, it's not called systemnote.
A similar question has been posted here but the System Notes has been incorrectly referenced there.
systemnotes aren't available as record type which is evident from the record browser link
However, you can still get system notes fields using join searches on any record type in NetSuite
eg:
x = nlapiSearchRecord('vendor', null, null,
[new nlobjSearchColumn('date', 'systemNotes'),
new nlobjSearchColumn('name', 'systemNotes'), // Set By
new nlobjSearchColumn('context', 'systemNotes'),
new nlobjSearchColumn('newvalue', 'systemNotes'),
new nlobjSearchColumn('oldvalue', 'systemNotes'),
])
x[0].getValue('name', 'systemNotes'); //gives the set by value
Thanks for your responses guys. I finally managed to query the System Notes using the code below. I thought I should share it in case someone else wants to accomplish the same job. I created a RESTlet in NetSuite using the below code that returns the list of merged customer records merged after a given date.
I created a new search with ID customsearch_mergedrecords and in Criteria tab, added a filter on 'System Notes: NewValue' where the description is 'starts with Merged with duplicates:' and in the Results tab, I added the columns I needed.
Note that you need to create the new search on Customer, not on System Notes. System Notes is hooked up in the search using join (the second argument in nlobjSearchFilter constructor).
function GetMergedRecordsAfter(input) {
var systemNotesSearch = nlapiLoadSearch('customer', 'customsearch_mergedrecords');
var filters = new Array();
filters.push(new nlobjSearchFilter('date', 'systemNotes', 'notbefore', input.fromdate));
systemNotesSearch.addFilters(filters);
var resultSet = systemNotesSearch.runSearch();
var searchResultJson = [];
resultSet.forEachResult(function (searchResult){
var searchColumns = resultSet.getColumns();
searchResultJson.push({
ID: searchResult.getValue(searchColumns[0]),
Name: searchResult.getValue(searchColumns[1]),
Context: searchResult.getValue(searchColumns[2]),
Date: searchResult.getValue(searchColumns[3]),
Field: searchResult.getValue(searchColumns[4]),
NewValue: searchResult.getValue(searchColumns[5]),
OldValue: searchResult.getValue(searchColumns[6]),
Record: searchResult.getValue(searchColumns[7]),
Setby: searchResult.getValue(searchColumns[8]),
Type: searchResult.getValue(searchColumns[9]),
InternalId: searchResult.getValue(searchColumns[10])
});
return true;
});
return searchResultJson;
}

nodejs: save function in for loop, async troubles

NodeJS + Express, MongoDB + Mongoose
I have a JSON feed where each record has a set of "venue" attributes (things like "venue name" "venue location" "venue phone" etc). I want to create a collection of all venues in the feed -- one instance of each venue, no dupes.
I loop through the JSON and test whether the venue exists in my venue collection. If it doesn't, save it.
jsonObj.events.forEach(function(element, index, array){
Venue.findOne({'name': element.vname}, function(err,doc){
if(doc == null){
var instance = new Venue();
instance.name = element.vname;
instance.location = element.location;
instance.phone = element.vphone;
instance.save();
}
}
}
Desired: A list of all venues (no dupes).
Result: Plenty of dupes in the venue collection.
Basically, the loop created a new Venue record for every record in the JSON feed.
I'm learning Node and its async qualities, so I believe the for loop finishes before even the first save() function finishes -- so the if statement is always checking against an empty collection. Console.logging backs this claim up.
I'm not sure how to rework this so that it performs the desired task. I've tried caolan's async module but I can't get it to help. There's a good chance I'm using incorrectly.
Thanks so much for pointing me in the right direction -- I've searched to no avail. If the async module is the right answer, I'd love your help with how to implement it in this specific case.
Thanks again!
Why not go the other way with it? You didn't say what your persistence layer is, but it looks like mongoose or possibly FastLegS. In either case, you can create a Unique Index on your Name field. Then, you can just try to save anything, and handle the error if it's a unique index violation.
Whatever you do, you must do as #Paul suggests and make a unique index in the database. That's the only way to ensure uniqueness.
But the main problem with your code is that in the instance.save() call, you need a callback that triggers the next iteration, otherwise the database will not have had time to save the new record. It's a race condition. You can solve that problem with caolan's forEachSeries function.
Alternatively, you could get an array of records already in the Venue collection that match an item in your JSON object, then filter the matches out of the object, then iteratively add each item left in the filtered JSON object. This will minimize the number of database operations by not trying to create duplicates in the first place.
Venue.find({'name': { $in: jsonObj.events.map(function(event){ return event.vname; }) }}, function (err, docs){
var existingVnames = docs.map(function(doc){ return doc.name; });
var filteredEvents = jsonObj.events.filter(function(event){
return existingVnames.indexOf(event.vname) === -1;
});
filteredEvents.forEach(function(event){
var venue = new Venue();
venue.name = event.vname;
venue.location = event.location;
venue.phone = event.vphone;
venue.save(function (err){
// Optionally, do some logging here, perhaps.
if (err) return console.error('Something went wrong!');
else return console.log('Successfully created new venue %s', venue.name);
});
});
});

Resources