edit users button in tenant view
Scott Baker [Tue, 13 Jan 2015 03:45:40 +0000 (19:45 -0800)]
planetstack/core/xoslib/dashboards/xosTenant.html
planetstack/core/xoslib/methods/sliceplus.py
planetstack/core/xoslib/methods/tenantview.py
planetstack/core/xoslib/objects/sliceplus.py
planetstack/core/xoslib/static/js/xosTenant.js
planetstack/core/xoslib/static/js/xoslib/xos-util.js
planetstack/core/xoslib/static/js/xoslib/xosHelper.js
planetstack/core/xoslib/templates/xosAdmin.html

index 42a41e0..16e60f0 100644 (file)
 <script src="{{ STATIC_URL }}/js/xoslib/xos-validators.js"></script>
 <script src="{{ STATIC_URL }}/js/xoslib/xos-backbone.js"></script>
 <script src="{{ STATIC_URL }}/js/xoslib/xosHelper.js"></script>
+<script src="{{ STATIC_URL }}/js/picker.js"></script>
 <script src="{{ STATIC_URL }}/js/xosTenant.js"></script>
 
 <script type="text/template" id="xos-tenant-buttons-template">
   <div class="box save-box">
     <button class="btn btn-high btn-tenant-create">Create New Slice</button>
     <button class="btn btn-high btn-tenant-delete">Delete Slice</button>
-    <button class="btn btn-high btn-tenant-add-user">Add User</button>
+    <button class="btn btn-high btn-tenant-add-user">Edit Users</button>
     <button class="btn btn-high btn-tenant-save">Save</button>
   </div>
 </script>
   </tr>
 </script>
 
+<script type="text/template" id="tenant-edit-users">
+    <%= xosPickerTemplate({pickedItems: model.attributes.users,
+                          unpickedItems: array_diff(xos.tenant().current_user_site_users, model.attributes.users),
+                          id: "users",
+                          fieldName: "users",
+                          detailView: detailView,
+                          lookupFunc: function(x) { return array_pair_lookup(x, xos.tenant().current_user_site_user_names, xos.tenant().current_user_site_users); },
+                          } ) %>
+</script>
+
 <div id="xos-confirm-dialog" title="Confirmation Required">
   Are you sure about this?\r
 </div>
 
 <div id="tenant-addslice-dialog" title="Add Child">
 <div id="tenant-addslice-interior"></div>\r
-</div>
+</div>\r
+\r
+<div id="tenant-edit-users-dialog" title="Add Child">\r
+<div id="tenant-edit-users-interior"></div>\r
+</div>\r
 
 <div id="xos-error-dialog" title="Error Message">
 </div>\r
index 0cfc67c..c48d036 100644 (file)
@@ -22,7 +22,14 @@ class NetworkPortsField(serializers.WritableField):   # note: maybe just Field i
     def to_internal_value(self, data):
         return data
 
-class SiteAllocationField(serializers.WritableField):   # note: maybe just Field in rest_framework 3.x instead of WritableField
+class DictionaryField(serializers.WritableField):   # note: maybe just Field in rest_framework 3.x instead of WritableField
+    def to_representation(self, obj):
+        return json.dumps(obj)
+
+    def to_internal_value(self, data):
+        return json.loads(data)
+
+class ListField(serializers.WritableField):   # note: maybe just Field in rest_framework 3.x instead of WritableField
     def to_representation(self, obj):
         return json.dumps(obj)
 
@@ -35,7 +42,8 @@ class SlicePlusIdSerializer(serializers.ModelSerializer, PlusSerializerMixin):
         sliceInfo = serializers.SerializerMethodField("getSliceInfo")\r
         humanReadableName = serializers.SerializerMethodField("getHumanReadableName")\r
         network_ports = NetworkPortsField(required=False)\r
-        site_allocation = SiteAllocationField(required=False)\r
+        site_allocation = DictionaryField(required=False)\r
+        users = ListField(required=False)\r
 \r
         def getSliceInfo(self, slice):\r
             return slice.getSliceInfo(user=self.context['request'].user)\r
@@ -44,13 +52,12 @@ class SlicePlusIdSerializer(serializers.ModelSerializer, PlusSerializerMixin):
             return str(obj)\r
 \r
         networks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)\r
-#        availableNetworks = serializers.PrimaryKeyRelatedField(many=True, read_only=True, view_name='network-detail')\r
 \r
         class Meta:\r
             model = SlicePlus\r
             fields = ('humanReadableName', 'id','created','updated','enacted','name','enabled','omf_friendly','description','slice_url','site','max_slivers','service','network','mount_data_sets',
                       'default_image', 'default_flavor',
-                      'serviceClass','creator','networks','sliceInfo','network_ports','backendIcon','backendHtml','site_allocation')
+                      'serviceClass','creator','networks','sliceInfo','network_ports','backendIcon','backendHtml','site_allocation','users')
 
 class SlicePlusList(PlusListCreateAPIView): #generics.ListCreateAPIView):
     queryset = SlicePlus.objects.select_related().all()
