using promises with getCollection - rally

I'm trying to figure out how to apply the promises infrastructure in the case where I'm looping through a list of portfolio items to extract data for highcharts use and need to retrieve data from the related user stories. The goal is to create a way to not attempt to instantiate the chart object until all async callbacks are completed. Here's a code snippet illustrating what I'm trying to do - in this example, the getCollection() method's callback function is not being executed until all of the outer loop features have been retrieved.
_.each(records, function(feature) {
var rname = (feature.get('Release')) ? feature.get('Release')._refObjectName: "None";
//various other feature record extraction steps
feature.getCollection('UserStories').load({
fetch: ['FormattedID', 'Name', 'InProgressDate','AcceptedDate'],
callback: function(stories, operation, success){
Ext.Array.each(stories, function(story) {
var storyname = story.get('FormattedID') + ': ' + story.get('Name');
// other chart data extraction steps
}
});
}
});
});

I'd check out the guide in the docs on working with promises, especially the section on retrieving hierarchical data:
https://help.rallydev.com/apps/2.0/doc/#!/guide/promises-section-retrieving-hierarchical-data
The basic idea is to keep an array of all the promises representing the child collection store loads and then to use a Deft.Promise.all to wait for them all to finish before continuing.
So something like this, based on your code above:
var childStoryPromises = [];
_.each(records, function(feature) {
var rname = (feature.get('Release')) ? feature.get('Release')._refObjectName: "None";
// various other feature record extraction steps
var userStoriesStore = feature.getCollection('UserStories');
var promise = userStoriesStore.load({
fetch: ['FormattedID', 'Name', 'InProgressDate','AcceptedDate']
});
childStoryPromises.push(promise);
feature.userStoriesStore = userStoriesStore; //save reference for later
});
//wait for all stores to load
Deft.Promise.all(childStoryPromises).then({
success: function() {
_.each(records, function(feature) {
var userStories = feature.userStoriesStore.getRange();
//extract user story data here
});
},
scope: this
});

Related

Odoo UI widget - how to get settings from database?

I'm writing an Odoo v9 widget, which renders a URL, based on concatenation of a setting in the database, and the actual form fields.
The setting in the database I figure should live in ir_config_parameter. I'm inserting a default value with my module.
What's the best way to get this value when rendering the widget? Doing an async ajax call using
new Model("ir.config_parameter")
seems a little heavy handed. Is there a better way to be doing this?
Thanks.
Widget code:
var UrlWidget2 = form_common.FormWidget.extend({
start: function() {
this._super();
this.field_manager.on("field_changed:ref", this, this.display_result);
this.display_result();
},
display_result: function() {
var ref = this.field_manager.get_field_value("ref");
if (!ref) return;
var baseUrl = 'https://example.com'; //this is the value I want to get from the setting in the database.
var url = baseUrl + '/foo/' + ref;
this.$el.html('View Externally<br /><br/>');
}
});
You can use RPC for this. This is example which work for me:
var Model = require('web.DataModel');
var UrlWidget2 = form_common.FormWidget.extend({
// just example how to get parameter from backend
display_result: function() {
var parameter = new Model('ir.config_parameter');
// get fields value, key
parameter.query(['value', 'key'])
// criteria of search - record with id = 1
.filter([['id', '=', 1]])
// only one record
.limit(1)
.all()
.then(function (parameter) {
// here data from server
console.log(parameter);
});
// ...
}
});
Hope this helps you.

find subdocument without start from parent

Pretty new to mongoose. Can I findOne off of a subdocument model?
I have a subdoc called deliverables which is a child of projects
What I'd like to do is FIND on my deliverables model so I don't have to find on the project as
{project.child.child.child.deliverables._id: req.id}
Is that possible or do I have to start from the project model each time? Below is a sample setup I'm using along with my example findOne.
'use strict';
//////////////model/////////////////
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var deliverablesSchema = new Schema({
title:{
type:String,
}
})
var ProjectSchema = new Schema({
name: {
type: String,
},
deliverables: [deliverablesSchema],
});
mongoose.model('Deliverable', deliverablesSchema);
mongoose.model('Project', ProjectSchema);
//////////////controller/////////////////
var mongoose = require('mongoose'),
Project = mongoose.model('Project'),
Deliverable = mongoose.model('Deliverable'),
_ = require('lodash');
exports.findDeliverable = function(req, res) {
Deliverable.findOne({'_id': req.params.deliverableId}).exec(function(err, deliverable) {
if(deliverable){
//return
}
});
};
You can find subdocuments within a document only if you have declared their schema http://mongoosejs.com/docs/subdocs.html
Here is an example taken from here:
Project.findOne({
'_id': myid
}).exec(function (err, p) {
if (p) {
//return
var deriv = p.deliverables.filter(function (oneP) {
return oneP._id === 'myderivableid';
}).pop();
}
});
If your subdocuments are just nested objects in an array you may use Lodash to retrieve that data using _ .where or _.find
Kept digging and found this:
https://stackoverflow.com/a/28952991/2453687
You still have to pull the master document first but it's easy to drill down to the particular object you're looking for and make a quick update, then just update the whole master document in one shot.
Dead simple. Works like a charm.

