generic applyConstraints, before abandoning
[plstackapi.git] / planetstack / core / xoslib / static / js / xoslib / xosHelper.js
index 46bc522..1141dcb 100644 (file)
@@ -39,6 +39,13 @@ XOSRouter = Marionette.AppRouter.extend({
                 this.navigate("#"+prevPage, {trigger: false, replace: true} );
             }
         },
+
+        navigate: function(href, options) {
+            if (options.force) {
+                Marionette.AppRouter.prototype.navigate.call(this, "nowhere", {trigger: false, replace: true});
+            }
+            Marionette.AppRouter.prototype.navigate.call(this, href, options);
+        },
     });\r
 
 
@@ -107,28 +114,39 @@ XOSApplication = Marionette.Application.extend({
         }
     },
 
+    hideTabs: function() { $("#tabs").hide(); },
+    showTabs: function() { $("#tabs").show(); },
+
     createListHandler: function(listViewName, collection_name, regionName, title) {
         var app=this;
         return function() {
-            app[regionName].show(new app[listViewName]);
+            listView = new app[listViewName];
+            app[regionName].show(listView);
             app.hideLinkedItems();
             $("#contentTitle").html(templateFromId("#xos-title-list")({"title": title}));
             $("#detail").show();
-            $("#xos-listview-button-box").show();
-            $("#tabs").hide();
-            $("#xos-detail-button-box").hide();
+            app.hideTabs();
+
+            listButtons = new XOSListButtonView({linkedView: listView});
+            app["rightButtonPanel"].show(listButtons);
         }
     },
 
     createAddHandler: function(detailName, collection_name, regionName, title) {
         var app=this;
         return function() {
+            console.log("addHandler");
+
+            app.hideLinkedItems();
+            app.hideTabs();
+
             model = new xos[collection_name].model();
             detailViewClass = app[detailName];
             detailView = new detailViewClass({model: model, collection:xos[collection_name]});
             app[regionName].show(detailView);
-            $("#xos-detail-button-box").show();
-            $("#xos-listview-button-box").hide();
+
+            detailButtons = new XOSDetailButtonView({linkedView: detailView});
+            app["rightButtonPanel"].show(detailButtons);
         }
     },
 
