sorting 2d array in node js - node.js

From the following code I am getting the appropriate output, but I want the data to come in sorted form i.e the most recent data must come on top. The data must be sorted in descending order according to the difference of current date and 'win_date'.I am new to node.js..earlier in PHP I used to do this by using function array_multisort. Can someone suggest the alternative to do the same in nodejs.
var post=[];
var sql2 ="SELECT `post_id`, `user_id`, `post`, `votes_count`, `win_date` FROM `tb_winning_posts` WHERE `group_id`=?";
connection.query(sql2,[groupId],function(err, result) {
});
for(var i=0;i<result.length;i++)
{
var timeDiff = getTimeDifference(result[i].win_date); //returns diff of cur date & given date in day,hour,min
post.push({"post_id":result[i].post_id,"post":result[i].post,"votes":result[i].votes_count,"date":timeDiff});
}
console.log(post); //getting the data in order as stored in database

Based on the answer https://stackoverflow.com/a/8837511/1903116
post.sort(function(a, b){
var keyA = a.date, keyB = b.date;
if(keyA < keyB) return 1;
if(keyA > keyB) return -1;
return 0;
});
console.log (post);

Related

How get Lot/Serial number in Netsuite SuiteScript 2.0 for Inventory Adjustment Transaction?

I'm trying to get the serial numbers from a inventory adjustment in a user event script. The following code works very well for me when the amount to adjust is positive, but not when it is negative.
var invDet = transaction.getSublistSubrecord({sublistId:'inventory',
fieldId:'inventorydetail',
line:x});
for(var y = 0; y = invDet.getLineCount('inventoryassignment'); y++) {
var lotNumber = invDet.getSublistValue({sublistId:'inventoryassignment',
fieldId:'receiptinventorynumber',
line:y});
log.debug('lotNumber', lotNumber);
}
When adjust quantity is negative, receiptinvetorynumber is empty
I have tried using field id equal to 'issueinventorynumber' or 'binnunber' but the returned value is empty.
I found the following comment in a NetsuiteHub forum...
In 2.0 the getValue call returns the internal ID of the serial/lot number and the getText equivalent does not work. Depending on the exact logic you need to execute for the obtained numbers you might need to call a subsequent saved search to obtain the actual serial/lot numbers and not internal IDs (an 'inventorynumber' search will do the trick).
I tried this...
try{
var internalId = invdet.getSublistValue({sublistId:'inventoryassignment',fieldId:'internalid', line:y});
search.create({type:'inventorynumber', filters:[
['internalid', 'is', internalId]
], columns:['inventorynumber']}).run().each(function (result) {
binText = result.getValue('inventorynumber');
log.debug('binText', binText);
});
} catch(e) {
log.debug('Error', e.message);
throw e.message;
}
I am too inexperienced to make this work. I appreciate any help you can give me.
Thanks.
The challenge is that this area of the NetSuite API is not well documented. However, I pushed through it through trial and error and search hours.
var invDet = transaction.getSublistSubrecord({sublistId:'inventory',
fieldId:'inventorydetail',
line:x});
for(var y = 0; y = invDet.getLineCount('inventoryassignment'); y++) {
var Qty = invdet.getSublistValue({sublistId:'inventoryassignment',
fieldId:'quantity',
line:y});
var lotNumber = '';
if(Qty < 0)
{
var ivnNumId = nvdet.getSublistValue({sublistId:'inventoryassignment',
fieldId:'issueinventorynumber',
line:y});
if(ivnNumId !== '')
{
var invNum = record.load({type: 'inventorynumber',id:ivnNumId});
lotNumber = invNum.getValue({fieldId: 'inventorynumber'});
}
}
else
{
lotNumber = invdet.getSublistValue({sublistId:'inventoryassignment',
fieldId:'receiptinventorynumber',
line:y});
}
log.debug('lotNumber', lotNumber);
}
This information was very helpful in ss1.0
I hope it is useful to someone

Convert geojson polygons into points with node using query-overpass and turf.js