TestCases collections is not retrieved correctly through SDK but only with Web Service api

SDK retrieval of TestCases collection from the TestSet object is not working correctly IMO as TestCase collection is not a full array of objects and TestCases collection has very scarce information.
Web service API returns them correctly and so far only 2.0p5 returns them correctly and neither of 2.0rc rc2 and rc3 returns them as expected
Am I doing something wrong?
I just need to get TestCases collection with all fully qualified objects for each test case when I retrieve a TestSet object.
AppSDK rc2 works with v2.0 of WS API. v2.0 removed the ability to return child collections in the same response for performance reasons. Per WS API documentation fetching a collection will return an object with the count and the url from which to get the collection data. To get full objects a separate request is needed. In app example in this github repo when a testset is selected from a combobox, and testset loaded, TestCases collection is hydreated:
_onDataLoaded: function(store, records){
if ((records.length === 0) && (this._grid)) {
this._grid.destroy();
}
var that = this;
var promises = [];
_.each(records, function(tcr) {
promises.push(that._getTestCase(tcr, that));
});
Deft.Promise.all(promises).then({
success: function(results) {
that._testcaseresults = results;
that._createGrid(records);
}
});
},
_getTestCase: function(tcr, scope) {
var deferred = Ext.create('Deft.Deferred');
var that = scope;
var testcaseOid = tcr.get('TestCase').ObjectID;
Rally.data.ModelFactory.getModel({
type: 'Test Case',
scope: this,
success: function(model, operation) {
fetch: ['FormattedID','Name','Method'],
model.load(testcaseOid, {
scope: this,
success: function(record, operation) {
var testName = record.get('Name');
var testFid = record.get('FormattedID');
var testMethod = record.get('Method');
var tcrRef = tcr.get('_ref');
var tcrOid = tcr.get('ObjectID');
var tcrVerdict = tcr.get('Verdict');
var tcrBuild = tcr.get('Build');
result = {
"_ref" : tcrRef,
"ObjectID" : tcrOid,
"Verdict" : tcrVerdict,
"Build" : tcrBuild,
"TestCaseName" : testName,
"TestCase" : testFid,
"Method" : testMethod
};
deferred.resolve(result);
}
});
}
});
return deferred;
}

Filtering epics from Kanban board