index 596c082..b2e0e0e 100644 (file)
@@ -46,6 +46,10 @@ def getTenantViewDict(user):
         if not volume.private:\r
             volumes.append(volume)
 
+    site_users=[]
+    for auser in user.site.users.all():
+        site_users.append(auser)
+
     blessed_service_classes = [ServiceClass.objects.get(name="Best Effort")]
 
     return {"id": 0,
@@ -62,6 +66,8 @@ def getTenantViewDict(user):
             "public_volumes": [volume.id for volume in volumes],
             "current_user_site_id": user.site.id,
             "current_user_login_base": user.site.login_base,
+            "current_user_site_users": [auser.id for auser in site_users],
+            "current_user_site_user_names": [auser.email for auser in site_users],
             }
 
 class TenantList(APIView):
index 7ec8e27..adbc77e 100644 (file)
@@ -1,4 +1,4 @@
-from core.models.slice import Slice
+from core.models.slice import Slice, SlicePrivilege
 from plus import PlusObjectMixin
 
 class SlicePlus(Slice, PlusObjectMixin):
@@ -35,6 +35,18 @@ class SlicePlus(Slice, PlusObjectMixin):
         print "XXX set sitesUsed to", value
 
     @property
+    def users(self):
+        user_ids = []
+        for priv in SlicePrivilege.objects.filter(slice=self):
+            if not (priv.user.id in user_ids):
+                user_ids.append(priv.user.id)
+        return user_ids
+
+    @users.setter
+    def users(self, value):
+        print "XXX set users to", value
+
+    @property
     def network_ports(self):
         # XXX this assumes there is only one network that can have ports bound
         # to it for a given slice. This is intended for the tenant view, which
