how can i set ID of qty in nativescript - vue.js

I have button + - and i want to save the result of that butotn + -. But i have no idea id of the button/qty. First, variable in run debug android is empty. And when i insert qty:1, the result is "variables: {qty_used: 1}". Here is the code
data() {
return {
pageData: this.tempData,
list: {},
is_checked_all: false,
is_saving: false,
is_completed: false,
qty: 1
}
},
and here is the method
methods: {
toggleSelectAll() {
if (this.is_completed) return
this.is_checked_all = true
},
save(qty) {
if (this.is_saving) return
this.is_saving = true
var vm = this
this.$apollo.query({
query: gqlUseVoucher,
variables: {
id: this.pageData.id,
qty_used: qty
},
fetchPolicy: 'no-cache'
}).then((resp) => {
if (resp.room.AuthorizeVoucherUsingID) {
vm.is_saving = false
vm.$modal.close()
vm.$store.commit('setSuccess', 'Voucher breakfast berhasil divalidasi')
} else {
vm.is_saving = false
errorHandler(vm, null, 'Voucher breakfast tidak dapat digunakan')
}
}).catch((error) => {
vm.is_saving = false
console.log(error)
errorHandler(vm, error)
})
},
now, what should i do to get the ID of that button/qty. Am new in nativescript xoxo. thank you

Related

how can get values from va-select when user choose the data?

how can get values from va-select when user choose the data?
I use this method to show my data in va-select
<va-select
:label="$t('Unit Code')"
v-model="aircraftData.afta_ProcUnit1"
textBy="name"
searchable
:options="optionsProcUnit1"
:addBtn="true"
placeholder=""
:error="!!afta_ProcUnit1Errors.length"
:error-messages="afta_ProcUnit1Errors"
/>
apiRelatedUnit(postData) {
let self = this;
this.isLoading = true;
SmsApis.relatedUnit.post
.GetRelatedUnit(postData)
.then((xhr) => {
self.isLoading = false;
if (xhr.data.result[0].smsB_RelatedUnit) {
xhr.data.result[0].smsB_RelatedUnit.forEach(function (g, i) {
if (g.runt_Category === "0") {
self.optionsProcUnit2.push({
id: g.runt_unitID,
name: g.runt_unitID + " / " + g.runt_UnitTitle,
tel: g.runt_UnitTel,
});
}
if (g.runt_Category === "2") {
self.optionsProcUnit1.push({
id: g.runt_unitID,
name: g.runt_unitID + " / " + g.runt_UnitTitle,
tel: g.runt_UnitTel,
});
}
});
} else {
self.$swal.fire("Error", xhr.data.result[0].Error, "error");
}
})
.catch(function (error) {
self.isLoading = false;
if (error.message === "Cannot read property 'status' of undefined")
self.$swal.fire("Connect Error", "", "warning");
});
},
And the va-select will show like this one
Test / Sales
Test2 / Dev
Test3 / Bus
and when user click submit, it's will send date and writing in database
pdbt = {
tableA: [
{
afta_ProcUnit1: xxx, //how can get unit code in here???
afta_ProcUnit2: ProcUnit2,
}
]
}
Apis.AircraftAnomaly.post
.EditAircraftAnomaly(pdbt )
.then(function (xhr) {
self.isLoading = false;
if (xhr.data.result[0].Result === "OK") {
self.onEditAnomalyCL();
self.isLoading = true;
}
})
}
how can get value when user choose the options in va-select?

How merge mutil object in array with lodash?

