RIFT-14803: UI Composer: References should be dropdowns https://osm.etsi.org/gerrit...
[osm/UI.git] / skyquake / plugins / composer / src / src / stores / CatalogDataStore.js
1
2 /*
3 *
4 * Copyright 2016 RIFT.IO Inc
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 */
19 'use strict';
20
21 import _ from 'lodash'
22 import cc from 'change-case'
23 import alt from '../alt'
24 import UID from '../libraries/UniqueId'
25 import guid from '../libraries/guid'
26 import React from 'react'
27 import DescriptorModel from '../libraries/model/DescriptorModel'
28 import DescriptorModelMetaFactory from '../libraries/model/DescriptorModelMetaFactory'
29 import CatalogPackageManagerActions from '../actions/CatalogPackageManagerActions'
30 import CatalogDataSourceActions from '../actions/CatalogDataSourceActions'
31 import CatalogItemsActions from '../actions/CatalogItemsActions'
32 import ModalOverlayActions from '../actions/ModalOverlayActions'
33 import ComposerAppActions from '../actions/ComposerAppActions'
34 import CatalogDataSource from '../sources/CatalogDataSource'
35 import ComposerAppStore from '../stores/ComposerAppStore'
36 import SelectionManager from '../libraries/SelectionManager'
37 import ExportSelectorDialog from '../components/ExportSelectorDialog'
38
39 const defaults = {
40 catalogs: [],
41 catalogItemExportFormats: ['mano', 'rift'],
42 catalogItemExportGrammars: ['osm', 'tosca']
43 };
44
45 const areCatalogItemsMetaDataEqual = function (a, b) {
46 const metaProps = ['id', 'name', 'short-name', 'description', 'vendor', 'version'];
47 const aMetaData = _.pick(a, metaProps);
48 const bMetaData = _.pick(b, metaProps);
49 return _.isEqual(aMetaData, bMetaData);
50 };
51
52 class CatalogDataStore {
53
54 constructor() {
55 this.catalogs = defaults.catalogs;
56 this.isLoading = true;
57 this.requiresSave = false;
58 this.snapshots = {};
59 this.selectedFormat = defaults.catalogItemExportFormats[0];
60 this.selectedGrammar = defaults.catalogItemExportGrammars[0];
61 this.registerAsync(CatalogDataSource);
62 this.bindActions(CatalogDataSourceActions);
63 this.bindActions(CatalogItemsActions);
64 this.exportPublicMethods({
65 getCatalogs: this.getCatalogs,
66 getCatalogItemById: this.getCatalogItemById,
67 getCatalogItemByUid: this.getCatalogItemByUid,
68 getTransientCatalogs: this.getTransientCatalogs,
69 getTransientCatalogItemById: this.getTransientCatalogItemById,
70 getTransientCatalogItemByUid: this.getTransientCatalogItemByUid
71 });
72 }
73
74 resetSelectionState = () => {
75 this.selectedFormat = defaults.catalogItemExportFormats[0];
76 this.selectedGrammar = defaults.catalogItemExportGrammars[0];
77 }
78
79 getCatalogs() {
80 return this.catalogs || (this.catalogs = []);
81 }
82
83 getTransientCatalogs() {
84 return this.state.catalogs || (this.state.catalogs = []);
85 }
86
87 getAllSelectedCatalogItems() {
88 return this.getCatalogs().reduce((r, d) => {
89 d.descriptors.forEach(d => {
90 if (SelectionManager.isSelected(d) /*d.uiState.selected*/) {
91 r.push(d);
92 }
93 });
94 return r;
95 }, []);
96 }
97
98 getFirstSelectedCatalogItem() {
99 return this.getCatalogs().reduce((r, catalog) => {
100 return r.concat(catalog.descriptors.filter(d => SelectionManager.isSelected(d) /*d.uiState.selected*/));
101 }, [])[0];
102 }
103
104 getCatalogItemById(id) {
105 return this.getCatalogs().reduce((r, catalog) => {
106 return r.concat(catalog.descriptors.filter(d => d.id === id));
107 }, [])[0];
108 }
109
110 getTransientCatalogItemById(id) {
111 return this.getTransientCatalogs().reduce((r, catalog) => {
112 return r.concat(catalog.descriptors.filter(d => d.id === id));
113 }, [])[0];
114 }
115
116 getCatalogItemByUid(uid) {
117 return this.getCatalogs().reduce((r, catalog) => {
118 return r.concat(catalog.descriptors.filter(d => UID.from(d) === uid));
119 }, [])[0];
120 }
121
122 getTransientCatalogItemByUid(uid) {
123 return this.getTransientCatalogs().reduce((r, catalog) => {
124 return r.concat(catalog.descriptors.filter(d => UID.from(d) === uid));
125 }, [])[0];
126 }
127
128 removeCatalogItem(deleteItem = {}) {
129 this.getCatalogs().map(catalog => {
130 catalog.descriptors = catalog.descriptors.filter(d => d.id !== deleteItem.id);
131 return catalog;
132 });
133 }
134
135 addNewItemToCatalog(newItem) {
136 const id = guid();
137 const type = newItem.uiState.type;
138 newItem.id = id;
139 UID.assignUniqueId(newItem.uiState);
140 this.getCatalogs().filter(d => d.type === type).forEach(catalog => {
141 catalog.descriptors.push(newItem);
142 });
143 // update indexes and integrate new model into catalog
144 this.updateCatalogIndexes(this.getCatalogs());
145 return this.getCatalogItemById(id);
146 }
147
148 updateCatalogIndexes(catalogs) {
149 // associate catalog identity with individual descriptors so we can
150 // update the catalog when any given descriptor is updated also add
151 // vnfd model to the nsd object to make it easier to render an nsd
152 const vnfdLookup = {};
153 const updatedCatalogs = catalogs.map(catalog => {
154 catalog.descriptors.map(descriptor => {
155 if (typeof descriptor.meta === 'string' && descriptor.meta.trim() !== '') {
156 try {
157 descriptor.uiState = JSON.parse(descriptor.meta);
158 } catch (ignore) {
159 console.warn('Unable to deserialize the uiState property.');
160 }
161 } else if (typeof descriptor.meta === 'object') {
162 descriptor.uiState = descriptor.meta;
163 descriptor.meta = JSON.stringify(descriptor.meta);
164 }
165
166 const uiState = descriptor.uiState || (descriptor.uiState = {});
167 uiState.catalogId = catalog.id;
168 uiState.catalogName = catalog.name;
169 uiState.type = catalog.type;
170 if (!UID.hasUniqueId(uiState)) {
171 UID.assignUniqueId(uiState);
172 }
173 if (catalog.type === 'vnfd') {
174 vnfdLookup[descriptor.id] = descriptor;
175 }
176 return descriptor;
177 });
178 return catalog;
179 });
180 updatedCatalogs.filter(d => d.type === 'nsd').forEach(catalog => {
181 catalog.descriptors = catalog.descriptors.map(descriptor => {
182 const instanceRefCount = parseInt(descriptor.uiState['instance-ref-count'], 10);
183 if (descriptor['constituent-vnfd']) {
184 descriptor.vnfd = descriptor['constituent-vnfd'].map(d => {
185 const vnfdId = d['vnfd-id-ref'];
186 const vnfd = vnfdLookup[vnfdId];
187 if (!vnfd) {
188 throw new ReferenceError('no VNFD found in the VNFD Catalog for the constituent-vnfd: ' + d);
189 }
190 if (!isNaN(instanceRefCount) && instanceRefCount > 0) {
191 // this will notify user that this item cannot be updated when/if they make a change to it
192 vnfd.uiState['instance-ref-count'] = instanceRefCount;
193 }
194 // create an instance of this vnfd to carry transient ui state properties
195 const instance = _.cloneDeep(vnfd);
196 instance.uiState['member-vnf-index'] = d['member-vnf-index'];
197 instance['vnf-configuration'] = d['vnf-configuration'];
198 instance['start-by-default'] = d['start-by-default'];
199 return instance;
200 });
201 }
202 return descriptor;
203 });
204 });
205 return updatedCatalogs;
206 }
207
208 updateCatalogItem(item) {
209 // replace the given item in the catalog
210 const catalogs = this.getCatalogs().map(catalog => {
211 if (catalog.id === item.uiState.catalogId) {
212 catalog.descriptors = catalog.descriptors.map(d => {
213 if (d.id === item.id) {
214 return item;
215 }
216 return d;
217 });
218 }
219 return catalog;
220 });
221 this.setState({catalogs: catalogs});
222 }
223
224 mergeEditsIntoLatestFromServer(catalogsFromServer = []) {
225
226 // if the UI has modified items use them instead of the server items
227
228 const currentData = this.getCatalogs();
229
230 const modifiedItemsMap = currentData.reduce((result, catalog) => {
231 return result.concat(catalog.descriptors.filter(d => d.uiState.modified));
232 }, []).reduce((r, d) => {
233 r[d.uiState.catalogId + '/' + d.id] = d;
234 return r;
235 }, {});
236
237 const itemMetaMap = currentData.reduce((result, catalog) => {
238 return result.concat(catalog.descriptors.filter(d => d.uiState));
239 }, []).reduce((r, d) => {
240 r[d.uiState.catalogId + '/' + d.id] = d.uiState;
241 return r;
242 }, {});
243
244 const newItemsMap = currentData.reduce((result, catalog) => {
245 result[catalog.id] = catalog.descriptors.filter(d => d.uiState.isNew);
246 return result;
247 }, {});
248
249 catalogsFromServer.forEach(catalog => {
250 catalog.descriptors = catalog.descriptors.map(d => {
251 const key = d.uiState.catalogId + '/' + d.id;
252 if (modifiedItemsMap[key]) {
253 // use local modified item instead of the server item
254 return modifiedItemsMap[key];
255 }
256 if (itemMetaMap[key]) {
257 Object.assign(d.uiState, itemMetaMap[key]);
258 }
259 return d;
260 });
261 if (newItemsMap[catalog.id]) {
262 catalog.descriptors = catalog.descriptors.concat(newItemsMap[catalog.id]);
263 }
264 });
265
266 return catalogsFromServer;
267
268 }
269
270 loadCatalogsSuccess(context) {
271 const fromServer = this.updateCatalogIndexes(context.data);
272 const catalogs = this.mergeEditsIntoLatestFromServer(fromServer);
273 this.setState({
274 catalogs: catalogs,
275 isLoading: false
276 });
277 }
278
279 deleteCatalogItemSuccess (response) {
280 let catalogType = response.catalogType;
281 let itemId = response.itemId;
282 const catalogs = this.getCatalogs().map(catalog => {
283 if (catalog.type === catalogType) {
284 catalog.descriptors = catalog.descriptors.filter(d => d.id !== itemId);
285 }
286 return catalog;
287 });
288
289 this.setState({catalogs: catalogs});
290 }
291
292 deleteCatalogItemError (data) {
293 console.log('Unable to delete', data.catalogType, 'id:', data.itemId, 'Error:', data.error.responseText);
294 ComposerAppActions.showError.defer({
295 errorMessage: 'Unable to delete ' + data.catalogType + ' id: ' + data.itemId + '. Check if it is in use'
296 });
297 }
298
299 selectCatalogItem(item = {}) {
300 SelectionManager.select(item);
301 }
302
303 catalogItemMetaDataChanged(item) {
304 let requiresSave = false;
305 const catalogs = this.getCatalogs().map(catalog => {
306 if (catalog.id === item.uiState.catalogId) {
307 catalog.descriptors = catalog.descriptors.map(d => {
308 if (d.id === item.id) {
309 // compare just the catalog uiState data (id, name, short-name, description, etc.)
310 const modified = !areCatalogItemsMetaDataEqual(d, item);
311 if (modified) {
312 if (d.uiState['instance-ref-count'] > 0) {
313 console.log('cannot edit NSD/VNFD with references to instantiated Network Services');
314 ComposerAppActions.showError.defer({
315 errorMessage: 'Cannot edit NSD/VNFD with references to instantiated Network Services'
316 });
317 return _.cloneDeep(d);
318 } else {
319 item.uiState.modified = modified;
320 requiresSave = true;
321 this.addSnapshot(item);
322 }
323 }
324 return item;
325 }
326 return d;
327 });
328 }
329 return catalog;
330 });
331 if (requiresSave) {
332 this.setState({catalogs: catalogs, requiresSave: true});
333 }
334 }
335
336 catalogItemDescriptorChanged(itemDescriptor) {
337 // when a descriptor object is modified in the canvas we have to update the catalog
338 const catalogId = itemDescriptor.uiState.catalogId;
339 const catalogs = this.getCatalogs().map(catalog => {
340 if (catalog.id === catalogId) {
341 // find the catalog
342 const descriptorId = itemDescriptor.id;
343 // replace the old descriptor with the updated one
344 catalog.descriptors = catalog.descriptors.map(d => {
345 if (d.id === descriptorId) {
346 if (d.uiState['instance-ref-count'] > 0) {
347 console.log('cannot edit NSD/VNFD with references to instantiated Network Services');
348 ComposerAppActions.showError.defer({
349 errorMessage: 'Cannot edit NSD/VNFD with references to instantiated Network Services'
350 });
351 return _.cloneDeep(d);
352 } else {
353 itemDescriptor.model.uiState.modified = true;
354 this.addSnapshot(itemDescriptor.model);
355 return itemDescriptor.model;
356 }
357 }
358 return d;
359 });
360 }
361 return catalog;
362 });
363 this.setState({catalogs: catalogs, requiresSave: true})
364 }
365
366 deleteSelectedCatalogItem() {
367 SelectionManager.getSelections().forEach(selectedId => {
368 const item = this.getCatalogItemByUid(selectedId);
369 if (item) {
370 this.deleteCatalogItem(item);
371 }
372 });
373 SelectionManager.clearSelectionAndRemoveOutline();
374 }
375
376 deleteCatalogItem(item) {
377 const snapshot = JSON.stringify(item);
378 function confirmDeleteCancel(event) {
379 undo();
380 event.preventDefault();
381 ModalOverlayActions.hideModalOverlay();
382 }
383 const remove = () => {
384 // item is deleted or does not exist on server, so remove from ui
385 this.removeCatalogItem(item);
386 this.setState({catalogs: this.getCatalogs()});
387 const activeItem = ComposerAppStore.getState().item;
388 if (activeItem && activeItem.id === item.id) {
389 CatalogItemsActions.editCatalogItem.defer(null);
390 }
391 ModalOverlayActions.hideModalOverlay();
392 };
393 const undo = () => {
394 // item failed to delete on server so revert ui
395 const revertTo = JSON.parse(snapshot);
396 this.updateCatalogItem(revertTo);
397 const activeItem = ComposerAppStore.getState().item;
398 if (activeItem && activeItem.id === revertTo.id) {
399 SelectionManager.select(activeItem);
400 CatalogItemsActions.editCatalogItem.defer(revertTo);
401 SelectionManager.refreshOutline();
402 }
403 };
404 if (item) {
405 if (item.uiState.isNew) {
406 CatalogDataStore.confirmDelete(remove, confirmDeleteCancel);
407 } else {
408 if (item.uiState['instance-ref-count'] > 0) {
409 console.log('cannot delete NSD/VNFD with references to instantiated Network Services');
410 ComposerAppActions.showError.defer({
411 errorMessage: 'Cannot delete NSD/VNFD with references to instantiated Network Services'
412 });
413 undo();
414 } else {
415 const confirmDeleteOK = event => {
416 event.preventDefault();
417 item.uiState.deleted = true;
418 this.setState({catalogs: this.getCatalogs()});
419 ModalOverlayActions.showModalOverlay.defer();
420 this.getInstance().deleteCatalogItem(item.uiState.type, item.id)
421 .then(remove, undo)
422 .then(ModalOverlayActions.hideModalOverlay, ModalOverlayActions.hideModalOverlay)
423 .catch(function() {
424 console.log('overcoming ES6 unhandled rejection red herring');
425 });
426 };
427 CatalogDataStore.confirmDelete(confirmDeleteOK, confirmDeleteCancel);
428 }
429 }
430 }
431 }
432
433 static confirmDelete(onClickYes, onClickCancel) {
434 ModalOverlayActions.showModalOverlay.defer((
435 <div className="actions panel">
436 <div className="panel-header">
437 <h1>Delete the selected catalog item?</h1>
438 </div>
439 <div className="panel-body">
440 <a className="action confirm-yes primary-action Button" onClick={onClickYes}>Yes, delete selected catalog item</a>
441 <a className="action cancel secondary-action Button" onClick={onClickCancel}>No, cancel</a>
442 </div>
443 </div>
444 ));
445 }
446
447 createCatalogItem(type = 'nsd') {
448 const model = DescriptorModelMetaFactory.createModelInstanceForType(type);
449 if (model) {
450 const newItem = this.addNewItemToCatalog(model);
451 newItem.uiState.isNew = true;
452 newItem.uiState.modified = true;
453 newItem.uiState['instance-ref-count'] = 0;
454 // open the new model for editing in the canvas/details panels
455 setTimeout(() => {
456 this.selectCatalogItem(newItem);
457 CatalogItemsActions.editCatalogItem.defer(newItem);
458 }, 200);
459 }
460 }
461
462 duplicateSelectedCatalogItem() {
463 const item = this.getFirstSelectedCatalogItem();
464 if (item) {
465 const newItem = _.cloneDeep(item);
466 newItem.name = newItem.name + ' Copy';
467 const nsd = this.addNewItemToCatalog(newItem);
468 this.selectCatalogItem(nsd);
469 nsd.uiState.isNew = true;
470 nsd.uiState.modified = true;
471 nsd.uiState['instance-ref-count'] = 0;
472 // note duplicated items get a new id, map the layout position
473 // of the old id to the new id in order to preserve the layout
474 if (nsd.uiState.containerPositionMap) {
475 nsd.uiState.containerPositionMap[nsd.id] = nsd.uiState.containerPositionMap[item.id];
476 delete nsd.uiState.containerPositionMap[item.id];
477 }
478 setTimeout(() => {
479 this.selectCatalogItem(nsd);
480 CatalogItemsActions.editCatalogItem.defer(nsd);
481 }, 200);
482 }
483 }
484
485 addSnapshot(item) {
486 if (item) {
487 if (!this.snapshots[item.id]) {
488 this.snapshots[item.id] = [];
489 }
490 this.snapshots[item.id].push(JSON.stringify(item));
491 }
492 }
493
494 resetSnapshots(item) {
495 if (item) {
496 this.snapshots[item.id] = [];
497 this.addSnapshot(item);
498 }
499 }
500
501 editCatalogItem(item) {
502 if (item) {
503 this.addSnapshot(item);
504 // replace the given item in the catalog
505 const catalogs = this.getCatalogs().map(catalog => {
506 catalog.descriptors = catalog.descriptors.map(d => {
507 // note only one item can be "open" at a time
508 // so remove the flag from all the other items
509 d.uiState.isOpenForEdit = (d.id === item.id);
510 if (d.uiState.isOpenForEdit) {
511 return item;
512 }
513 return d;
514 });
515 return catalog;
516 });
517 this.setState({catalogs: catalogs});
518 this.catalogItemMetaDataChanged(item);
519 }
520 }
521
522 cancelCatalogItemChanges() {
523 const activeItem = ComposerAppStore.getState().item;
524 if (activeItem) {
525 const snapshots = this.snapshots[activeItem.id];
526 if (snapshots.length) {
527 const revertTo = JSON.parse(snapshots[0]);
528 this.updateCatalogItem(revertTo);
529 // TODO should the cancel action clear the undo/redo stack back to the beginning?
530 this.resetSnapshots(revertTo);
531 this.setState({requiresSave: false});
532 CatalogItemsActions.editCatalogItem.defer(revertTo);
533 }
534 }
535 }
536
537 saveCatalogItem() {
538 const activeItem = ComposerAppStore.getState().item;
539 if (activeItem) {
540 if (activeItem.uiState['instance-ref-count'] > 0) {
541 console.log('cannot save NSD/VNFD with references to instantiated Network Services');
542 ComposerAppActions.showError.defer({
543 errorMessage: 'Cannot save NSD/VNFD with references to instantiated Network Services'
544 });
545 return;
546 }
547 const success = () => {
548 delete activeItem.uiState.isNew;
549 delete activeItem.uiState.modified;
550 this.updateCatalogItem(activeItem);
551 // TODO should the save action clear the undo/redo stack back to the beginning?
552 this.resetSnapshots(activeItem);
553 ModalOverlayActions.hideModalOverlay.defer();
554 CatalogItemsActions.editCatalogItem.defer(activeItem);
555 };
556 const failure = () => {
557 ModalOverlayActions.hideModalOverlay.defer();
558 CatalogItemsActions.editCatalogItem.defer(activeItem);
559 };
560 const exception = () => {
561 console.warn('unable to save catalog item', activeItem);
562 ModalOverlayActions.hideModalOverlay.defer();
563 CatalogItemsActions.editCatalogItem.defer(activeItem);
564 };
565 ModalOverlayActions.showModalOverlay.defer();
566 this.getInstance().saveCatalogItem(activeItem).then(success, failure).catch(exception);
567 }
568 }
569
570 exportSelectedCatalogItems(draggedItem) {
571 const onSelectFormat = (selectedFormat, event) => {
572 this.setState({
573 selectedFormat: selectedFormat
574 });
575 };
576
577 const onSelectGrammar = (selectedGrammar, event) => {
578 this.setState({
579 selectedGrammar: selectedGrammar
580 });
581 }
582
583
584 const onCancel = () => {
585 this.resetSelectionState();
586 ModalOverlayActions.hideModalOverlay();
587 };
588
589 const onDownload = (event) => {
590 CatalogPackageManagerActions.downloadCatalogPackage.defer({
591 selectedItems: selectedItems,
592 selectedFormat: this.selectedFormat,
593 selectedGrammar: this.selectedGrammar
594 });
595 this.resetSelectionState();
596 ModalOverlayActions.hideModalOverlay();
597 return;
598 }
599
600 if (draggedItem) {
601 // if item is given make sure it is also selected
602 //draggedItem.uiState.selected = true;
603 SelectionManager.addSelection(draggedItem);
604 this.updateCatalogItem(draggedItem);
605 }
606 // collect the selected items and delegate to the catalog package manager action creator
607 const selectedItems = this.getAllSelectedCatalogItems();
608 if (selectedItems.length) {
609 CatalogDataStore.chooseExportFormat(onSelectFormat, onSelectGrammar, onDownload, onCancel);
610 }
611 }
612
613 static chooseExportFormat(onSelectFormat, onSelectGrammar, onDownload, onCancel) {
614 ModalOverlayActions.showModalOverlay.defer(
615 <ExportSelectorDialog
616 onSelectFormat={onSelectFormat}
617 onSelectGrammar={onSelectGrammar}
618 onCancel={onCancel}
619 onDownload={onDownload}
620 currentlySelectedFormat='mano'
621 currentlySelectedGrammar='osm'
622 />
623 );
624 }
625
626 }
627
628 export default alt.createStore(CatalogDataStore, 'CatalogDataStore');