index 8bf2442..fc510f3 100644 (file)
@@ -9,7 +9,7 @@ XOSTenantSiteCollection = XOSCollection.extend( {
     modelName: "tenantSite",
     collectionName: "tenantSites",
 
-    updateFromSlice: function(slice) {
+    getFromSlice: function(slice) {
         var tenantSites = [];
         var id = 0;
         for (siteName in slice.attributes.site_allocation) {
@@ -26,8 +26,31 @@ XOSTenantSiteCollection = XOSCollection.extend( {
         }
         this.set(tenantSites);
     },
+
+    putToSlice: function(slice) {
+        slice.attributes.site_allocation = {};
+        for (index in this.models) {
+            model = this.models[index];
+            slice.attributes.site_allocation[ model.attributes.name ] = model.attributes.allocated;
+        }
+    },
 });
 
+XOSEditUsersView = Marionette.ItemView.extend({
+            template: "#tenant-edit-users",
+            viewInitializers: [],
+
+            onShow: function() {
+                _.each(this.viewInitializers, function(initializer) {
+                    initializer();
+                });
+            },
+
+            templateHelpers: function() { return { detailView: this, model: this.model }; },
+
+            });
+
+
 XOSTenantButtonView = Marionette.ItemView.extend({
             template: "#xos-tenant-buttons-template",
 
@@ -46,9 +69,12 @@ XOSTenantButtonView = Marionette.ItemView.extend({
                      },
 
             addUserClicked: function(e) {
+                     XOSTenantApp.editUsers(this.options.linkedView.model);
                      },
 
             saveClicked: function(e) {
+                     model = this.options.linkedView.model;
+                     model.tenantSiteCollection.putToSlice(model);
                      this.options.linkedView.submitContinueClicked.call(this.options.linkedView, e);
                      },
             });
@@ -66,6 +92,7 @@ XOSTenantApp.addRegions({
     tenantSiteList: "#tenantSiteList",
     tenantButtons: "#tenantButtons",
     tenantAddSliceInterior: "#tenant-addslice-interior",
+    tenantEditUsersInterior: "#tenant-edit-users-interior",
 });
 
 XOSTenantApp.buildViews = function() {
@@ -73,7 +100,9 @@ XOSTenantApp.buildViews = function() {
 \r
      tenantSummaryClass = XOSDetailView.extend({template: "#xos-detail-template",\r
                                                 app: XOSTenantApp,\r
-                                                detailFields: ["serviceClass", "default_image", "default_flavor", "network_ports", "mount_data_sets"]});\r
+                                                detailFields: ["serviceClass", "default_image", "default_flavor", "network_ports", "mount_data_sets"],\r
+                                                fieldDisplayNames: {serviceClass: "Service Level", "default_flavor": "Flavor", "default_image": "Image"},\r
+                                                });\r
 \r
      XOSTenantApp.tenantSummaryView = tenantSummaryClass;\r
 \r
@@ -138,10 +167,14 @@ XOSTenantApp.adjustCollectionField = function(collectionName, id, fieldName, amo
 \r
 XOSTenantApp.addSlice = function() {\r
     var app=this;\r
-    model = new xos.slicesPlus.model({site: xos.tenant().current_user_site_id});\r
+    model = new xos.slicesPlus.model({site: xos.tenant().current_user_site_id,\r
+                                      name: xos.tenant().current_user_login_base + "_"});\r
     console.log(model);\r
-    var detailView = new XOSTenantApp.tenantAddView({model: model, collection: xos.slicesPlus});\r
-    detailView.dialog = $("tenant-addslice-dialog");\r
+    var detailView = new XOSTenantApp.tenantAddView({model: model,\r
+                                                    collection: xos.slicesPlus,\r
+                                                    noSubmitButton: true,\r
+                                                    });\r
+    detailView.dialog = $("#tenant-addslice-dialog");\r
     app.tenantAddSliceInterior.show(detailView);\r
     $("#tenant-addslice-dialog").dialog({\r
        autoOpen: false,
@@ -150,6 +183,7 @@ XOSTenantApp.addSlice = function() {
        buttons : {
             "Save" : function() {
               var addDialog = this;
+              console.log("SAVE!!!");
               detailView.synchronous = true;
               detailView.afterSave = function() { $(addDialog).dialog("close"); XOSTenantApp.navToSlice(detailView.model.id); }
               detailView.save();
@@ -162,6 +196,31 @@ XOSTenantApp.addSlice = function() {
     $("#tenant-addslice-dialog").dialog("open");\r
 };\r
 \r
+XOSTenantApp.editUsers = function(model) {\r
+    var app=this;\r
+    var detailView = new XOSEditUsersView({model: model, collection: xos.slicesPlus});\r
+    detailView.dialog = $("#tenant-edit-users-dialog");\r
+    app.tenantEditUsersInterior.show(detailView);\r
+    $("#tenant-edit-users-dialog").dialog({\r
+       autoOpen: false,
+       modal: true,
+       width: 640,
+       buttons : {
+            "Save" : function() {
+              var editDialog = this;
+              user_ids = all_options($("#tenant-edit-users-dialog").find(".select-picker-to"));
+              user_ids = user_ids.map( function(x) { return parseInt(x,10); } );
+              model.attributes.users = user_ids;
+              $(editDialog).dialog("close");
+            },
+            "Cancel" : function() {
+              $(this).dialog("close");
+            }
+          }
+        });
+    $("#tenant-edit-users-dialog").dialog("open");\r
+};\r
+\r
 XOSTenantApp.deleteSlice = function(model) {\r
     var app=this;\r
     app.deleteDialog(model, function() { console.log("afterDelete"); app.viewSlice(undefined); });\r
@@ -181,13 +240,14 @@ XOSTenantApp.viewSlice = function(model) {
     tenantSummary = new XOSTenantApp.tenantSummaryView({model: model,\r
                                                         choices: {mount_data_sets: make_choices(xos.tenant().public_volume_names, null),\r
                                                                   serviceClass: make_choices(xos.tenant().blessed_service_class_names, xos.tenant().blessed_service_classes),\r
-                                                                  default_image: make_choices(xos.tenant().blessed_image_names, xos.tenant().blessed_image_ids),\r
-                                                                  default_flavor: make_choices(xos.tenant().blessed_flavor_names, xos.tenant().blessed_flavor_ids),},\r
+                                                                  default_image: make_choices(xos.tenant().blessed_image_names, xos.tenant().blessed_images),\r
+                                                                  default_flavor: make_choices(xos.tenant().blessed_flavor_names, xos.tenant().blessed_flavors),},\r
                                                        });\r
     XOSTenantApp.tenantSummary.show(tenantSummary);\r
 \r
     tenantSites = new XOSTenantSiteCollection();\r
-    tenantSites.updateFromSlice(model);\r
+    tenantSites.getFromSlice(model);\r
+    model.tenantSiteCollection = tenantSites;\r
     XOSTenantApp.tenantSites = tenantSites;\r
 \r
     tenantSiteList = new XOSTenantApp.tenantSiteListView({collection: tenantSites });\r
index 3fd597b..1d135f4 100644 (file)
@@ -79,3 +79,35 @@ function validateField(validatorName, value, obj) {
 
     return true;
 }
+
+function array_diff(a1, a2)
+{\r
+  var a=[], diff=[];\r
+  for(var i=0;i<a1.length;i++)\r
+    a[a1[i]]=true;\r
+  for(var i=0;i<a2.length;i++)\r
+    if(a[a2[i]]) delete a[a2[i]];\r
+    else a[a2[i]]=true;\r
+  for(var k in a)\r
+    diff.push(k);\r
+  return diff;\r
+}
+
+function array_pair_lookup(x, names, values)
+{
+    for (index in values) {
+        if (values[index] == x) {
+            return names[index];
+        }
+    }
+    return undefined;
+}
+
+function all_options(selector) {
+    el = $(selector);
+    result = [];
+    _.each(el.find("option"), function(option) {
+        result.push($(option).val());
+    });
+    return result;
+}
index 9f9964c..e8c1b10 100644 (file)
@@ -80,8 +80,13 @@ XOSRouter = Marionette.AppRouter.extend({
             Marionette.AppRouter.prototype.navigate.call(this, href, options);
         },
     });\r
-
-Backbone.Syphon.InputReaders.register('select', function(el) {
+\r
+// XXX - We import backbone multiple times (BAD!) since the import happens\r
+//   inside of the view's html. The second time it's imported (developer\r
+//   view), it wipes out Backbone.Syphon. So, save it as Backbone_Syphon for\r
+//   now.\r
+Backbone_Syphon = Backbone.Syphon\r
+Backbone_Syphon.InputReaders.register('select', function(el) {\r
     // Modify syphon so that if a select has "syphonall" in the class, then
     // the value of every option will be returned, regardless of whether of
     // not it is selected.
@@ -498,6 +503,9 @@ XOSDetailView = Marionette.ItemView.extend({
             submitLeaveClicked: function(e) {
                 console.log("saveLeave");
                 e.preventDefault();
+                if (this.options.noSubmitButton || this.noSubmitButton) {
+                    return;
+                }
                 var that=this;
                 this.afterSave = function() {
                     that.app.navigate("list", that.model.modelName);
@@ -519,7 +527,7 @@ XOSDetailView = Marionette.ItemView.extend({
 
             save: function() {
                 this.app.hideError();
-                var data = Backbone.Syphon.serialize(this);
+                var data = Backbone_Syphon.serialize(this);
                 var that = this;
                 var isNew = !this.model.id;
 
@@ -647,6 +655,7 @@ XOSDetailView = Marionette.ItemView.extend({
                                                     addFields: this.model.addFields,
                                                     listFields: this.model.listFields,
                                                     detailFields: this.options.detailFields || this.detailFields || this.model.detailFields,
+                                                    fieldDisplayNames: this.options.fieldDisplayNames || this.fieldDisplayNames || this.model.fieldDisplayNames || {},
                                                     foreignFields: this.model.foreignFields,
                                                     detailLinkFields: this.model.detailLinkFields,
                                                     inputType: this.model.inputType,
index 53b9fe6..c155848 100644 (file)
   <table>\r
   <% args = arguments; %>\r
   <% _.each(detailFields, function(fieldName) { %>\r
-     <tr><td><%= fieldNameToHumanReadable(fieldName) %>:</td>\r
+     <tr><td><%= fieldName in fieldDisplayNames ? fieldDisplayNames[fieldName] : fieldNameToHumanReadable(fieldName) %>:</td>\r
         <% readOnly = $.inArray(fieldName, model.readOnlyFields)>=0 ? " readonly" : "";  %>\r
         <% if (fieldName in choices) { %>\r
             <td><%= choicesToSelect(fieldName, model.attributes[fieldName], choices[fieldName]) %></td>\r
             <td><%= idToSelect(fieldName, model.attributes[fieldName], foreignFields[fieldName], "humanReadableName", readOnly) %></td>\r
         <% } else if (inputType[fieldName] == "spinner") { %>\r
             <!-- note: I never finished working on this spinner stuff! -->\r
-            <td><%= xosSpinnerTemplate({id: "picker_" + fieldName, fieldName: fieldName, value: model.attributes[fieldName]}) %></td>\r
+            <td><%= xosSpinnerTemplate({id: "spinner_" + fieldName, fieldName: fieldName, value: model.attributes[fieldName]}) %></td>\r
         <% } else if (inputType[fieldName] == "checkbox") { %>\r
             <td><input type="checkbox" name="<%= fieldName %>" <% if (model.attributes[fieldName]) print("checked"); %><%= readOnly %>></td>\r
         <% } else if (inputType[fieldName] == "picker") { %>\r