I would like to start by saying I have read Rally Kanban - hiding Epic Stories but I'm still having trouble on implementing my filter based on the filter process from the Estimation Board app. Currently I'm trying to add an items filter to my query object for my cardboard. The query object calls this._getItems to return an array of items to filter from. As far as I can tell the query calls the function, loads for a second or two, and then displays no results. Any input, suggestions, or alternative solutions are welcomed.
Here's my code
$that._redisplayBoard = function() {
that._getAndStorePrefData(displayBoard);
this._getItems = function(callback) {
//Build types based on checkbox selections
var queries = [];
queries.push({key:"HierarchicalRequirement",
type: "HierarchicalRequirement",
fetch: "Name,FormattedID,Owner,ObjectID,Rank,PlanEstimate,Children,Ready,Blocked",
order: "Rank"
});
function bucketItems(results) {
var items = [];
rally.forEach(queries, function(query) {
if (results[query.key]) {
rally.forEach(results[query.key], function(item) {
//exclude epic stories since estimates cannot be altered
if ((item._type !== 'HierarchicalRequirement') ||
(item._type === 'HierarchicalRequirement' && item.Children.length === 0)) {
items = items.concat(item);
}
});
}
});
callback(items);
}
rallyDataSource.findAll(queries, bucketItems);
};
function displayBoard() {
artifactTypes = [];
var cardboardConfig = {
types: [],
items: that._getItems,
attribute: kanbanField,
sortAscending: true,
maxCardsPerColumn: 200,
order: "Rank",
cardRenderer: KanbanCardRenderer,
cardOptions: {
showTaskCompletion: showTaskCompletion,
showAgeAfter: showAgeAfter
},
columnRenderer: KanbanColumnRenderer,
columns: columns,
fetch: "Name,FormattedID,Owner,ObjectID,Rank,Ready,Blocked,LastUpdateDate,Tags,State,Priority,StoryType,Children"
};
if (showTaskCompletion) {
cardboardConfig.fetch += ",Tasks";
}
if (hideLastColumnIfReleased) {
cardboardConfig.query = new rally.sdk.util.Query("Release = null").or(kanbanField + " != " + '"' + lastState + '"');
}
if (filterByTagsDropdown && filterByTagsDropdown.getDisplayedValue()) {
cardboardConfig.cardOptions.filterBy = { field: FILTER_FIELD, value: filterByTagsDropdown.getDisplayedValue() };
}
cardboardConfig.types.push("HierarchicalRequirement");
if (cardboard) {
cardboard.destroy();
}
artifactTypes = cardboardConfig.types;
cardboard = new rally.sdk.ui.CardBoard(cardboardConfig, rallyDataSource);
cardboard.addEventListener("preUpdate", that._onBeforeItemUpdated);
cardboard.addEventListener("onDataRetrieved", function(cardboard,args){ console.log(args.items); });
cardboard.display("kanbanBoard");
}
};
that.display = function(element) {
//Build app layout
this._createLayout(element);
//Redisplay the board
this._redisplayBoard();
};
};
Per Charles' hint in Rally Kanban - hiding Epic Stories
Here's how I approached this following Charles' hint for the Rally Catalog Kanban. First, modify the fetch statement inside the cardboardConfig so that it includes the Children collection, thusly:
fetch: "Name,FormattedID,Children,Owner,ObjectID,Rank,Ready,Blocked,LastUpdateDate,Tags,State"
Next, in between this statement:
cardboard.addEventListener("preUpdate", that._onBeforeItemUpdated);
And this statement:
cardboard.display("kanbanBoard");
Add the following event listener and callback:
cardboard.addEventListener("onDataRetrieved",
function(cardboard, args){
// Grab items hash
filteredItems = args.items;
// loop through hash keys (states)
for (var key in filteredItems) {
// Grab the workproducts objects (Stories, defects)
workproducts = filteredItems[key];
// Array to hold filtered results, childless work products
childlessWorkProducts = new Array();
// loop through 'em and filter for the childless
for (i=0;i<workproducts.length;i++) {
thisWorkProduct = workproducts[i];
// Check first if it's a User Story, since Defects don't have children
if (thisWorkProduct._type == "HierarchicalRequirement") {
if (thisWorkProduct.Children.length === 0 ) {
childlessWorkProducts.push(thisWorkProduct);
}
} else {
// If it's a Defect, it has no children so push it
childlessWorkProducts.push(thisWorkProduct);
}
}
filteredItems[key] = childlessWorkProducts;
}
// un-necessary call to cardboard.setItems() was here - removed
}
);
This callback should filter for only leaf-node items.
Mark's answer caused an obscure crash when cardboard.setItems(filteredItems) was called. However, since the filtering code is actually manipulating the actual references, it turns out that setItems() method is actually not needed. I pulled it out, and it now filters properly.
Not sure this is your problem but your cardboard config does not set the 'query' field. The fetch is the type of all data to retrieve if you want to filter it you add a "query:" value to the config object.
Something like :
var cardboardConfig = {
types: ["PortfolioItem", "HierarchicalRequirement", "Feature"],
attribute: dropdownAttribute,
fetch:"Name,FormattedID,Owner,ObjectID,ClassofService",
query : fullQuery,
cardRenderer: PriorityCardRenderer
};
Where fullQuery can be constructed using the the Rally query object. You find it by searching in the SDK. Hope that maybe helps.

looping through DOM / mootools sortables

I can't seem to get a handle on my list of sortables. They are a list of list elements, each with a
form inside, which I need to get the values from.
Sortables.implement({
serialize: function(){
var serial = [];
this.list.getChildren().each(function(el, i){
serial[i] = el.getProperty('id');
}, this);
return serial;
}
});
var sort = new Sortables('.teams', {
handle: '.drag-handle',
clone: true,
onStart: function(el) {
el.fade('hide');
},
onComplete: function(el) {
//go go gadget go
order = this.serialize();
alert(order);
for(var i=0; i<order.length;i++) {
if (order[i]) {
//alert(order[i].substr(5, order[i].length));
}
}
}
});
the sortables list is then added to a list in a loop with sort.addItems(li); . But when I try to get the sortables outside of the sortables onComplete declaration, js says this.list is undefined.
Approaching the problem from another angle:
Trying to loop through the DOM gives me equally bizarre results. Here are the firebug console results for some code:
var a = document.getElementById('teams').childNodes;
var b = document.getElementById('teams').childNodes.length;
try {
console.log('myVar: ', a);
console.log('myVar.length: ', b);
} catch(e) {
alert("error logging");
}
Hardcoding one li element into the HTML (rather than being injected via JS) changes length == 1, and allows me to access that single element, leading me to believe that accessing injected elements via the DOM is the problem (for this method)
Trying to get the objects with document.getElementById('teams').childNodes[i] returns undefined.
thank you for any help!
not sure why this would fail, i tried it in several ways and it all works
http://www.jsfiddle.net/M7zLG/ test case along with html markup
here is the source that works for local refernece, using the native built-in .serialize method as well as a custom one that walks the dom and gets a custom attribute rel, which can be your DB IDs in their new order (I tend to do that)
var order = []; // global
var sort = new Sortables('.teams', {
handle: '.drag-handle',
clone: true,
onStart: function(el) {
el.fade('hide');
},
onComplete: function(el) {
//go go gadget go
order = this.serialize();
}
});
var mySerialize = function(parentEl) {
var myIds = [];
parentEl.getElements("li").each(function(el) {
myIds.push(el.get("rel"));
});
return myIds;
};
$("saveorder").addEvents({
click: function() {
console.log(sort.serialize());
console.log(order);
console.log(mySerialize($("teams")));
}
});