make save button green when slice is dirty
[plstackapi.git] / planetstack / core / xoslib / static / js / xosTenant.js
1 XOSTenantSite = XOSModel.extend( {
2     listFields: ["name", "allocated"],
3     modelName: "tenantSite",
4     collectionName: "tenantSites"
5 });
6
7 XOSTenantSiteCollection = XOSCollection.extend( {
8     listFields: ["name", "allocated"],
9     modelName: "tenantSite",
10     collectionName: "tenantSites",
11
12     getFromSlice: function(slice) {
13         var tenantSites = [];
14         var id = 0;
15         for (siteName in slice.attributes.site_allocation) {
16             allocated = slice.attributes.site_allocation[siteName];
17             tenantSites.push(new XOSTenantSite( { name: siteName, allocated: allocated, id: id} ));
18             id = id + 1;
19         }
20         for (index in xos.tenantview.models[0].attributes.blessed_site_names) {
21             siteName = xos.tenantview.models[0].attributes.blessed_site_names[index];
22             if (! (siteName in slice.attributes.site_allocation)) {
23                 tenantSites.push(new XOSTenantSite( { name: siteName, allocated: 0, id: id} ));
24                 id = id + 1;
25             }
26         }
27         this.set(tenantSites);
28     },
29
30     putToSlice: function(slice) {
31         slice.attributes.site_allocation = {};
32         for (index in this.models) {
33             var model = this.models[index];
34             slice.attributes.site_allocation[ model.attributes.name ] = model.attributes.allocated;
35         }
36     },
37 });
38
39 XOSEditUsersView = Marionette.ItemView.extend({
40             template: "#tenant-edit-users",
41             viewInitializers: [],
42
43             onShow: function() {
44                 _.each(this.viewInitializers, function(initializer) {
45                     initializer();
46                 });
47             },
48
49             templateHelpers: function() { return { detailView: this, model: this.model }; },
50
51             });
52
53 XOSTenantSummaryView = XOSDetailView.extend({
54             events: {"change": "onChange"},
55
56             onChange: function(e) {
57                 XOSTenantApp.setDirty(true);
58             },
59
60             saveSuccess: function() {
61                 console.log("saveSuccess!");
62                 XOSTenantApp.setDirty(false);
63             },
64
65             });
66
67
68 XOSTenantButtonView = Marionette.ItemView.extend({
69             template: "#xos-tenant-buttons-template",
70
71             events: {"click button.btn-tenant-create": "createClicked",
72                      "click button.btn-tenant-delete": "deleteClicked",
73                      "click button.btn-tenant-add-user": "addUserClicked",
74                      "click button.btn-tenant-save": "saveClicked",
75                      },
76
77             createClicked: function(e) {
78                      XOSTenantApp.addSlice();
79                      },
80
81             deleteClicked: function(e) {
82                      XOSTenantApp.deleteSlice(this.options.linkedView.model);
83                      },
84
85             addUserClicked: function(e) {
86                      XOSTenantApp.editUsers(this.options.linkedView.model);
87                      },
88
89             saveClicked: function(e) {
90                      model = this.options.linkedView.model;
91                      model.tenantSiteCollection.putToSlice(model);
92                      model.attributes.users = model.usersBuffer;
93
94                      e.preventDefault();
95                      this.options.linkedView.save();
96                      //this.options.linkedView.submitContinueClicked.call(this.options.linkedView, e);
97                      //XOSTenantApp.setDirty(false);
98                      },
99             });
100
101 XOSTenantApp = new XOSApplication({
102     logTableId: "#logTable",
103     statusMsgId: "#statusMsg",
104     hideTabsByDefault: true,
105     varName: "XOSTenantApp",
106 });
107
108 XOSTenantApp.addRegions({
109     tenantSliceSelector: "#tenantSliceSelector",
110     tenantSummary: "#tenantSummary",
111     tenantSiteList: "#tenantSiteList",
112     tenantButtons: "#tenantButtons",
113     tenantAddSliceInterior: "#tenant-addslice-interior",
114     tenantEditUsersInterior: "#tenant-edit-users-interior",
115 });
116
117 XOSTenantApp.setDirty = function(dirty) {
118     if (dirty) {
119         $("button.btn-tenant-save").addClass("btn-success");
120     } else {
121         $("button.btn-tenant-save").removeClass("btn-success");
122     }
123 };
124
125 XOSTenantApp.buildViews = function() {
126      XOSTenantApp.tenantSites = new XOSTenantSiteCollection();\r
127 \r
128      tenantSummaryClass = XOSTenantSummaryView.extend({template: "#xos-detail-template",\r
129                                                 app: XOSTenantApp,\r
130                                                 detailFields: ["serviceClass", "default_image", "default_flavor", "network_ports", "mount_data_sets"],\r
131                                                 fieldDisplayNames: {serviceClass: "Service Level", "default_flavor": "Flavor", "default_image": "Image", "mount_data_sets": "Data Sets"},\r
132 \r
133                                                 onShow: function() {\r
134                                                     // the slice selector is in a different table, so make every label cell the maximal width\r
135                                                     make_same_width("#xos-tenant-view-panel", ".xos-label-cell");\r
136                                                 },\r
137                                                 });\r
138 \r
139      XOSTenantApp.tenantSummaryView = tenantSummaryClass;\r
140 \r
141      tenantAddClass = XOSDetailView.extend({template: "#xos-detail-template",\r
142                                                 app: XOSTenantApp,\r
143                                                 detailFields: ["name", "description"]});\r
144 \r
145      XOSTenantApp.tenantAddView = tenantAddClass;\r
146 \r
147      tenantSiteItemClass = XOSItemView.extend({template: "#xos-listitem-template",\r
148                                                app: XOSTenantApp});\r
149 \r
150      XOSTenantApp.tenantSiteItemView = tenantSiteItemClass;\r
151 \r
152      tenantSiteListClass = XOSDataTableView.extend({template: "#xos-list-template",\r
153                                                app: XOSTenantApp,\r
154                                                childView: tenantSiteItemClass,\r
155                                                collection: XOSTenantApp.tenantSites,\r
156                                                title: "sites",\r
157                                                inputType: {allocated: "spinner"},\r
158                                                noDeleteColumn: true,\r
159                                                disablePaginate: true,\r
160                                                disableFilter: true,\r
161                                                fieldDisplayNames: {"name": "Site"},\r
162                                                });\r
163 \r
164      XOSTenantApp.tenantSiteListView = tenantSiteListClass;\r
165 \r
166      XOSTenantApp.tenantSliceSelectorView = SliceSelectorView.extend( {\r
167          sliceChanged: function(id) {\r
168              XOSTenantApp.navToSlice(id);\r
169          },\r
170      });\r
171 \r
172      xos.sites.fetch();\r
173      xos.slicesPlus.fetch();\r
174      xos.tenantview.fetch();\r
175 };\r
176 \r
177 make_choices = function(list_of_names, list_of_values) {\r
178     result = [];\r
179     if (!list_of_values) {\r
180         for (index in list_of_names) {\r
181             displayName = list_of_names[index];\r
182             result.push( [displayName, displayName] );\r
183         }\r
184     } else {\r
185         for (index in list_of_names) {\r
186             displayName = list_of_names[index];\r
187             id = list_of_values[index];\r
188             result.push( [displayName, id] );\r
189         }\r
190     }\r
191     return result;\r
192 };\r
193 \r
194 XOSTenantApp.navToSlice = function(id) {\r
195     XOSTenantApp.viewSlice(xos.slicesPlus.get(id));\r
196 };\r
197 \r
198 XOSTenantApp.adjustCollectionField = function(collectionName, id, fieldName, amount) {\r
199     model = XOSTenantApp[collectionName].get(id);\r
200     model.set(fieldName, Math.max(model.get(fieldName) + amount, 0));\r
201     XOSTenantApp.setDirty(true);\r
202 };\r
203 \r
204 XOSTenantApp.addSlice = function() {\r
205     var app=this;\r
206 \r
207     if (!xos.tenant().current_user_can_create_slice) {\r
208         window.alert("You do not have sufficient rights to create a slice on your site");\r
209         return;\r
210     }\r
211 \r
212     model = new xos.slicesPlus.model({site: xos.tenant().current_user_site_id,\r
213                                       name: xos.tenant().current_user_login_base + "_",\r
214                                       creator: xos.tenant().current_user_id});\r
215     console.log(model);\r
216     var detailView = new XOSTenantApp.tenantAddView({model: model,\r
217                                                      collection: xos.slicesPlus,\r
218                                                      noSubmitButton: true,\r
219                                                     });\r
220     detailView.dialog = $("#tenant-addslice-dialog");\r
221     app.tenantAddSliceInterior.show(detailView);\r
222     $("#tenant-addslice-dialog").dialog({\r
223        autoOpen: false,
224        modal: true,
225        width: 640,
226        buttons : {
227             "Create Slice" : function() {
228               var addDialog = this;
229               console.log("SAVE!!!");
230               detailView.synchronous = true;
231               detailView.afterSave = function() { $(addDialog).dialog("close"); XOSTenantApp.navToSlice(detailView.model.id); }
232               detailView.save();
233             },
234             "Cancel" : function() {
235               $(this).dialog("close");
236             }
237           }
238         });
239     $("#tenant-addslice-dialog").dialog("open");\r
240 };\r
241 \r
242 XOSTenantApp.editUsers = function(model) {\r
243     var app=this;\r
244     var detailView = new XOSEditUsersView({model: model, collection: xos.slicesPlus});\r
245     detailView.dialog = $("#tenant-edit-users-dialog");\r
246     app.tenantEditUsersInterior.show(detailView);\r
247     $("#tenant-edit-users-dialog").dialog({\r
248        autoOpen: false,
249        modal: true,
250        width: 640,
251        buttons : {
252             "Ok" : function() {
253               var editDialog = this;
254               user_ids = all_options($("#tenant-edit-users-dialog").find(".select-picker-to"));
255               user_ids = user_ids.map( function(x) { return parseInt(x,10); } );
256               model.usersBuffer = user_ids;
257               $(editDialog).dialog("close");
258             },
259             "Cancel" : function() {
260               $(this).dialog("close");
261             }
262           }
263         });
264     $("#tenant-edit-users-dialog").dialog("open");\r
265 };\r
266 \r
267 XOSTenantApp.deleteSlice = function(model) {\r
268     var app=this;\r
269     app.deleteDialog(model, function() { console.log("afterDelete"); app.viewSlice(undefined); });\r
270 };\r
271 \r
272 XOSTenantApp.viewSlice = function(model) {\r
273     if (!model && xos.slicesPlus.models.length > 0) {\r
274         model = xos.slicesPlus.models[0];\r
275     }\r
276 \r
277     if (model) {\r
278         sliceSelector = new XOSTenantApp.tenantSliceSelectorView({collection: xos.slicesPlus,\r
279                                                                   selectedID: model ? model.id : null,\r
280                                                                  } );\r
281         XOSTenantApp.sliceSelector = sliceSelector;\r
282         XOSTenantApp.tenantSliceSelector.show(sliceSelector);\r
283 \r
284         tenantSummary = new XOSTenantApp.tenantSummaryView({model: model,\r
285                                                             choices: {mount_data_sets: make_choices(xos.tenant().public_volume_names, null),\r
286                                                                       serviceClass: make_choices(xos.tenant().blessed_service_class_names, xos.tenant().blessed_service_classes),\r
287                                                                       default_image: make_choices(xos.tenant().blessed_image_names, xos.tenant().blessed_images),\r
288                                                                       default_flavor: make_choices(xos.tenant().blessed_flavor_names, xos.tenant().blessed_flavors),},\r
289                                                            });\r
290         XOSTenantApp.tenantSummary.show(tenantSummary);\r
291 \r
292         tenantSites = new XOSTenantSiteCollection();\r
293         tenantSites.getFromSlice(model);\r
294         model.usersBuffer = model.attributes.users; /* save a copy of 'users' that we can edit. This prevents another view (developer) from overwriting our copy with a fetch from the server */\r
295         model.usersOrig = model.attributes.users;   /* save an immutable copy that we'll use for username lookups */\r
296         model.user_namesOrig = model.attributes.user_names;\r
297         model.tenantSiteCollection = tenantSites;\r
298         XOSTenantApp.tenantSites = tenantSites;\r
299 \r
300         tenantSiteList = new XOSTenantApp.tenantSiteListView({collection: tenantSites });\r
301         XOSTenantApp.tenantSiteList.show(tenantSiteList);\r
302         // on xos.slicePlus.sort, need to update xostenantapp.tenantSites\r
303 \r
304         XOSTenantApp.tenantButtons.show( new XOSTenantButtonView( { app: XOSTenantApp,\r
305                                                                     linkedView: tenantSummary } ) );\r
306     } else {\r
307         XOSTenantApp.tenantSliceSelector.show(new HTMLView({html: ""}));\r
308         XOSTenantApp.tenantSummary.show(new HTMLView({html: "You have no slices"}));\r
309         XOSTenantApp.tenantSiteList.show(new HTMLView({html: ""}));\r
310         XOSTenantApp.tenantButtons.show( new XOSTenantButtonView( { template: "#xos-tenant-buttons-noslice-template",\r
311                                                                     app: XOSTenantApp,\r
312                                                                     linkedView: tenantSummary } ) );\r
313     }\r
314 };\r
315 \r
316 XOSTenantApp.sanityCheck = function() {\r
317     errors = [];\r
318     if (xos.tenant().blessed_service_classes.length == 0) {\r
319         errors.push("no blessed service classes");\r
320     }\r
321     if (xos.tenant().blessed_flavors.length == 0) {\r
322         errors.push("no blessed flavors");\r
323     }\r
324     if (xos.tenant().blessed_images.length == 0) {\r
325         errors.push("no blessed images");\r
326     }\r
327     if (xos.tenant().blessed_sites.length == 0) {\r
328         errors.push("no blessed sites");\r
329     }\r
330     if (xos.tenant().current_user_site_id == null) {\r
331         errors.push("current user does not have a site");\r
332     }\r
333 \r
334     if (errors.length > 0) {\r
335          $("#tenantSummary").html("Tenant view sanity check failed<br>" + errors.join("<br>"));\r
336          return false;\r
337     }\r
338 \r
339     return true;\r
340 }\r
341 \r
342 XOSTenantApp.collectionLoadChange = function() {\r
343     stats = xos.getCollectionStatus();\r
344 \r
345     if (!XOSTenantApp.navigationStarted) {\r
346         if (stats["isLoaded"] + stats["failedLoad"] >= stats["startedLoad"]) {\r
347             if (XOSTenantApp.sanityCheck()) {\r
348                 XOSTenantApp.viewSlice(undefined);\r
349             }\r
350         } else {\r
351             $("#tenantSummary").html("<h3>Loading...</h3><div id='xos-startup-progress'></div>");\r
352             $("#xos-startup-progress").progressbar({value: stats["completedLoad"], max: stats["startedLoad"]});\r
353         }\r
354     }\r
355 };\r
356 \r
357 XOSTenantApp.on("start", function() {\r
358      XOSTenantApp.buildViews();
359
360      // fire it once to initially show the progress bar
361      XOSTenantApp.collectionLoadChange();
362
363      // fire it each time the collection load status is updated
364      Backbone.on("xoslib:collectionLoadChange", XOSTenantApp.collectionLoadChange);
365 });
366
367 $(document).ready(function(){
368     XOSTenantApp.start();
369 });
370