set dirty if users edited, warning message if change slice while 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     dirty: false,
106     varName: "XOSTenantApp",
107 });
108
109 XOSTenantApp.addRegions({
110     tenantSliceSelector: "#tenantSliceSelector",
111     tenantSummary: "#tenantSummary",
112     tenantSiteList: "#tenantSiteList",
113     tenantButtons: "#tenantButtons",
114     tenantAddSliceInterior: "#tenant-addslice-interior",
115     tenantEditUsersInterior: "#tenant-edit-users-interior",
116 });
117
118 XOSTenantApp.setDirty = function(dirty) {
119     XOSTenantApp.dirty = dirty;
120     if (dirty) {
121         $("button.btn-tenant-save").addClass("btn-success");
122     } else {
123         $("button.btn-tenant-save").removeClass("btn-success");
124     }
125 };
126
127 XOSTenantApp.buildViews = function() {
128      XOSTenantApp.tenantSites = new XOSTenantSiteCollection();\r
129 \r
130      tenantSummaryClass = XOSTenantSummaryView.extend({template: "#xos-detail-template",\r
131                                                 app: XOSTenantApp,\r
132                                                 detailFields: ["serviceClass", "default_image", "default_flavor", "network_ports", "mount_data_sets"],\r
133                                                 fieldDisplayNames: {serviceClass: "Service Level", "default_flavor": "Flavor", "default_image": "Image", "mount_data_sets": "Data Sets"},\r
134 \r
135                                                 onShow: function() {\r
136                                                     // the slice selector is in a different table, so make every label cell the maximal width\r
137                                                     make_same_width("#xos-tenant-view-panel", ".xos-label-cell");\r
138                                                 },\r
139                                                 });\r
140 \r
141      XOSTenantApp.tenantSummaryView = tenantSummaryClass;\r
142 \r
143      tenantAddClass = XOSDetailView.extend({template: "#xos-detail-template",\r
144                                                 app: XOSTenantApp,\r
145                                                 detailFields: ["name", "description"]});\r
146 \r
147      XOSTenantApp.tenantAddView = tenantAddClass;\r
148 \r
149      tenantSiteItemClass = XOSItemView.extend({template: "#xos-listitem-template",\r
150                                                app: XOSTenantApp});\r
151 \r
152      XOSTenantApp.tenantSiteItemView = tenantSiteItemClass;\r
153 \r
154      tenantSiteListClass = XOSDataTableView.extend({template: "#xos-list-template",\r
155                                                app: XOSTenantApp,\r
156                                                childView: tenantSiteItemClass,\r
157                                                collection: XOSTenantApp.tenantSites,\r
158                                                title: "sites",\r
159                                                inputType: {allocated: "spinner"},\r
160                                                noDeleteColumn: true,\r
161                                                disablePaginate: true,\r
162                                                disableFilter: true,\r
163                                                fieldDisplayNames: {"name": "Site"},\r
164                                                });\r
165 \r
166      XOSTenantApp.tenantSiteListView = tenantSiteListClass;\r
167 \r
168      XOSTenantApp.tenantSliceSelectorView = SliceSelectorView.extend( {\r
169          sliceChanged: function(id) {\r
170              XOSTenantApp.navToSlice(id);\r
171          },\r
172      });\r
173 \r
174      xos.sites.fetch();\r
175      xos.slicesPlus.fetch();\r
176      xos.tenantview.fetch();\r
177 };\r
178 \r
179 make_choices = function(list_of_names, list_of_values) {\r
180     result = [];\r
181     if (!list_of_values) {\r
182         for (index in list_of_names) {\r
183             displayName = list_of_names[index];\r
184             result.push( [displayName, displayName] );\r
185         }\r
186     } else {\r
187         for (index in list_of_names) {\r
188             displayName = list_of_names[index];\r
189             id = list_of_values[index];\r
190             result.push( [displayName, id] );\r
191         }\r
192     }\r
193     return result;\r
194 };\r
195 \r
196 XOSTenantApp.navToSlice = function(id) {\r
197     XOSTenantApp.viewSlice(xos.slicesPlus.get(id));\r
198 };\r
199 \r
200 XOSTenantApp.adjustCollectionField = function(collectionName, id, fieldName, amount) {\r
201     model = XOSTenantApp[collectionName].get(id);\r
202     model.set(fieldName, Math.max(model.get(fieldName) + amount, 0));\r
203     XOSTenantApp.setDirty(true);\r
204 };\r
205 \r
206 XOSTenantApp.addSlice = function() {\r
207     var app=this;\r
208 \r
209     if (!xos.tenant().current_user_can_create_slice) {\r
210         window.alert("You do not have sufficient rights to create a slice on your site");\r
211         return;\r
212     }\r
213 \r
214     model = new xos.slicesPlus.model({site: xos.tenant().current_user_site_id,\r
215                                       name: xos.tenant().current_user_login_base + "_",\r
216                                       creator: xos.tenant().current_user_id});\r
217     console.log(model);\r
218     var detailView = new XOSTenantApp.tenantAddView({model: model,\r
219                                                      collection: xos.slicesPlus,\r
220                                                      noSubmitButton: true,\r
221                                                     });\r
222     detailView.dialog = $("#tenant-addslice-dialog");\r
223     app.tenantAddSliceInterior.show(detailView);\r
224     $("#tenant-addslice-dialog").dialog({\r
225        autoOpen: false,
226        modal: true,
227        width: 640,
228        buttons : {
229             "Create Slice" : function() {
230               var addDialog = this;
231               console.log("SAVE!!!");
232               detailView.synchronous = true;
233               detailView.afterSave = function() { $(addDialog).dialog("close"); XOSTenantApp.navToSlice(detailView.model.id); }
234               detailView.save();
235             },
236             "Cancel" : function() {
237               $(this).dialog("close");
238             }
239           }
240         });
241     $("#tenant-addslice-dialog").dialog("open");\r
242 };\r
243 \r
244 XOSTenantApp.editUsers = function(model) {\r
245     var app=this;\r
246     var detailView = new XOSEditUsersView({model: model, collection: xos.slicesPlus});\r
247     detailView.dialog = $("#tenant-edit-users-dialog");\r
248     app.tenantEditUsersInterior.show(detailView);\r
249     $("#tenant-edit-users-dialog").dialog({\r
250        autoOpen: false,
251        modal: true,
252        width: 640,
253        buttons : {
254             "Ok" : function() {
255               var editDialog = this;
256               user_ids = all_options($("#tenant-edit-users-dialog").find(".select-picker-to"));
257               user_ids = user_ids.map( function(x) { return parseInt(x,10); } );
258               if (!array_same_elements(user_ids, model.usersBuffer)) {
259                   XOSTenantApp.setDirty(true);
260               }
261               model.usersBuffer = user_ids;
262               $(editDialog).dialog("close");
263             },
264             "Cancel" : function() {
265               $(this).dialog("close");
266             }
267           }
268         });
269     $("#tenant-edit-users-dialog").dialog("open");\r
270 };\r
271 \r
272 XOSTenantApp.deleteSlice = function(model) {\r
273     var app=this;\r
274     app.deleteDialog(model, function() { console.log("afterDelete"); app.viewSlice(undefined); });\r
275 };\r
276 \r
277 XOSTenantApp.viewSlice = function(model) {\r
278     if (XOSTenantApp.dirty) {\r
279         if (!confirm("The current sliver has unsaved data -- view new sliver anyway ?")) {\r
280             $("#tenantSliceSelector select").val(XOSTenantApp.currentSlice.id);\r
281             return;\r
282         }\r
283     }\r
284 \r
285     XOSTenantApp.setDirty(false);\r
286 \r
287     if (!model && xos.slicesPlus.models.length > 0) {\r
288         model = xos.slicesPlus.models[0];\r
289     }\r
290 \r
291     if (model) {\r
292         sliceSelector = new XOSTenantApp.tenantSliceSelectorView({collection: xos.slicesPlus,\r
293                                                                   selectedID: model ? model.id : null,\r
294                                                                  } );\r
295         XOSTenantApp.sliceSelector = sliceSelector;\r
296         XOSTenantApp.tenantSliceSelector.show(sliceSelector);\r
297 \r
298         tenantSummary = new XOSTenantApp.tenantSummaryView({model: model,\r
299                                                             choices: {mount_data_sets: make_choices(xos.tenant().public_volume_names, null),\r
300                                                                       serviceClass: make_choices(xos.tenant().blessed_service_class_names, xos.tenant().blessed_service_classes),\r
301                                                                       default_image: make_choices(xos.tenant().blessed_image_names, xos.tenant().blessed_images),\r
302                                                                       default_flavor: make_choices(xos.tenant().blessed_flavor_names, xos.tenant().blessed_flavors),},\r
303                                                            });\r
304         XOSTenantApp.tenantSummary.show(tenantSummary);\r
305 \r
306         tenantSites = new XOSTenantSiteCollection();\r
307         tenantSites.getFromSlice(model);\r
308         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
309         model.usersOrig = model.attributes.users;   /* save an immutable copy that we'll use for username lookups */\r
310         model.user_namesOrig = model.attributes.user_names;\r
311         model.tenantSiteCollection = tenantSites;\r
312         XOSTenantApp.tenantSites = tenantSites;\r
313 \r
314         tenantSiteList = new XOSTenantApp.tenantSiteListView({collection: tenantSites });\r
315         XOSTenantApp.tenantSiteList.show(tenantSiteList);\r
316         // on xos.slicePlus.sort, need to update xostenantapp.tenantSites\r
317 \r
318         XOSTenantApp.tenantButtons.show( new XOSTenantButtonView( { app: XOSTenantApp,\r
319                                                                     linkedView: tenantSummary } ) );\r
320 \r
321         XOSTenantApp.currentSlice = model;\r
322     } else {\r
323         XOSTenantApp.tenantSliceSelector.show(new HTMLView({html: ""}));\r
324         XOSTenantApp.tenantSummary.show(new HTMLView({html: "You have no slices"}));\r
325         XOSTenantApp.tenantSiteList.show(new HTMLView({html: ""}));\r
326         XOSTenantApp.tenantButtons.show( new XOSTenantButtonView( { template: "#xos-tenant-buttons-noslice-template",\r
327                                                                     app: XOSTenantApp,\r
328                                                                     linkedView: tenantSummary } ) );\r
329     }\r
330 };\r
331 \r
332 XOSTenantApp.sanityCheck = function() {\r
333     errors = [];\r
334     if (xos.tenant().blessed_service_classes.length == 0) {\r
335         errors.push("no blessed service classes");\r
336     }\r
337     if (xos.tenant().blessed_flavors.length == 0) {\r
338         errors.push("no blessed flavors");\r
339     }\r
340     if (xos.tenant().blessed_images.length == 0) {\r
341         errors.push("no blessed images");\r
342     }\r
343     if (xos.tenant().blessed_sites.length == 0) {\r
344         errors.push("no blessed sites");\r
345     }\r
346     if (xos.tenant().current_user_site_id == null) {\r
347         errors.push("current user does not have a site");\r
348     }\r
349 \r
350     if (errors.length > 0) {\r
351          $("#tenantSummary").html("Tenant view sanity check failed<br>" + errors.join("<br>"));\r
352          return false;\r
353     }\r
354 \r
355     return true;\r
356 }\r
357 \r
358 XOSTenantApp.collectionLoadChange = function() {\r
359     stats = xos.getCollectionStatus();\r
360 \r
361     if (!XOSTenantApp.navigationStarted) {\r
362         if (stats["isLoaded"] + stats["failedLoad"] >= stats["startedLoad"]) {\r
363             if (XOSTenantApp.sanityCheck()) {\r
364                 XOSTenantApp.viewSlice(undefined);\r
365             }\r
366         } else {\r
367             $("#tenantSummary").html("<h3>Loading...</h3><div id='xos-startup-progress'></div>");\r
368             $("#xos-startup-progress").progressbar({value: stats["completedLoad"], max: stats["startedLoad"]});\r
369         }\r
370     }\r
371 };\r
372 \r
373 XOSTenantApp.on("start", function() {\r
374      XOSTenantApp.buildViews();
375
376      // fire it once to initially show the progress bar
377      XOSTenantApp.collectionLoadChange();
378
379      // fire it each time the collection load status is updated
380      Backbone.on("xoslib:collectionLoadChange", XOSTenantApp.collectionLoadChange);
381 });
382
383 $(document).ready(function(){
384     XOSTenantApp.start();
385 });
386