@@ -136,14 +154,9 @@ XOSApplication = Marionette.Application.extend({
         var app=this;
         return function(parent_modelName, parent_fieldName, parent_id) {
             app.Router.showPreviousURL();
-            console.log("acs");
-            console.log(parent_modelName);
-            console.log(parent_fieldName);
-            console.log(parent_id);
             model = new xos[collection_name].model();
             model.attributes[parent_fieldName] = parent_id;
             model.readOnlyFields.push(parent_fieldName);
-            console.log(model);
             detailViewClass = app[addChildName];
             var detailView = new detailViewClass({model: model, collection:xos[collection_name]});
             detailView.dialog = $("xos-addchild-dialog");
@@ -156,7 +169,7 @@ XOSApplication = Marionette.Application.extend({
                     "Save" : function() {
                       var addDialog = this;
                       detailView.synchronous = true;
-                      detailView.afterSave = function() { console.log("afterSave"); $(addDialog).dialog("close"); }
+                      detailView.afterSave = function() { console.log("addChild afterSave"); $(addDialog).dialog("close"); }
                       detailView.save();
 
                       //$(this).dialog("close");
@@ -196,8 +209,9 @@ XOSApplication = Marionette.Application.extend({
                 detailView = new detailViewClass({model: model});
                 app[regionName].show(detailView);
                 detailView.showLinkedItems();
-                $("#xos-detail-button-box").show();
-                $("#xos-listview-button-box").hide();
+
+                detailButtons = new XOSDetailButtonView({linkedView: detailView});
+                app["rightButtonPanel"].show(detailButtons);
             }
         }
         return showModelId;
@@ -344,6 +358,43 @@ XOSApplication = Marionette.Application.extend({
     },
 });
 
+XOSButtonView = Marionette.ItemView.extend({
+            events: {"click button.btn-xos-save-continue": "submitContinueClicked",
+                     "click button.btn-xos-save-leave": "submitLeaveClicked",
+                     "click button.btn-xos-save-another": "submitAddAnotherClicked",
+                     "click button.btn-xos-delete": "deleteClicked",
+                     "click button.btn-xos-add": "addClicked",
+                     "click button.btn-xos-refresh": "refreshClicked",
+                     },
+
+            submitLeaveClicked: function(e) {
+                     this.options.linkedView.submitLeaveClicked.call(this.options.linkedView, e);
+                     },
+
+            submitContinueClicked: function(e) {
+                     this.options.linkedView.submitContinueClicked.call(this.options.linkedView, e);
+                     },
+
+            submitAddAnotherClicked: function(e) {
+                     this.options.linkedView.submitAddAnotherClicked.call(this.options.linkedView, e);
+                     },
+
+            submitDeleteClicked: function(e) {
+                     this.options.linkedView.submitDeleteClicked.call(this.options.linkedView, e);
+                     },
+
+            addClicked: function(e) {
+                     this.options.linkedView.addClicked.call(this.options.linkedView, e);
+                     },
+
+            refreshClicked: function(e) {
+                     this.options.linkedView.refreshClicked.call(this.options.linkedView, e);
+                     },
+            });
+
+XOSDetailButtonView = XOSButtonView.extend({ template: "#xos-savebuttons-template" });
+XOSListButtonView = XOSButtonView.extend({ template: "#xos-listbuttons-template" });
+
 /* XOSDetailView
       extend with:
          app - MarionetteApplication
@@ -399,9 +450,11 @@ XOSDetailView = Marionette.ItemView.extend({
 
             submitAddAnotherClicked: function(e) {
                 console.log("saveAnother");
+                console.log(this);
                 e.preventDefault();
                 var that=this;
                 this.afterSave = function() {
+                    console.log("addAnother afterSave");
                     that.app.navigate("add", that.model.modelName);
                 }
                 this.save();
@@ -499,7 +552,7 @@ XOSDetailView = Marionette.ItemView.extend({
                         relatedListViewClassName = relatedName + "ListView";
                         assert(this.app[relatedListViewClassName] != undefined, relatedListViewClassName + " not found");
                         relatedListViewClass = this.app[relatedListViewClassName].extend({collection: xos[relatedName],
-                                                                                          filter: makeFilter(relatedField, relatedId), //function(model) { return model.attributes[relatedField]==relatedId; },
+                                                                                          filter: makeFilter(relatedField, relatedId),
                                                                                           parentModel: this.model});
                         this.app[regionName].show(new relatedListViewClass());
                         if (this.app.hideTabsByDefault) {
@@ -542,6 +595,34 @@ XOSDetailView = Marionette.ItemView.extend({
                                                     model: this.model,
                                          }},
 
+             applyConstraints: function() {
+                 for (constraint in this.model.constraints) {
+                     // constraint syntax: "operator,destField.destSubField,srcField.srcSubField"
+                     //   i.e. equal,node.deployment,deploymentNetwork.id
+                     parts = constraints.split(",");
+                     operator = parts[0];
+                     parts1 = parts[1].split(".");
+                     destField = parts1[0];
+                     destSubField = parts1[1];
+                     parts2 = parts[2].split(".");
+                     srcField = parts2[0];
+                     srcID = this.$el.find(srcModel).val();
+                     if (operator == "equal"):
+                         filterMaker = function makeFilter(destSubField,srcID) { return function(linkedObj) { return (linkedObj.attributes[destSubField] == srcID); } };
+                         filterFunc = filterMaker(destSubField, srcID);
+                     else:
+                         continue;
+
+                     newSelect = idToSelect(destField,
+                                            model.attributes[destField],
+                                            model.foreignFields[destField],
+                                            "humanReadableName",
+                                            false,
+                                            filterFunc);
+
+                     this.$el.find(destFieldName).html(newSelect);
+                 },
+
 });
 
 /* XOSItemView
@@ -649,6 +730,213 @@ XOSListView = FilteredCompositeView.extend({
              },
 });
 
+XOSDataTableView = Marionette.View.extend( {
+    el: '<div style="overflow: hidden">' +
+        '<h3 class="xos-list-title title_placeholder"></h3>' +
+        '<div class="header_placeholder"></div>' +
+        '<table></table>' +
+        '<div class="footer_placeholder"></div>' +
+        '</div>',
+
+    filter: undefined,
+
+     events: {"click button.btn-xos-add": "addClicked",
+              "click button.btn-xos-refresh": "refreshClicked",
+             },
+
+     _fetchStateChange: function() {
+         if (this.collection.fetching) {
+            $("#xos-list-title-spinner").show();
+         } else {
+            $("#xos-list-title-spinner").hide();
+         }
+     },
+
+     addClicked: function(e) {
+        e.preventDefault();
+        this.app.Router.navigate("add" + firstCharUpper(this.collection.modelName), {trigger: true});
+     },
+
+     refreshClicked: function(e) {
+         e.preventDefault();
+         this.collection.refresh(refreshRelated=true);
+     },
+
+
+    initialize: function() {
+        $(this.el).find(".footer_placeholder").html( xosListFooterTemplate({addChildHash: this.getAddChildHash()}) );
+        $(this.el).find(".header_placeholder").html( xosListHeaderTemplate() );
+
+        this.listenTo(this.collection, 'fetchStateChange', this._fetchStateChange);
+    },
+
+    render: function() {
+        var view = this;
+
+        view.columnsByIndex = [];
+        view.columnsByFieldName = {};
+        _.each(this.collection.listFields, function(fieldName) {
+            mRender = undefined;
+            mSearchText = undefined;
+            sTitle = fieldNameToHumanReadable(fieldName);
+            bSortable = true;
+            if (fieldName=="backend_status") {
+                mRender = function(x,y,z) { return xosBackendStatusIconTemplate(z); };
+                sTitle = "";
+                bSortable = false;
+            } else if (fieldName in view.collection.foreignFields) {
+                var foreignCollection = view.collection.foreignFields[fieldName];
+                mSearchText = function(x) { return idToName(x, foreignCollection, "humanReadableName"); };
+            }
+            if ($.inArray(fieldName, view.collection.detailLinkFields)>=0) {
+                var collectionName = view.collection.collectionName;
+                mRender = function(x,y,z) { return '<a href="#' + collectionName + '/' + z.id + '">' + x + '</a>'; };
+            }
+            thisColumn = {sTitle: sTitle, bSortable: bSortable, mData: fieldName, mRender: mRender, mSearchText: mSearchText};
+            view.columnsByIndex.push( thisColumn );
+            view.columnsByFieldName[fieldName] = thisColumn;
+        });
+
+        deleteColumn = {sTitle: "", bSortable: false, mRender: function(x,y,z) { return xosDeleteButtonTemplate({modelName: view.collection.modelName, id: z.id}); }, mData: function() { return "delete"; }};
+        view.columnsByIndex.push(deleteColumn);
+        view.columnsByFieldName["delete"] = deleteColumn;
+
+        oTable = $(this.el).find("table").dataTable( {
+            "bJQueryUI": true,
+            "bStateSave": true,
+            "bServerSide": true,
+            "aoColumns": view.columnsByIndex,
+
+            fnServerData: function(sSource, aoData, fnCallback, settings) {
+                var compareColumns = function(sortCols, sortDirs, a, b) {
+                    a = a[sortCols[0]];
+                    b = b[sortCols[0]];
+                    result = (a==b) ? 0 : ((a<b) ? -1 : 1);
+                    if (sortDirs[0] == "desc") {
+                        result = -result;
+                    }
+                    return result;
+                };
+
+                var searchMatch = function(row, sSearch) {
+                    for (fieldName in row) {
+                        if (fieldName in view.columnsByFieldName) {
+                            try {
+                                value = row[fieldName].toString();
+                            } catch(e) {
+                                continue;
+                            }
+                            if (value.indexOf(sSearch) >= 0) {
+                                return true;
+                            }
+                        }
+                    }
+                    return false;
+                };
+
+                //console.log(aoData);
+\r
+                // function used to populate the DataTable with the current\r
+                // content of the collection\r
+                var populateTable = function()\r
+                {\r
+                  console.log("populatetable!");\r
+\r
+                  // clear out old row views\r
+                  rows = [];\r
+\r
+                  sSearch = null;\r
+                  iDisplayStart = 0;\r
+                  iDisplayLength = 1000;\r
+                  sortDirs = [];\r
+                  sortCols = [];\r
+                  _.each(aoData, function(param) {\r
+                      if (param.name == "sSortDir_0") {\r
+                          sortDirs = [param.value];\r
+                      } else if (param.name == "iSortCol_0") {\r
+                          sortCols = [view.columnsByIndex[param.value].mData];\r
+                      } else if (param.name == "iDisplayStart") {\r
+                          iDisplayStart = param.value;\r
+                      } else if (param.name == "iDisplayLength") {\r
+                          iDisplayLength = param.value;\r
+                      } else if (param.name == "sSearch") {\r
+                          sSearch = param.value;\r
+                      }\r
+                  });\r
+\r
+                  aaData = view.collection.toJSON();\r
+\r
+                  // apply backbone filtering on the models\r
+                  if (view.filter) {\r
+                      aaData = aaData.filter( function(row) { model = {}; model.attributes = row; return view.filter(model); } );\r
+                  }\r
+\r
+                  var totalSize = aaData.length;\r
+\r
+                  // turn the ForeignKey fields into human readable things\r
+                  for (rowIndex in aaData) {\r
+                      row = aaData[rowIndex];\r
+                      for (fieldName in row) {\r
+                          if (fieldName in view.columnsByFieldName) {\r
+                              mSearchText = view.columnsByFieldName[fieldName].mSearchText;\r
+                              if (mSearchText) {\r
+                                  row[fieldName] = mSearchText(row[fieldName]);\r
+                              }\r
+                          }\r
+                      }\r
+                  }\r
+\r
+                  // apply datatables search\r
+                  if (sSearch) {\r
+                      aaData = aaData.filter( function(row) { return searchMatch(row, sSearch); });\r
+                  }\r
+\r
+                  var filteredSize = aaData.length;\r
+\r
+                  // apply datatables sort\r
+                  aaData.sort(function(a,b) { return compareColumns(sortCols, sortDirs, a, b); });\r
+\r
+                  // slice it for pagination\r
+                  aaData = aaData.slice(iDisplayStart, iDisplayStart+iDisplayLength);\r
+\r
+                  return fnCallback({iTotalRecords: totalSize,\r
+                         iTotalDisplayRecords: filteredSize,\r
+                         aaData: aaData});\r
+                };\r
+\r
+                aoData.shift(); // ignore sEcho
+                populateTable();
+
+                view.listenTo(view.collection, 'change', populateTable);
+                view.listenTo(view.collection, 'add', populateTable);
+                view.listenTo(view.collection, 'remove', populateTable);
+            },
+        } );
+
+        return this;
+    },
+
+     getAddChildHash: function() {
+        if (this.parentModel) {
+            parentFieldName = this.parentModel.relatedCollections[this.collection.collectionName];
+            parentFieldName = parentFieldName || "unknown";
+
+            /*parentFieldName = "unknown";
+
+            for (fieldName in this.collection.foreignFields) {
+                cname = this.collection.foreignFields[fieldName];
+                if (cname = this.collection.collectionName) {
+                    parentFieldName = fieldName;
+                }
+            }*/
+            return "#addChild" + firstCharUpper(this.collection.modelName) + "/" + this.parentModel.modelName + "/" + parentFieldName + "/" + this.parentModel.id; // modelName, fieldName, id
+        } else {
+            return null;
+        }
+     },
+
+});
+
 idToName = function(id, collectionName, fieldName) {
     return xos.idToName(id, collectionName, fieldName);
 };
@@ -660,7 +948,7 @@ idToName = function(id, collectionName, fieldName) {
    fieldName = name of field within models of collection that will be displayed
 */
 
-idToOptions = function(selectedId, collectionName, fieldName) {
+idToOptions = function(selectedId, collectionName, fieldName, filterFunc) {
     result=""
     for (index in xos[collectionName].models) {
         linkedObject = xos[collectionName].models[index];
@@ -671,6 +959,9 @@ idToOptions = function(selectedId, collectionName, fieldName) {
         } else {
             selected = "";
         }
+        if ((filterFunc) && (!filterFunc(linkedObject)) {
+            continue;
+        }
         result = result + '<option value="' + linkedId + '"' + selected + '>' + linkedName + '</option>';
     }
     return result;
@@ -684,16 +975,15 @@ idToOptions = function(selectedId, collectionName, fieldName) {
    fieldName = name of field within models of collection that will be displayed
 */
 
-idToSelect = function(variable, selectedId, collectionName, fieldName, readOnly) {
+idToSelect = function(variable, selectedId, collectionName, fieldName, readOnly. filterFunc) {
     if (readOnly) {
         readOnly = " readonly";
     } else {
         readOnly = "";
     }
     result = '<select name="' + variable + '"' + readOnly + '>' +
-             idToOptions(selectedId, collectionName, fieldName) +
+             idToOptions(selectedId, collectionName, fieldName, filterFunc) +
              '</select>';
-    console.log(result);
     return result;
 }