Can't find specific address for specific customer by internal id - netsuite

I'm trying to find the specific address by internal id from specific customer. Currently I'm trying to fetch 'address1' and 'address2' columns.
function getAddrById(addressid,invcustomerid) {
try {
var filters = new Array();
filters[0] = new nlobjSearchFilter('internalid', null, 'is', invcustomerid);
var columns = new Array();
columns[0] = new nlobjSearchColumn('address1');
var searchResult = nlapiSearchRecord('customer', null, filters , columns);
debugger;
if (!searchResult || searchResult.length < 1) {
nlapiLogExecution('DEBUG', 'XML HEAD', 'not supported address');
return;
}
if(searchResult) {
for (var i = 0 ; i < searchResult.length; i++) {
alert(searchResult[i].getValue('address1'));
};
};
} catch(e) {
nlapiLogExecution('ERROR', 'Try/catch error', e.message);
}
}
... here I get all address subrecords for specific customer, but I want only one specified by internal id, not to list all associated addresses from the customer.

columns[0] = new nlobjSearchColumn('addr1');
should be:
columns[0] = new nlobjSearchColumn('address1');
From your own link, you should be using the internal id from 'Search Columns' list at the bottom of the record, not "Fields".

Related

I'm trying to connect my back end payment to my front end card charge with angular. How can I achieve this?