I have a bit of problems with my code :
[
{
"key": 0,
"server": 0
},
{
"key": 0,
"server": 1
},
{
"key": 1,
"server": 0
}
]
how i can result to :
[
{ key: 0 , server:[0,1] },
{ key: 1 , server:[0] }
]
I'm using _.groupBy but it does not return results as expected.
How merge mutil object in array with lodash?
One solution would be to use a combination of groupBy, map, and mergeWith.
So first, you group the items by key, so in this example it will return an object with 0 and 1 as the keys which will contain the grouped items.
Then you use .map to iterate through the returned object and get the grouped values.
Finally, you use .mergeWith with a customizer function which you can use to customize the how the values of the server key is merged.
const servers = [{
"key": 0,
"server": 0
},
{
"key": 0,
"server": 1
},
{
"key": 1,
"server": 0
}
];
function customizer(objValue, srcValue, key, fourth) {
if (key === 'server') {
if (!_.isArray(objValue)) objValue = [objValue];
return objValue.concat(srcValue);
}
}
let test = _(servers)
.groupBy('key')
.map((values, key) => {
if (values.length === 1) {
values[0].server = [values[0].server];
return values[0];
}
return _.mergeWith(...values, customizer);
})
.value();
console.log(test);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
new Vue({
el: "#app",
data: {
needMergedArray: [
{
key: 0,
server: 0
},
{
key: 0,
server: 1
},
{
key: 1,
server: 0
}
],
},
methods: {
mergeObject() {
let merged = [];
this.needMergedArray.map(item => {
let found = false;
merged.map(element => {
if(item.key === element.key) {
found = true;
if(!element.server) {
//const myserver = [item.server];
element.server =[item.server];
} else {
element.server.push(item.server);
}
}
});
if(!found) {
const myserver = [item.server];
merged.push({key: item.key, server: myserver});
}
found = false;
});
return merged;
}
}
})
// one loop solution: https://jsfiddle.net/haianhnc/2mhsquad/78
mergeObject() {
let merged = {};
this.needMergedArray.map(item => {
merged = {...merged, [item.key]: {key: [item.key], server: (merged[item.key] && merged[item.key].server || []).concat(item.server)}};
});
return Object.values(merged);
}
}
Haven't tested yet
arr.reduce(function(acc,value){
const isExists = acc.findIndex(({key})=>key===value.key)
if(!isExists){
acc.push(value)
} else {
let servers = acc[isExists].server
if(!Array.isArray(servers))
servers = [servers]
servers.push(value.server)
servers = _.uniq(servers)
acc[isExists].server = servers
}
return acc
},[])

How to unit test API calls with axios() in react-native with Jest

I am developing Sample Application in React-native . I used Jest to use unit testing, i don't have an idea about Jest Api call
I want to need without using Promises:
Here this is my Code:
this is My Function Code:
/**
* #description Action to call nilpick service ,on success increment route as well as mark the location as fulfilled
*/
function nilPick() {
return async (dispatch, getState) => {
const currentState = getState();
const { user, picking } = currentState;
const { currentRouteIndex, pickRoute } = getState().picking.pickRouteInfo;
const { workId } = picking.pickWorkInfo;
const nilPickItem = pickRoute[currentRouteIndex];
const currentItem = getCurrentItem(currentState);
const currentTime = dateFunctions.getCurrentUTC();
const nilpickedItem = [
{
orderId: nilPickItem.fulfillOrdNbr,
lineNbr: nilPickItem.ordLine,
pickUpcNbr: nilPickItem.upc,
pickDisplayTs: currentTime,
pickUom: currentItem.workDetail.uom,
pickedLoc: nilPickItem.location,
locationType: nilPickItem.locType,
locId: nilPickItem.locId,
pickByType: currentItem.workDetail.pickByType,
exceptionPick: false,
gtinPrefRankNbr: 0,
pickUpcTypeCd: 5100
}
];
const { status, statusText } = await pickingService.nilPick(nilpickedItem, user, workId);
if (status === 200 || statusText === 'Created') {
console.info('Item nilpicked');
if (currentRouteIndex < pickRoute.length) {
dispatch(incrementRoute());
} else {
Alert.alert(
'Nilpick Complete',
[
{
text: 'OK',
onPress: () => {
dispatch(endPicking());
}
}
],
{ cancelable: false }
);
console.log('End of pickwalk');
return;
}
} else {
console.info('error in nilpicking item ');
}
};
}
This is my code above method to Converting Like this below sample test Case:
This is sample Test i want to call Api How to implement in Jest
it('Test For nillPic', () => {
const initialState = {
picking: {
pickRouteInfo: {
"fulfillOrdNbr": pickRouteInfo.fulfillOrdNbr,
"orderLine": '1',
"upc": '4155405089',
"location": 'A-1-1',
"availableLocsToPick": '2',
'suggSubPendingPicks?': 'N',
'manualSubPendingPicks?': 'N',
"lineFullfilled": 'false',
"currentRouteIndex": 1,
"pickRoute": ['r1', 'r2', 'r3']
}
}
};
// console.log("state data...", initialState);
const store = mockStore(initialState);
store.dispatch(actions.pickRouteActions.nilPickSuccess());
const expectedAction = [{ type: 'INCREMENT_ROUTE' }];
const localActions = store.getActions();
expect(localActions).toEqual(expectedAction);
});
Finally This is my code Please . Thanks in Advance