I use the node module "query-overpass" for a query to get farmshops from openstreetmaps. I would like to convert all polygons to points inside this script. I use turf.js to get the centroids of theese polygons, but I am not able to change the objects in a permanent way. This is my code so far:
const query_overpass = require("query-overpass");
const turf = require ("turf");
const fs = require("fs")
let test
let filename = "data/test.js"
let bbox = "48.91821286473131,8.309097290039062,49.0610446187357,8.520584106445312";
console.log('starting query for ' +filename)
console.log('bbox: ' +bbox)
let query = `
[out:json][timeout:250];
// gather results
(
// query part for: “vending=milk”
node["vending"="milk"](${bbox});
way["vending"="milk"](${bbox});
relation["vending"="milk"](${bbox});
// query part for: “shop=farm”
node["shop"="farm"](${bbox});
way["shop"="farm"](${bbox});
relation["shop"="farm"](${bbox});
// query part for: “vending=food”
node["vending"="food"](${bbox});
way["vending"="food"](${bbox});
relation["vending"="food"](${bbox});
);
// print results
out body;
>;
out skel qt;
`;
// query overpass, write result to file
query_overpass(query, (error, data) => {
data = JSON.stringify(data , null, 1)
console.log(data)
test = JSON.parse(data)
//create centroids for every polyon and save them as a point
for (var i = 0; i < test.features.length; i++) {
console.log("Log: " +test.features[i].geometry.type)
console.log("Log: " +test.features[i].properties.name)
if (test.features[i].geometry.type === "Polygon"){
console.log("polygon detected")
var centroid = turf.centroid(test.features[i]);
var lon = centroid.geometry.coordinates[0];
var lat = centroid.geometry.coordinates[1];
console.log(" lon: " +lon +" lat: " +lat)
test.features[i].geometry.type = 'Point'
//delete Polygon structure and insert centroids as new points here
console.log("polygon deleted and changed to point")
}
}
console.log(test)
fs.writeFile(filename, `var file = ${test};` , ["utf-8"], (error, data) => {if (error) {console.log(error)}})
}, {flatProperties: true}
)
It seems like I can change things inside of the for loop, but they do not appear when the data is saved later. It is basically a question of how to edit json objects properly, but I can't figure out why this doesnt work here at all.
So there are basically two questions:
Why cant I override geometry.type in the example above?
How can I delete the old polygon and add a new point to a feature?
Thanks for any help.
That's quite complicated... Why don't you let Overpass API do this job and use out center; instead of out body;>;out skel qt; to return the center points of all nodes, ways and relations. You can use overpass-turbo.eu to try this out first.

Inventory Assignment Sublist doesn't react to Suitescript

I'm currently having some trouble with Client-Side Scripting of an Inventory Detail Subrecord on an Assembly Build. As you know, Assembly Builds have two Inventory Details. The one in the top right corner works as expected, and I can access every field with Suitescript.
I'm having trouble with the bottom Inventory Detail though. I'm able to access it and use nlapiGetFieldValue() just fine. However, when I access the sublist, I am only able to look up the value of 'id'.
These are the fields that are supposed to exist, along with a less documented one called "receiptinventorynumber".
Here is my code:
//get the line items in the bottom inventory details
var bottom_line_items = [];
for(var line_index = 0; line_index < nlapiGetLineItemCount("component"); line_index++)
{
var bottom_inv_detail = nlapiViewLineItemSubrecord("component", 'componentinventorydetail', line_index+1);
if(bottom_inv_detail != null)
{
var bottom_line_count = bottom_inv_detail.getLineItemCount('inventoryassignment');
for(var index =0; index < bottom_line_count; index++)
{
bottom_inv_detail.selectLineItem('inventoryassignment', index+1);
var sn = bottom_inv_detail.getCurrentLineItemValue('inventoryassignment', 'receiptinventorynumber');
bottom_line_items.push(sn);
}
}
}
console.log(bottom_line_items);
Here is the result of executing it in the browser console:
As you can see, 'id', and 'internalid' work. 'receiptinventorynumber' does not. Neither do any of the other fields.
Because of my use case, I cannot wait for the record to be saved on the server. I have to catch this client side. Any suggestions are appreciated.
It has been a long time since I have worked with Inventory Detail subrecord, but I think there is another field called 'assigninventorynumber'. Have you tried using that?
Just was able to answer my own question, but it did end up involving a server-side search. I'm pretty sure it works as I wanted it to, but I am still involved in testing it. In essence, I grabbed the field 'issueinventorynumber', which had an id. That id was the internalid of a 'Inventory Serial Number', which I was able to perform a search for to get the actual number. Here's the resulting code:
//get the line items in the bottom inventory details
var bottom_line_ids = [];
for(var line_index = 0; line_index < nlapiGetLineItemCount("component"); line_index++)
{
var bottom_inv_detail = nlapiViewLineItemSubrecord("component", 'componentinventorydetail', line_index+1);
if(bottom_inv_detail != null)
{
var bottom_line_count = bottom_inv_detail.getLineItemCount('inventoryassignment');
for(var index =0; index < bottom_line_count; index++)
{
bottom_inv_detail.selectLineItem('inventoryassignment', index+1);
var sn = bottom_inv_detail.getCurrentLineItemValue('inventoryassignment', 'issueinventorynumber');
bottom_line_ids.push(sn);
}
}
}
//do search to identify numbers of bottom serial numbers
var columns = [new nlobjSearchColumn('inventorynumber')];
var filters = []
for(var index = 0; index < bottom_line_ids.length; index++)
{
filters.push(['internalid', 'is', bottom_line_ids[index]]);
filters.push('or');
}
//remove the last 'or'
if(filters.length > 0)
{
filters.pop();
}
var search = nlapiCreateSearch('inventorynumber', filters, columns);
var results = search.runSearch().getResults(0,1000);
bottom_line_items = []
if(results.length != bottom_line_ids.length)
{
//if you get to this point, pop an error as the 'issueinventorynumber' we pulled is associated with multiple serial numbers
//you can see which ones by doing a 'Inventory Serial Number' Saved Search
//this is a serious problem, so we'd have to figure out what to do from there
}
for(var index = 0; index < results.length; index++)
{
bottom_line_items.push(results[index].getValue('inventorynumber'));
}
console.log(bottom_line_items);