As you can imagine, stripe and authorize.net and other payment gateway services offer an api that can only be hit via server-side for safety reasons. Currently the documentation for Authorize.net allows for me to create an express node app and then run the command node charge-credit-card.js (which works and gets a 200 response from their api) My question is two parts. How do I connect my server directory (aptly named named AuthorizePaymentNode in the image below this paragraph) with my angular src app directory(aptly named named FoodOrderingApp in the image) to gather the card info on the front end so that I may process a credit card from start to finish? Secondly assuming I get it working in development how and where do I upload my AuthorizePaymentNode directory along with my FoodOrderingApp so that the two work together. Do I do it in two separate places as a friend of mine suggested or can it just be done all at once and in one place?
[https://i.stack.imgur.com/ibUDr.png][1]
charge-credit-card.js (works like a charm when running node charge-credit-card.js)
var ApiContracts = require('authorizenet').APIContracts;
var ApiControllers = require('authorizenet').APIControllers;
var SDKConstants = require('authorizenet').Constants;
var utils = require('./utils.js');
var constants = require('./constants.js');
function chargeCreditCard(callback) {
var merchantAuthenticationType = new ApiContracts.MerchantAuthenticationType();
merchantAuthenticationType.setName(constants.apiLoginKey);
merchantAuthenticationType.setTransactionKey(constants.transactionKey);
var creditCard = new ApiContracts.CreditCardType();
creditCard.setCardNumber('4242424242424242');
creditCard.setExpirationDate('0822');
creditCard.setCardCode('999');
var paymentType = new ApiContracts.PaymentType();
paymentType.setCreditCard(creditCard);
var orderDetails = new ApiContracts.OrderType();
orderDetails.setInvoiceNumber('INV-12345');
orderDetails.setDescription('Product Description');
var tax = new ApiContracts.ExtendedAmountType();
tax.setAmount('4.26');
tax.setName('level2 tax name');
tax.setDescription('level2 tax');
var duty = new ApiContracts.ExtendedAmountType();
duty.setAmount('8.55');
duty.setName('duty name');
duty.setDescription('duty description');
var shipping = new ApiContracts.ExtendedAmountType();
shipping.setAmount('8.55');
shipping.setName('shipping name');
shipping.setDescription('shipping description');
var billTo = new ApiContracts.CustomerAddressType();
billTo.setFirstName('Ellen');
billTo.setLastName('Johnson');
billTo.setCompany('Souveniropolis');
billTo.setAddress('14 Main Street');
billTo.setCity('Pecan Springs');
billTo.setState('TX');
billTo.setZip('44628');
billTo.setCountry('USA');
var shipTo = new ApiContracts.CustomerAddressType();
shipTo.setFirstName('China');
shipTo.setLastName('Bayles');
shipTo.setCompany('Thyme for Tea');
shipTo.setAddress('12 Main Street');
shipTo.setCity('Pecan Springs');
shipTo.setState('TX');
shipTo.setZip('44628');
shipTo.setCountry('USA');
var lineItem_id1 = new ApiContracts.LineItemType();
lineItem_id1.setItemId('1');
lineItem_id1.setName('vase');
lineItem_id1.setDescription('cannes logo');
lineItem_id1.setQuantity('18');
lineItem_id1.setUnitPrice(45.00);
var lineItem_id2 = new ApiContracts.LineItemType();
lineItem_id2.setItemId('2');
lineItem_id2.setName('vase2');
lineItem_id2.setDescription('cannes logo2');
lineItem_id2.setQuantity('28');
lineItem_id2.setUnitPrice('25.00');
var lineItemList = [];
lineItemList.push(lineItem_id1);
lineItemList.push(lineItem_id2);
var lineItems = new ApiContracts.ArrayOfLineItem();
lineItems.setLineItem(lineItemList);
var userField_a = new ApiContracts.UserField();
userField_a.setName('A');
userField_a.setValue('Aval');
var userField_b = new ApiContracts.UserField();
userField_b.setName('B');
userField_b.setValue('Bval');
var userFieldList = [];
userFieldList.push(userField_a);
userFieldList.push(userField_b);
var userFields = new ApiContracts.TransactionRequestType.UserFields();
userFields.setUserField(userFieldList);
var transactionSetting1 = new ApiContracts.SettingType();
transactionSetting1.setSettingName('duplicateWindow');
transactionSetting1.setSettingValue('120');
var transactionSetting2 = new ApiContracts.SettingType();
transactionSetting2.setSettingName('recurringBilling');
transactionSetting2.setSettingValue('false');
var transactionSettingList = [];
transactionSettingList.push(transactionSetting1);
transactionSettingList.push(transactionSetting2);
var transactionSettings = new ApiContracts.ArrayOfSetting();
transactionSettings.setSetting(transactionSettingList);
var transactionRequestType = new ApiContracts.TransactionRequestType();
transactionRequestType.setTransactionType(ApiContracts.TransactionTypeEnum.AUTHCAPTURETRANSACTION);
transactionRequestType.setPayment(paymentType);
transactionRequestType.setAmount(utils.getRandomAmount());
transactionRequestType.setLineItems(lineItems);
transactionRequestType.setUserFields(userFields);
transactionRequestType.setOrder(orderDetails);
transactionRequestType.setTax(tax);
transactionRequestType.setDuty(duty);
transactionRequestType.setShipping(shipping);
transactionRequestType.setBillTo(billTo);
transactionRequestType.setShipTo(shipTo);
transactionRequestType.setTransactionSettings(transactionSettings);
var createRequest = new ApiContracts.CreateTransactionRequest();
createRequest.setMerchantAuthentication(merchantAuthenticationType);
createRequest.setTransactionRequest(transactionRequestType);
//pretty print request
console.log(JSON.stringify(createRequest.getJSON(), null, 2));
var ctrl = new ApiControllers.CreateTransactionController(createRequest.getJSON());
//Defaults to sandbox
//ctrl.setEnvironment(SDKConstants.endpoint.production);
ctrl.execute(function(){
var apiResponse = ctrl.getResponse();
var response = new ApiContracts.CreateTransactionResponse(apiResponse);
//pretty print response
console.log(JSON.stringify(response, null, 2));
if(response != null){
if(response.getMessages().getResultCode() == ApiContracts.MessageTypeEnum.OK){
if(response.getTransactionResponse().getMessages() != null){
console.log('Successfully created transaction with Transaction ID: ' + response.getTransactionResponse().getTransId());
console.log('Response Code: ' + response.getTransactionResponse().getResponseCode());
console.log('Message Code: ' + response.getTransactionResponse().getMessages().getMessage()[0].getCode());
console.log('Description: ' + response.getTransactionResponse().getMessages().getMessage()[0].getDescription());
}
else {
console.log('Failed Transaction.');
if(response.getTransactionResponse().getErrors() != null){
console.log('Error Code: ' + response.getTransactionResponse().getErrors().getError()[0].getErrorCode());
console.log('Error message: ' + response.getTransactionResponse().getErrors().getError()[0].getErrorText());
}
}
}
else {
console.log('Failed Transaction. ');
if(response.getTransactionResponse() != null && response.getTransactionResponse().getErrors() != null){
console.log('Error Code: ' + response.getTransactionResponse().getErrors().getError()[0].getErrorCode());
console.log('Error message: ' + response.getTransactionResponse().getErrors().getError()[0].getErrorText());
}
else {
console.log('Error Code: ' + response.getMessages().getMessage()[0].getCode());
console.log('Error message: ' + response.getMessages().getMessage()[0].getText());
}
}
}
else {
console.log('Null Response.');
}
callback(response);
});
}
if (require.main === module) {
chargeCreditCard(function(){
console.log('chargeCreditCard call complete.');
});
}
module.exports.chargeCreditCard = chargeCreditCard;
cart.ts
let total = item.price * item.quantity;
item.options.forEach(option => (total += option.value * item.quantity));
return total;
}
get totalAmount() {
let total = 0;
this.cart.forEach(item => (total += this.getItemTotal(item)));
return total;
}```
[1]: https://i.stack.imgur.com/ibUDr.png
using the accept suite seems to be the most logical answer

RCRD_DSNT_EXIST while creating user event script with aftersubmit function

I'm trying to write a user event script which loads the current record and populates a line item value through search after submit record. But, it is giving an error RCRD_DSNT_EXIST, even though the record exists.
function afterSubmit_SO(type){
try
{
//var record_type = nlapiGetRecordType();
var recordID = nlapiGetRecordId();
var context = nlapiGetContext();
var recordOBJ = nlapiLoadRecord('salesorder',recordID);
var source = context.getExecutionContext();
if(source == 'userinterface')
{
var line_count = recordOBJ.getLineItemCount('item');
nlapiLogExecution('DEBUG', 'line count ', line_count);
for(var i = 1; i <= line_count; i++)
{
var itemID = recordOBJ.getLineItemValue('item','item',i);
nlapiLogExecution('DEBUG', 'item ID', itemID);
var filter = new Array();
filter[0] = new nlobjSearchFilter('internalid', null, 'is', itemID);
var columns = new Array();
columns[0] = new nlobjSearchColumn('custitem_web_market_availability');
var a_search_results = nlapiSearchRecord('item',null,filter,columns);
if(a_search_results)
{
for(var x = 0; x < a_search_results.length; x++)
{
var item_web_availability = a_search_results[x].getText('custitem_web_market_availability');
nlapiLogExecution('DEBUG', 'value', item_web_availability);
}
} recordOBJ.setLineItemValue('item','custcol_web_item_availability',i,item_web_availability);
}
var submitID = nlapiSubmitRecord(recordOBJ, true, true);
}
}
catch(exception)
{
nlapiLogExecution('DEBUG','Exception Caught ','' + exception);
}
return true;
}```
It could be that your script is executing on the delete operation. I did not see any checking for this in the code you provided. If it is a delete operation then the after submit user event script wont be able to load the deleted record, this is why you get the error.
The type parameter of your afterSubmit function should contain the operation type. You can something like if (type == 'delete') { return true;} at the top of your script.