On my cardboard app trying to show total of all features actual points for each column(Release) on the header, but that is not getting displayed

On my cardboard app trying to show total of all features actual points for each column(Release) on the header, but that is not getting displayed.
See the image below the cards are my portfolioitem/feature, in particular release.
On each header with release information, below progress-bar I want to show total of all features actual points in that release.
Below is the code for that, I am not getting why actual_points are not getting displayed. I am doing something wrong, but I don't know where exactly it is
Ext.override(Rally.ui.cardboard.CardBoard,{
_buildColumnsFromModel: function() {
var me = this;
var model = this.models[0];
if (model) {
if ( this.attribute === "Release" ) {
var retrievedColumns = [];
retrievedColumns.push({
value: null,
columnHeaderConfig: {
headerTpl: "{name}",
headerData: {
name: "Backlog"
}
}
});
this._getLocalReleases(retrievedColumns, this.globalVar);
}
}
},
_getLocalReleases: function(retrievedColumns, today_iso) {
var me = this;
if (today_iso == undefined) {
today_iso = Rally.util.DateTime.toIsoString(new Date(),false);
}
var filters = [{property:'ReleaseDate',operator:'>',value:today_iso}];
var iteration_names = [];
Ext.create('Rally.data.WsapiDataStore',{
model:me.attribute,
autoLoad: true,
filters: filters,
context: { projectScopeUp: false, projectScopeDown: false },
sorters: [
{
property: 'ReleaseDate',
direction: 'ASC'
}
],
//limit: Infinity,
pageSize: 4,
//buffered: true,
//purgePageCount: 4,
fetch: ['Name','ReleaseStartDate','ReleaseDate','PlannedVelocity'],
listeners: {
load: function(store,records) {
Ext.Array.each(records, function(record){
console.log("records values", records);
var start_date = Rally.util.DateTime.formatWithNoYearWithDefault(record.get('ReleaseStartDate'));
var end_date = Rally.util.DateTime.formatWithNoYearWithDefault(record.get('ReleaseDate'));
//this._getMileStones(record.get('ReleaseStartDate'), record.get('ReleaseDate'), this.project);
iteration_names.push(record.get('Name'));
//iteration_names.push(record.get('ReleaseDate'));
retrievedColumns.push({
value: record,
_planned_velocity: 0,
_actual_points: 0,
_missing_estimate: false,
columnHeaderConfig: {
headerTpl: "{name}<br/>{start_date} - {end_date}",
headerData: {
name: record.get('Name'),
start_date: start_date,
end_date: end_date,
planned_velocity: 0,
actual_points: 0,
missing_estimate: false
}
}
});
});
this._getAllReleases(retrievedColumns,iteration_names);
},
scope: this
}
});
},
_getAllReleases: function(retrievedColumns,iteration_names, today_iso) {
var me = this;
if (today_iso == undefined) {
today_iso = Rally.util.DateTime.toIsoString(new Date(),false);
}
var filters = [{property:'ReleaseDate',operator:'>',value:today_iso}];
Ext.create('Rally.data.WsapiDataStore',{
model:me.attribute,
autoLoad: true,
filters: filters,
sorters: [
{
property: 'ReleaseDate',
direction: 'ASC'
}
],
fetch: ['Name','Project','PlannedVelocity'],
listeners: {
load: function(store,records) {
Ext.Array.each(records, function(record){
var planned_velocity = record.get('PlannedVelocity') || 0;
var actual_points = record.get('LeafStoryPlanEstimateTotal') || 0;
var index = Ext.Array.indexOf(iteration_names[0],record.get('Name'));
if (planned_velocity == 0 ) {
retrievedColumns[index+1]._missing_estimate = true;
}
retrievedColumns[index+1]._actual_points += actual_points;
retrievedColumns[index+1]._planned_velocity += planned_velocity;
});
this.fireEvent('columnsretrieved',this,retrievedColumns);
this.columnDefinitions = [];
_.map(retrievedColumns,this.addColumn,this);
this._renderColumns();
},
scope: this
}
});
}
});
Ext.define('Rally.technicalservices.plugin.ColumnHeaderUpdater', {
alias: 'plugin.tscolumnheaderupdater',
extend: 'Ext.AbstractPlugin',
config: {
/**
*
* #type {String} The name of the field holding the card's estimate
*
* Defaults to c_FeatureEstimate (try LeafStoryPlanEstimateTotal)
*/
field_to_aggregate: "planned_velocity",
/**
* #property {Number} The current count of feature estimates
*/
total_feature_estimate: 0,
fieldToDisplay: "actual_points",
/**
* #property {String|Ext.XTemplate} the header template to use
*/
headerTpl: new Rally.technicalservices.template.LabeledProgressBarTemplate({
fieldLabel: 'Features Planned vs Planned Velocity: ',
calculateColorFn: function(data) {
if ( data.percentDone > 0.9 ) {
return '#EDB5B1';
}
return '#99CCFF';
},
showDangerNotificationFn: function(data) {
return data.missing_estimate;
},
generateLabelTextFn: function(data) {
if ( data.percentDone === -1 ) {
return "No Planned Velocity";
} else {
var text_string = "";
if ( data.field_to_aggregate === "planned_velocity" ) {
text_string = this.calculatePercent(data) + '%';
} else {
text_string = 'By Story: ' + this.calculatePercent(data) + '%';
}
return text_string;
}
}
})
//headerTpl: '<div class="wipLimit">({total_feature_estimate} of {planned_velocity})</div>'
},
constructor: function(config) {
this.callParent(arguments);
if(Ext.isString(this.headerTpl)) {
this.headerTpl = Ext.create('Ext.XTemplate', this.headerTpl);
}
},
init: function(column) {
this.column = column;
if ( column.value === null ) {
this.headerTpl = new Ext.XTemplate('');
}
this.planned_velocity = this.column._planned_velocity;
this.missing_estimate = this.column._missing_estimate;
this.actual_points = this.column._actual_points;
this.column.on('addcard', this.recalculate, this);
this.column.on('removecard', this.recalculate, this);
this.column.on('storeload', this.recalculate, this);
this.column.on('afterrender', this._afterRender, this);
this.column.on('ready', this.recalculate, this);
this.column.on('datachanged', this.recalculate, this);
},
destroy: function() {
if(this.column) {
delete this.column;
}
},
_afterRender: function() {
if ( this.feature_estimate_container ) {
this.feature_estimate_container.getEl().on('click', this._showPopover, this);
}
},
recalculate: function() {
this.total_feature_estimate = this.getTotalFeatureEstimate();
this.refresh();
},
refresh: function() {
var me = this;
if (this.feature_estimate_container) {
this.feature_estimate_container.update(this.headerTpl.apply(this.getHeaderData()));
} else {
this.feature_estimate_container = Ext.widget({
xtype: 'container',
html: this.headerTpl.apply(this.getHeaderData())
});
this.column.getColumnHeader().getHeaderTitle().add(this.feature_estimate_container);
}
if ( this.feature_estimate_container && this.feature_estimate_container.getEl()) {
this.feature_estimate_container.getEl().on('click', this._showPopover, this);
}
},
_showPopover: function() {
var me = this;
if ( me.planned_velocity > 0 ) {
if ( this.popover ) { this.popover.destroy(); }
this.popover = Ext.create('Rally.ui.popover.Popover',{
target: me.column.getColumnHeader().getHeaderTitle().getEl(),
items: [ me.getSummaryGrid() ]
});
this.popover.show();
}
},
getSummaryGrid: function() {
var me = this;
var estimate_title = "Feature Estimates";
if ( this.field_to_aggregate !== "c_FeatureEstimate") {
estimate_title = "Story Estimates";
}
var store = Ext.create('Rally.data.custom.Store',{
data: [
{
'PlannedVelocity': me.planned_velocity,
'ActualPoints': me.actual_points,
'TotalEstimate': me.getTotalFeatureEstimate(),
'Remaining': me.getCapacity(),
'MissingEstimate': me.missing_estimate
}
]
});
var grid = Ext.create('Rally.ui.grid.Grid',{
store: store,
columnCfgs: [
{ text: 'Plan', dataIndex:'PlannedVelocity' },
{ text: estimate_title, dataIndex: 'TotalEstimate' },
{ text: 'Remaining', dataIndex: 'Remaining' },
{ text: 'Team Missing Plan?', dataIndex: 'MissingEstimate' }
],
showPagingToolbar: false
});
return grid;
},
getHeaderData: function() {
var total_feature_estimate = this.getTotalFeatureEstimate();
actual_points = 0;
var percent_done = -1;
planned_velocity = 20;
if ( planned_velocity > 0 ) {
percent_done = total_feature_estimate / 4;
}
return {
actual_points: actual_points,
total_feature_estimate: total_feature_estimate,
planned_velocity: planned_velocity,
percentDone: percent_done,
field_to_aggregate: this.field_to_aggregate,
missing_estimate: this.missing_estimate
};
},
getCapacity: function() {
return this.planned_velocity - this.getTotalFeatureEstimate();
},
getTotalFeatureEstimate: function() {
var me = this;
var total = 0;
var total_unaligned = 0;
var records = this.column.getRecords();
Ext.Array.each(records, function(record){
var total_points = record.get('AcceptedLeafStoryPlanEstimateTotal');
var feature_estimate = record.get(me.field_to_aggregate) || 0;
var unaligned_estimate = record.get('UnalignedStoriesPlanEstimateTotal') || 0;
total += parseFloat(total_points,10);
});
if ( me.field_to_aggregate !== "planned_velocity" ) {
total = total
}
return total;
}
});

