I am trying to assert and print the response, for that need help.
Below is response body:
{
"createdIncidents":[
{
"incidentRef":"I0000000",
"personName":"API API",
"personType":"Patient"
},
{
"incidentRef":"I0000000",
"personName":"Ballarat HelpDesk",
"personType":"Staff"
},
{
"incidentRef":"I0000000",
"personName":"test api",
"personType":"Visitor"
},
{
"incidentRef":"I0000000",
"personName":null,
"personType":"Hazard"
}
]
}
I am trying to print incidentRef and personType together in a string.
For that, I am using this code:
var data = JSON.parse(responseBody);
data.createdIncidents.forEach(function(incident, personT) {
var personType = "personType" + personT.personType;
var incidents = "incidentRef" + incident.incidentRef;
var pt = tests["incidents created for " + personType ] = 'personType';
var inc = tests["incidents number is " + incidents] = 'incidents';
tests["incidents created for" +inc && + pt ];
});
Here it is not reading the second items inside the function.
In a separate function declaration it works fine.
I want to print it as:
"incidentRef": "I0000000 is created for "personType": "Hazard""
This would log each item from the createdIncidents array to the console - Unsure what you're actually trying to assert against though:
_.each(pm.response.json().createdIncidents, (arrItem) => {
console.log(`Incident Ref: ${arrItem.incidentRef} is created for Person Type: ${arrItem.personType}`)
})
Given your response data, this would be the output:
Incident Ref: I0000000 is created for Person Type: Patient
Incident Ref: I0000000 is created for Person Type: Staff
Incident Ref: I0000000 is created for Person Type: Visitor
Incident Ref: I0000000 is created for Person Type: Hazard
This could be wrapped in a pm.test() and the different items can be asserted against using the pm.expect() syntax.
This is very basic and is very hardcoded but it would check the data in your example:
pm.test('Check the response', () => {
_.each(pm.response.json().createdIncidents, (arrItem) => {
pm.expect(arrItem.incidentRef).to.equal("I0000000")
pm.expect(arrItem.personType).to.be.oneOf(['Patient','Staff','Visitor','Hazard'])
console.log(`Incident Ref: ${arrItem.incidentRef} is created for Person Type: ${arrItem.personType}`)
})
})
Related
I have a workflow action script that is supposed to search for a string in an email message body (the string being for the document number--this is stored in a field with the id 'custevent_case_creation') and return the transaction record id.
The script:
/**
*#NApiVersion 2.x
*#NScriptType WorkflowActionScript
* #param {Object} context
*/
define(["N/search", "N/record"], function (search, record) {
function onAction(context) {
var recordObj = context.newRecord;
var oc_number = recordObj.getValue({ fieldId: "custevent_case_creation" });
var s = search
.create({
type: "salesorder",
filters: [
search.createFilter({
name: "tranid",
operator: search.Operator.IS,
values: [oc_number],
}),
],
columns: ["internalid"],
})
.run()
.getRange({
start: 0,
end: 1,
});
log.debug("result set", s[0].id);
return s[0].id;
}
return {
onAction: onAction,
};
});
This works as expected when there is a valid document number used in the email message.
However, there are two scenarios where that won't be the case:
there is no document number referenced in the original email (and therefore, the field "custevent_case_creation" will be blank)
the document number referenced is incorrect and there is no transaction with that document number in the system
I am trying to add some form of error handling to deal with these two scenarios though I can't find anything that works. Where should the error handling be in this script?
Should it be an if/else statement?
So far I have tried:
adding if{s.length>0);
adding a condition in the workflow itself so that the custom action from the workflow action script doesn't occur if the field for custevent_case_creation is blank
-
The error message I am getting is:
org.mozilla.javascript.EcmaError: TypeError: Cannot read property "id" from undefined (/SuiteScripts/sdf_ignore/Workflow Action Lookup SO.js#41)
EDIT:
The working code
/**
*#NApiVersion 2.x
*#NScriptType WorkflowActionScript
* #param {Object} context
*/
define(["N/search", "N/record"], function (search, record) {
function onAction(context) {
try {
var recordObj = context.newRecord;
var oc_number = recordObj.getValue({
fieldId: "custevent_case_creation",
});
var s = search
.create({
type: "salesorder",
filters: [
search.createFilter({
name: "tranid",
operator: search.Operator.IS,
values: [oc_number],
}),
],
columns: ["internalid"],
})
.run()
.getRange({
start: 0,
end: 1,
});
log.debug("result set", s[0].id);
return s[0].id;
} catch (error) {
log.debug(
error.name,
"recordObjId: " +
recordObj.id +
", oc_number:" +
oc_number +
", message: " +
error.message
);
}
}
return {
onAction: onAction,
};
});
Try wrapping the contents of you onAction function with try/catch. More info on try/catch can be found here on W3Schools.
try {
//your working code for onAction function
var recordObj = context.newRecord;
var oc_number = recordObj.getValue({ fieldId: "custevent_case_creation" });
var s = search.create({
type: "salesorder",
filters: [
search.createFilter({
name: "tranid",
operator: search.Operator.IS,
values: [oc_number]
})
],
columns: ["internalid"]
})run().getRange({
start: 0,
end: 1,
});
log.debug("result set", s[0].id);
return s[0].id;
} catch(e){
log.debug(e.name,'recordObjId: '+ recordObj.id +', oc_number:'+ oc_number +', message: ' + e.message); //if e.name is empty try e.title
//you can add additional steps here if desired, i.e. send an email, display an alert, etc.
}
The First array returned when I console log person
The second array that returns when I console log person
I am trying to create a function that pulls the data from 2 tables in my SQL database. I am using async/await, which is still new to me. The issue is somewhere in the two array methods; for some reason they are returning data as undefined.
async function updateRole() {
console.log('hi');
//cycle through both arrays and create new arrays with same information using maps
//return object with employee and role info
const allEmployees = await db.promise().query(`SELECT * FROM employees`);
const allRoles = await db.promise().query(`SELECT * FROM roles`);
console.log(allEmployees);
const employeeChoices = allEmployees.map((person) => {
return {
name: `${person.first_name} ${person.last_name}`,
value: person.id
}
})
const roleChoices = allRoles.map((role) => {
return {
name: role.title,
value: role.id
}
})
const { employeeId, roleId } = await inquirer.prompt([
{
type: 'list',
name: 'employeeId',
message: 'Which employee would you like to update?',
choices: employeeChoices
},
{
type: 'list',
name: 'roleId',
message: 'What is their new role?',
choices: roleChoices
}])
await db.promise().query(`UPDATE employees SET role_id = ? WHERE id = ?`, [roleId, employeeId])
console.log('Successfully updated employee!');
askQuestions();
Update: I added screenshots fo the console log for person. role returns the same format, but obviously different data. I am unsure what the array of ColumnDefinition objects does, or why it's there.
I developed a SAPUI5 table on frontend having 4 columns, now I need to show the total sum of 1 column. If anyone knows the code related to this please help me
Controller code
onInit: function () {
var oTable = this.byId("producttable");
oTable.addStyleClass("myCustomTable");
//column list item creation
var oTemplate = new sap.m.ColumnListItem({
cells: [
new sap.m.Text({
text: "{Plant}"
}),
new sap.m.Text({
text: "{PlantDesc}"
}),
new sap.m.Text({
text: "{parts: [ {path: 'NetAmount'}, {path: 'currency'}],type: 'sap.ui.model.type.Currency',formatOptions: {showMeasure: false, maxFractionDigits: 0,roundingMode: 'away_from_zero'}}"
})
]
});
var sServiceUrl = "/sap/opu/odata/sap/ZSALES_PLANT001_SRV/";
//Adding service to the odata model
var oModel = new sap.ui.model.odata.ODataModel(sServiceUrl, false);
//Setting model to the table
oTable.setModel(oModel);
oTable.bindAggregation("items", {
path: "/ZSalesheaderSet",
template: oTemplate
});
I am getting the following errors in console
sap-ui-core.js:187 Assertion failed: could not find any translatable
text for key 'Total Sales-Yesterday' in bundle
'./i18n/i18n.properties' Failed to load resource: the server
responded with a status of 503 ()
getSum: function() {
var sum = 0, items = this.getView().byId("tableId").getItems();
for (var i = 0; i < items.length; i++) {
sum = sum + items[i].getBindingContext("urBoundModel").getObject().urColumn
}
return sum;
}
If you have bound the table to a Odata or JSON model. Just Iterate over your items and sum the bound property of the column.
I search hi and lo but could not find any decent reference how to get paid and outstanding amounts for the invoice in NetSuite using SuiteTalk API.
Documentation is non-existent and so are the samples so I'm poking in the dark here.
When invoice is retrieved using get method, I kind of expected these to be specified (fields amountPaid and amountRemaining) but they are not.
The next port of call, unfortunately, is to search for customer payments that have been applied to the target invoice. Search works but, to make the matter worse, each payment is returned without any apply details so extra call is required to get all apply details and figure out the total payment amount applied to the invoice.
Is that REALLY the only way to do it?!
(And I probably would have to consider deposits and deposit applications as they are separate record types. Sigh)
Any help is appreciated
George
UPDATE: Working code sample
long internalInvoiceId = 42;
TransactionSearchAdvanced tsa = new TransactionSearchAdvanced()
{
columns = new TransactionSearchRow()
{
basic = new TransactionSearchRowBasic()
{
total = new SearchColumnDoubleField[] { new SearchColumnDoubleField() },
amount = new SearchColumnDoubleField[] { new SearchColumnDoubleField() },
amountPaid = new SearchColumnDoubleField[] { new SearchColumnDoubleField() },
amountRemaining = new SearchColumnDoubleField[] { new SearchColumnDoubleField() }
}
},
criteria = new TransactionSearch()
{
basic = new TransactionSearchBasic()
{
mainLine = new SearchBooleanField()
{
searchValue = true,
searchValueSpecified = true
},
type = new SearchEnumMultiSelectField()
{
#operator = SearchEnumMultiSelectFieldOperator.anyOf,
operatorSpecified = true,
searchValue = new string[] { "_invoice" }
},
internalIdNumber = new SearchLongField()
{
#operator = SearchLongFieldOperator.equalTo,
operatorSpecified = true,
searchValue = internalInvoiceId,
searchValueSpecified = true
}
}
}
};
SearchResult sr = nss.search(tsa);
Do a transaction search.
Criteria:
Main Line: Yes
Type: Invoice
(Optional) Internal ID: "The internal id of your Invoice"
Result/Columns:
Amount Paid
Amount Remaining
Translate the above to SuiteTalk API (TransactionSearchAdvanced) and you should be able to get what you want.
Here's a function using the NetSuite ruby bindings that retrieves the amount remaining (due) on an invoice:
def amount_due_for_invoice(ns_invoice)
search = NetSuite::Records::Invoice.search(
criteria: {
basic: [
{
field: 'type',
operator: 'anyOf',
value: %w(_invoice)
},
{
field: 'mainLine',
value: true
},
{
field: 'internalIdNumber',
operator: 'equalTo',
value: ns_invoice.internal_id
}
]
},
columns: {
'tranSales:basic' => {
'platformCommon:internalId/' => {},
'platformCommon:amountRemaining' => {}
}
}
)
if search.results.size > 1
fail "invoice search on internalId should never return more than a single result"
end
search.results.first.attributes[:amount_remaining].to_f
end
An alternative solution here is to create a custom transaction body formula field which pulls the value of the invoice's amountremainingtotalbox field.
I am trying to display console.log(r.get('info')) but, i am getting the output as (an empty string). What might have caused this error ?
var myst = Ext.getStore('MyStore');
var r = myst.getAt(0);
myst.on('load', function() {
r = myst.getAt(0);
console.log(r);
console.log(r.get('info'));
});
UPDATE 1
MODEL
Ext.define('MyApp.model.MyModel', {
extend: 'Ext.data.Model',
fields: [
{
name: 'info'
}
]
});
UPDATE 2
I actually get Object { phantom=true, internalId="ext-record-18", raw={...}, more...} when i print console.log(r)'and inside raw, i see info:"myname".
To display array or objects try console.dir(object).