Suitescript Netsuite create salesorder

I am not a suitescript coder. I have JS knowledge. A while back i came across a script which would create an SO for me. The script was similar to the one attached, just that it had the else condition for when "Typeof Value=='object'
function getItems(datain) {
var err = new Object();
// Validate if mandatory record type is set in the request
if (!datain.recordtype)
{
err.status = "failed";
err.message= "missing recordtype";
return err;
}
var record = nlapiCreateRecord(datain.recordtype);
for (var fieldname in datain)
{
if (datain.hasOwnProperty(fieldname))
{
if (fieldname != 'recordtype' && fieldname != 'id')
{
var value = datain[fieldname];
nlapiLogExecution('DEBUG', fieldname);
// ignore other type of parameters​
if (value && typeof value != 'object')
{
record.setFieldValue(fieldname, value);
}
}
}
}
var recordId = nlapiSubmitRecord(record);
nlapiLogExecution('DEBUG','id='+recordId);
// returns the created record in JSON format​
var nlobj = nlapiLoadRecord(datain.recordtype,recordId);
return nlobj;
}
Can someone help me fill the else section where I would process the Items array when the recordtype would be 'salesorder'
Greatly appreciate your help.
Thanks
Something like this:
nlapiSelectNewLineItem('item');
nlapiSetCurrentLineItemValue('item', 'item', 380, true, true);
nlapiSetCurrentLineItemValue('item', 'location', 102, true, true);
nlapiCommitLineItem('item');

