Looping Through a Group in Suitescript 2.0 - suitescript2.0

I am passing sales orders grouped by item into a function. I need to load the sales orders to modify the sales order record that it has already been processed. How would I go about getting all sales orders grouped under the item?
var itemId = result.getValue({
name: 'item',
summary: 'GROUP'
});
The above code gets me the item id for what the orders in the given result are being grouped by. There could be any number of sales within a single group.

Running a grouped saved search in SuiteScript doesn't give you the ability to "drill down" like you can when running a similar search in the user interface. As soon as you have a summary criteria for any column in a saved search, Netsuite requires that all your columns be summarized. If you want to get the internal IDs for the Sales Orders, then they will have to be returned as a summarized column in your saved search code.
Something like this:
const searchObj = search.create({
type: search.Type.SALES_ORDER,
filters: [
['mainline', 'is', 'F']
//,'AND', any other filters you need...
],
columns: [
search.createColumn({
name: "item",
summary: "GROUP"
}),
search.createColumn({
name: "formula(text)",
summary: "MAX",
formula: "ns_concat({internalid})"
})
]
}).run().each(function(result) {
const itemId = result.getValue({name: "item", summary: "GROUP"})
const salesOrderIds = result.getValue({
name: "formula(text)",
summary: "MAX",
formula: "ns_concat({internalid})"
}).split(',')
return true
})

Related

Query MongoDB Aggregation framework with Golang

I have in a collection stores , products and many prices (for store-products there are many prices) of the products in MongoDB
I have to find out min price from a product in a store in the last 30 days with the help of go
I have built the following aggregation pipeline
pipeline := []bson.M{
bson.D{
"$group", bson.D{
{
"_id", bson.D{
{
Key: "storeId",
Value: "$storeUd",
},
{
Key: "productId",
Value: "$productId",
},
},
},
minPrice : {
Key: "min",
Value: "$price",
},
},
} <---
}
But go compiler tell me in the line that I marked with an arrow (<---) there is a mistake
syntax error: unexpected newline in composite literal; possibly missing comma or }
I would like to calculate something like
select min(price)
from prices
group by storeId , productId
Please can you tell me what is wrong?
Thanks,
Aurel
I added }, but what I get you can see in the attached picture - the next declaration (var ... ) is in red ....

Get Empty Rows in TypeORM

I'm trying to write a typeORM query which includes multiple where clauses. I am able to achieve this via where option as follows:
const categories = [
{ name: 'master', categoryTypeId: 2, parentId: 1, locationId: null },
{ name: 'food', categoryTypeId: 3, parentId: null, locationId: null }];
const rows = await Repo.find({
where: categories.map((category) => ({
name: category.name,
categoryTypeId: category.categoryTypeId,
locationId: category.locationId
})),
});
I would want to maintain the mapping b/w the input array and the rows returned. For example, I know that the second category doesn't exist in the DB. I would want to have an empty object in the rows variable so that I know which categories didn't yield any result.
Upon research I have found that we can do something with SQL as mentioned here. But, I'm not sure how do I translate into typeORM if I can.

How to search for customer internal id using customer name? Suitescript 2.0

As titled, how to search Netsuite internal id by other fields (ex: customer name)? Thanks
You can use the following to fetch customer-internalid
var customerSearchResult = search.create({
type: 'customer',
filters: [{ name: 'entityid', operator: 'is', values: CUSTOMER_NAME }]
}).run().getRange({ start: 0, end: 1 });
var customerInternalId = customerSearchResult[0].id;
where, entityid is id of customer name field and CUSTOMER_NAME is customer name that you want to search

Setting the tax code on a Sales Order Item in SuiteScript 2.0