Change Value of a dojo tree node

I'm trying to change the value of a dojo tree to display the correct icon. I was hopping that I could get the object with fetchItemByIdentity() and change the value there but the item is null
_target: null,
_treeModel: null,
constructor: function(target, uuid) {
this._target = target;
this._uuid = uuid;
// from somewhere else the value get's changed
topic.subscribe("questionChanged", lang.hitch(this, function(object, id) {
var item = this._treeModel.fetchItemByIdentity({
identifier: id,
onItem: function(item, request) { alert("item " + item); }
});
}));
},
buildTree: function() {
xhr.get({
// The URL to request
url: er.getAbsoluteUrl("/secure/staticquestion/tree?uuid=" + this._uuid),
handleAs: "json",
headers: {
"Content-Type": "application/json; charset=utf-8"
},
preventCache: 'true',
// The method that handles the request's successful result
load: lang.hitch(this, function(response) {
var rawdata = new Array();
rawdata.push(response);
var store = new ItemFileReadStore({
data: {
identifier: "uuid",
label: "name",
items: rawdata
}
});
this._loadtree(store);
}),
error: function(err, ioArgs) {
errorDialog.show(err.message);
}
});
},
_loadtree: function(store) {
this._treeModel = new TreeStoreModel({
store: store,
query: {
name: 'root'
},
childrenAttrs: [ "children" ],
mayHaveChildren: function(object) {
return object.children.length > 0;
}
});
var tree = new Tree({ // create a tree
model: this._treeModel, // give it the model
showRoot: false,
getIconClass: function(/* dojo.data.Item */item, /* Boolean */opened) {
if (!item || this.model.mayHaveChildren(item)) {
return opened ? "dijitFolderOpened" : "dijitFolderClosed";
} else if (item.comment == 'false') {
return (item.answer == 'YES') ? "dijitLeafNoCommentYes"
: ((item.answer == 'NO') ? "dijitLeafNoCommentNo" : "dijitLeafNoComment");
} else if (item.comment == 'true') {
return (item.answer == 'YES') ? "dijitLeafYes" : ((item.answer == 'NO') ? "dijitLeafNo"
: "dijitLeaf");
}
return "dijitLeaf";
},
}, this._target); // target HTML element's id
tree.on("click", function(object) {
topic.publish("staticQuestionSelected", object);
}, true);
tree.startup();
}
I'm glad for help, thanks!
Ok, I found my issue: I need to use a ItemFileWriteStore and there I can change values with store.setValue(item, attribute, value). The tree updates itself afterwards.