get name from id inside loop in node js

hello all I am new to node js and mongo db so I am facing a problem which is written above want to match an id from an array and get all the record of matching id , but thats not working i have already tried for loop but that is taking too much time so i am looking for some kind of query by which I pass id and get the matching results i have below function also where i can pass id and get the matching result but i don't know how to call that .
exports.getDistrictFromId = function(req, res, next) {
var distId = req.params.id;
districtslib.getDistricts({_id: utils.toObjectId(distId)}, function(err, district) {
if (err) {
return next(err);
}
req.store.district = district;
next();
});
};
Here is my code
exports.getCompleteTeachersList = function(req, res, next) {
var query = req.store.get('query');
var teacherQuery = {enabled: true};
var searchQuery = '';
if (!_.isUndefined(query)) {
// schoolQuery = {'name':new RegExp(query.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"),'i')};
//{ $text: { $search: "amit hinduja"} }
//teacherQuery = {enabled: true,$or:[{firstName:new RegExp(query.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"),'i')},{lastName:new RegExp(query.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"),'i')}]};
if(query.trim() != '') {
teacherQuery = {enabled: true,$text: { $search: query} };
searchQuery = query;
}
}
teacherslib.getTeachers(teacherQuery, function(err, teachers) {
if (err) {
return next(err);
}
var schools = req.store.get('schools');
for(var i = 0; i < teachers.length; i++) {
teachers[i].schoolName = "";
for(var j = 0; j < schools.length; j++) {
if (teachers[i].schoolId.toString() === schools[j]._id.toString()) {
teachers[i].schoolName = schools[j].name;
teachers[i].distId = "";
var districts = req.store.get('districts');
console.log(schools[j].distId);
// i want to get the array of matching district id `schools[j].distId` from the district array from `var districts = req.store.get('districts');` this line
break;
}
}
}
req.store.set('searchQuery', searchQuery);
req.store.set('teachers', teachers);
//req.store.set('districts', districts);
next();
});
};
Collection structure is like this
1) distid is coming in schools collection
using distid get all the matching record from district
2)district array has countyid and from that county id has to get data from the county collection
Instead of looping inside a loop, i would suggest you look into the $lookup operator of the aggregation framework. Here you can perform the lookup server side.

How to query two collection in mongoose on nodeJs?

hi am new to nodeJs i have to query a table from the result of the query, i have to query another table. i tried the code as follows but it returns only null.
action(function getpositions(req){
var namearray = [];
NHLPlayerStatsDaily.find ({"created_at": {$gt: new Date(y+"-"+m+"-"+d)}}, function(err,position){
if(!err)
{
for (i=0;i< position.length; i++)
{
var obj = JSON.stringify(position[i]);
var pos = JSON.parse(obj);
var p = pos["player_stats_daily"]["content"]["team_sport_content"]["league_content"]["season_content"]["team_content"]["team"]["id"]
NHLTeam.find({"sdi_team_id": p}, "first_name nick_name short_name sport_id", function(err, team){
if (!err){
var obj = JSON.stringify(team);
var pos = JSON.parse(obj);
namearray.push(team)
}
})
}
return send(namearray);
}
})
})
if i just push "p" it shows the result and when am query "NHLTeam" in separate function it also shows the result. when querying a collection with in collection it return null. how to query a collection within a collection in mongoose. thanks in advance.
This is not a query problem, it is callback issue. The send(namearray) is called before any of the NHLTeam queries in the loop are completed (remember the result of these queries is passed to callback asynchronously).
What you can do is this (basically tracking when all callbacks are completed):
NHLPlayerStatsDaily.find ({"created_at": {$gt: new Date(y+"-"+m+"-"+d)}}, function(err,position){
if(!err)
{
var total = position.length;
for (i=0;i< position.length; i++)
{
var obj = JSON.stringify(position[i]);
var pos = JSON.parse(obj);
var p = pos["player_stats_daily"]["content"]["team_sport_content"]["league_content"]["season_content"]["team_content"]["team"]["id"]
NHLTeam.find({"sdi_team_id": p}, "first_name nick_name short_name sport_id", function(err, team){
total--;
if (!err){
var obj = JSON.stringify(team);
var pos = JSON.parse(obj);
namearray.push(team);
}
if(total == 0)
send(namearray);
})
}
}
})

Resources