I have created a script to add a Finance Charge item to my sales orders when they are edited but can't get it to set the tax Code. Also the line is not committing (because of the tax code issue?)
I have tried Internal IDs and names but am stuck
Any help?
define(['N/currentRecord'],
function(currentRecord) {
function AddFinanceCharge() {
try {
var record = currentRecord.get();
record.selectNewLine({ //add a line to a sublist
sublistId: 'item' //specify which sublist
});
record.setCurrentSublistValue({ //set item field
sublistId: 'item',
fieldId: 'item',
value: 1003 //replace with item internal id
});
record.setCurrentSublistValue({
sublistId: 'item',
fieldId: 'quantity',
value: 1 //replace with quantity
});
record.setCurrentSublistValue({
sublistId: 'item',
fieldId: 'taxCode',
value: 'VAT:S-GB'
});
record.commitLine({ //writes the line entry into the loaded record
sublistId: 'item'
});
log.debug ({
title: 'Success',
details: 'Alert displayed successfully'
});
} catch (e) {
log.error ({
title: e.name,
details: e.message
});
}
}
return {
pageInit: AddFinanceCharge
};
});
If you only use Tax codes, not Tax Groups I believe you can create a search to find internal ids:
var taxitemSearchObj = search.create({
type: "salestaxitem",
columns: ["internalid", "country", "rate"],
filters: [['firstFilter', 'firstComparisonOperator', firstValue]], 'and', ['anotherFilter', 'anotherComparisonOperator', anotherValue]] // i.e. ['itemid', 'is' 'VAT:S-GB'],
});
You can find available search filters in the NS record browser-
here (2019.2 version)
'VAT:S-GB' might be itemid? Then:
var taxCodeInternalId = taxitemSearchObj.run().getRange(0,1)[0].id // If you know there is only 1 code matching the search query
record.setCurrentSublistValue({
sublistId: 'item',
fieldId: 'taxcode', // FYI I'm not sure if capitalization matters here but I downcased the capital C
value: taxCodeInternalId
});
**Disclaimer - Does NOT work with mixed tax code / tax groups. To get that you'll need to make the search dynamic ('taxgroup' or 'salestaxitem'). Unfortunately Netsuite will overwrite your taxcode internal ID if "ENABLE TAX LOOKUP ON SALES AND PURCHASES" is selected in your tax preferences (Setup > Accounting > Tax Setup - set per nexus). If this option is not selected you'll need to make sure to set a tax code on every line item.
you have to pass internal id of the tax code if you re using setValue, use SetText instead of setValue and check.

Get Most Recent Column Value With Nested And Repeated Fields

I have a table with the following structure:
and the following data in it:
[
{
"addresses": [
{
"city": "New York"
},
{
"city": "San Francisco"
}
],
"age": "26.0",
"name": "Foo Bar",
"createdAt": "2016-02-01 15:54:25 UTC"
},
{
"addresses": [
{
"city": "New York"
},
{
"city": "San Francisco"
}
],
"age": "26.0",
"name": "Foo Bar",
"createdAt": "2016-02-01 15:54:16 UTC"
}
]
What I'd like to do is recreate the same table (same structure) but with only the latest version of a row. In this example let's say that I'd like to group by everything by name and take the row with the most recent createdAt.
I tried to do something like this: Google Big Query SQL - Get Most Recent Column Value but I couldn't get it to work with record and repeated fields.
I really hoped someone from Google Team will provide answer on this question as it is very frequent topic/problem asked here on SO. BigQuery definitelly not friendly enough with writing Nested / Repeated stuff back to BQ off of BQ query.
So, I will provide the workaround I found relatively long time ago. I DO NOT like it, but (and that is why I hoped for the answer from Google Team) it works. I hope you will be able to adopt it for you particular scenario
So, based on your example, assume you have table as below
and you expect to get most recent records based on createdAt column, so result will look like:
Below code does this:
SELECT name, age, createdAt, addresses.city
FROM JS(
( // input table
SELECT name, age, createdAt, NEST(city) AS addresses
FROM (
SELECT name, age, createdAt, addresses.city
FROM (
SELECT
name, age, createdAt, addresses.city,
MAX(createdAt) OVER(PARTITION BY name, age) AS lastAt
FROM yourTable
)
WHERE createdAt = lastAt
)
GROUP BY name, age, createdAt
),
name, age, createdAt, addresses, // input columns
"[ // output schema
{'name': 'name', 'type': 'STRING'},
{'name': 'age', 'type': 'INTEGER'},
{'name': 'createdAt', 'type': 'INTEGER'},
{'name': 'addresses', 'type': 'RECORD',
'mode': 'REPEATED',
'fields': [
{'name': 'city', 'type': 'STRING'}
]
}
]",
"function(row, emit) { // function
var c = [];
for (var i = 0; i < row.addresses.length; i++) {
c.push({city:row.addresses[i]});
};
emit({name: row.name, age: row.age, createdAt: row.createdAt, addresses: c});
}"
)
the way above code works is: it implicitely flattens original records; find rows that belong to most recent records (partitioned by name and age); assembles those rows back into respective records. final step is processing with JS UDF to build proper schema that can be actually written back to BigQuery Table as nested/repeated vs flatten
The last step is the most annoying part of this workaround as it needs to be customized each time for specific schema(s)
Please note, in this example - it is only one nested field inside addresses record, so NEST() fuction worked. In scenarious when you have more than just one
field inside - above approach still works, but you need to involve concatenation of those fields to put them inside nest() and than inside js function to do extra splitting those fields, etc.
You can see examples in below answers:
Create a table with Record type column
create a table with a column type RECORD
How to store the result of query on the current table without changing the table schema?
I hope this is good foundation for you to experiment with and make your case work!