Column Value in search api

I want to get the value from a Item sublist of Sales Order record.
But unable to get it. Though I can get the value of entity fields of the SO record.
Below is the snippet of the code:
var filters = new Array();
filters[0] = new nlobjSearchFilter("mainline",null,"is","T");
var column=new Array();
column[0] = new nlobjSearchColumn("trandate");
column[1] = new nlobjSearchColumn("item");
column[2] = new nlobjSearchColumn("cust_col_1");
var result = nlapiSearchRecord('salesorder', null, filters, column);
for(var i = 0; i<result.length; i++)
{
var col = result[i].getAllColumns();
var date = result[i].getFieldValue("trandate"); //I get this
var item_id = result[i].getLineItemValue("item", "item", i+1); // I don't get this
var cust_col = result[i].getLineItemValue("item", "cust_col_1", i+1); //I don't get this
}
I think I am defining the columns wrong.
This part
var item_id = result[i].getLineItemValue("item", "item", i+1); // I don't get this
var cust_col = result[i].getLineItemValue("item", "cust_col_1", i+1); //I don't get this
is also wrong, you use this syntax if you have loaded the record but for search results you just use
result[i].getValue('cust_col_1")
By specifying the filter new nlobjSearchFilter("mainline",null,"is","T"), you're basically telling the search that you don't want any line item data. This means that you will be unable to read any column data, custom or otherwise.
The mainline filter parameter has basically three options, 'F' means you want the line item details. 'T' means you just want the header data. Leaving this filter out will return one row for the header information and one row for each line item on the transaction.

Get records by page wise in Netsuite using RESTlet

i want to get all the records in particular record type , but i got 1000 only.
This is the code I used.
function getRecords() {
return nlapiSearchRecord('contact', null, null, null);
}
I need two codes.
1) Get whole records at a single time
2) Get the records page wise by passing pageindex as an argument to the getRecords [1st =>0-1000 , 2nd =>1000 - 2000 , ...........]
function getRecords(pageIndex) {
.........
}
Thanks in advance
you can't get whole records at a time. However, you can sort results by internalid, and remember the last internalId of 1st search result and use an additional filter in your next search result.
var totalResults = [];
var res = nlapiSearchRecord('contact', null, null, new nlobjSearchColumn('internalid').setSort()) || [];
lastId = res[res.length - 1].getId();
copyAndPushToArray(totalResult, res);
while(res.length < 1000)
{
res = nlapiSearchRecord('contact', null, ['internalidnumber', 'greaterthan', lastId], new nlobjSearchColumn('internalid').setSort());
copyAndPushToArray(totalResult, res);
lastId = res[res.length - 1].getId();
}
Beware, if the number of records are high you may overuse governance limit in terms of time and usage points.
If you remember the lastId you can write a logic in RESTlet to take id as param and then use that as additional filter to return nextPage.
You can write a logic to get nth pageresult but, you might have to run search uselessly n-1 times.
Also, I would suggest to use nlapiCreateSearch().runSearch() as it can return up to 4000 records
Here is another way to get more than 1000 results on a search:
function getItems() {
var columns = ['internalid', 'itemid', 'salesdescription', 'baseprice', 'lastpurchaseprice', 'upccode', 'quantityonhand', 'vendorcode'];
var searchcolumns = [];
for(var col in columns) {
searchcolumns.push(new nlobjSearchColumn(columns[col]));
}
var search = nlapiCreateSearch('item', null, searchcolumns);
var results = search.runSearch();
var items = [], slice = [], i = 0;
do {
slice = results.getResults(i, i + 1000);
for (var itm in slice) {
var item = {};
for(var col in columns) { item[columns[col]] = slice[itm].getValue(columns[col]); } // convert nlobjSearchResult into simple js object
items.push(item);
i++;
}
} while (slice.length >= 1000);
return items;
}

Resources