originalName fallbacks to customizationId or invariantId
[vid.git] / vid-webpack-master / src / app / drawingBoard / service-planning / objectsToTree / shared.tree.service.ts
1 import {Injectable} from "@angular/core";
2 import {NgRedux} from "@angular-redux/store";
3 import {AppState} from "../../../shared/store/reducers";
4 import {ServiceInstanceActions} from "../../../shared/models/serviceInstanceActions";
5 import {MessageBoxData} from "../../../shared/components/messageBox/messageBox.data";
6 import {MessageBoxService} from "../../../shared/components/messageBox/messageBox.service";
7 import * as _ from "lodash";
8 import {DrawingBoardModes} from "../drawing-board.modes";
9 import {AuditInfoModalComponent} from "../../../shared/components/auditInfoModal/auditInfoModal.component";
10 import {ILevelNodeInfo} from "./models/basic.model.info";
11 import {ComponentInfoModel, ComponentInfoType} from "../component-info/component-info-model";
12 import {ModelInformationItem} from "../../../shared/components/model-information/model-information.component";
13 import {undoUpgradeService, upgradeService} from "../../../shared/storeUtil/utils/service/service.actions";
14 import {VNFMethods} from "../../../shared/storeUtil/utils/vnf/vnf.actions";
15 import {FeatureFlagsService, Features} from "../../../shared/services/featureFlag/feature-flags.service";
16 import {Utils} from "../../../shared/utils/utils";
17 import {Constants} from "../../../shared/utils/constants";
18 import {NodeInstance} from "../../../shared/models/nodeInstance";
19
20 @Injectable()
21 export class SharedTreeService {
22   private _sharedTreeService: SharedTreeService;
23   constructor(private _store: NgRedux<AppState>) {
24   }
25
26   /***********************************************************
27    * return if instance has missing data
28    * @param instance - vnf instance
29    * @param dynamicInputs - from the instance
30    * @param isEcompGeneratedNaming
31    ************************************************************/
32   selectedVNF: string = null;
33
34
35   getSelectedVNF(): string {
36     return this.selectedVNF;
37   }
38
39   setSelectedVNF(node): void {
40     if (_.isNil(node) || node.data.type !== 'VF') {
41       this.selectedVNF = null;
42     } else {
43       this.selectedVNF = node.data.vnfStoreKey;
44     }
45   }
46
47   /**
48    * Determines a consistent unique ID for a given right-tree
49    * node instance.
50    */
51   modelUniqueId = (nodeInstance: NodeInstance): string => {
52     return _.isNil(nodeInstance.modelInfo)
53       ? null
54       : (nodeInstance.modelInfo.modelCustomizationId || nodeInstance.modelInfo.modelInvariantId);
55   };
56
57   modelUniqueNameOrId = (instance): string =>
58     instance.originalName ? instance.originalName : this.modelUniqueId(instance);
59
60   /**
61    * Finds a model inside a full service model
62    * @param serviceModelFromHierarchy
63    * @param modelTypeName "vnfs" | "networks" | "vfModules" | "collectionResources" | ...
64    * @param modelUniqueNameOrId Either an entry name (i.e. "originalName"), modelCustomizationId or modelInvariantId.
65    *                      Note that modelInvariantId will work only where model lacks a modelCustomizationId.
66    * @param modeName An optional entry name (i.e. "originalName"); will not try to use as id
67    */
68   modelByIdentifiers = (serviceModelFromHierarchy, modelTypeName: string, modelUniqueNameOrId: string, modeName?: string): any => {
69     const logErrorAndReturnUndefined = () =>
70       console.info(`modelByIdentifiers: could not find a model matching query`, {
71         modelTypeName, modelUniqueNameOrId, modeName, serviceModelFromHierarchy
72       });
73
74     if (_.isNil(serviceModelFromHierarchy)) return logErrorAndReturnUndefined();
75
76     const modelsOfType = serviceModelFromHierarchy[modelTypeName];
77     if (_.isNil(modelsOfType)) return logErrorAndReturnUndefined();
78
79     const modelIfModelIdentifierIsEntryName = modelsOfType[modelUniqueNameOrId];
80     const modelIfModeNameExists = _.isNil(modeName) ? null : modelsOfType[modeName];
81
82     if (!_.isNil(modelIfModelIdentifierIsEntryName)) {
83       return modelIfModelIdentifierIsEntryName;
84     } else if (!_.isNil(modelIfModeNameExists)) {
85       return modelIfModeNameExists;
86     } else {
87       // try modelUniqueNameOrId as an id
88       return _.find(modelsOfType, o => (o.customizationUuid || o.invariantUuid) === modelUniqueNameOrId) || logErrorAndReturnUndefined()
89     }
90   };
91
92   hasMissingData(instance, dynamicInputs: any, isEcompGeneratedNaming: boolean, requiredFields: string[]): boolean {
93     if (!isEcompGeneratedNaming && _.isEmpty(instance.instanceName)) {
94       return true;
95     }
96
97     for (let field of requiredFields) {
98       if (_.isEmpty(instance[field])) {
99         return true;
100       }
101     }
102
103     for (let field of dynamicInputs) {
104       if (field.isRequired && !_.isNil(instance.instanceParams) && _.isEmpty(instance.instanceParams[0][field.id])) {
105         return true;
106       }
107     }
108     return false;
109   }
110
111
112   addingStatusProperty(node) {
113     node['statusProperties'] = [];
114     node['statusProperties'].push({key: 'Prov Status:', value: node.provStatus, testId: 'provStatus'});
115     node['statusProperties'].push({key: 'Orch Status:', value: node.orchStatus, testId: 'orchStatus'});
116     if (node.inMaint) {
117       node['statusProperties'].push({key: 'In-maintenance', value: '', testId: 'inMaint'});
118     }
119     return node;
120   }
121
122   /**********************************************
123    * should delete or remove child instance's
124    "new" -> should remove
125    !new" -> should change action status
126    **********************************************/
127   removeDeleteAllChild(node, serviceModelId: string, callback): void {
128     for (let nodeChild of node.children) {
129       if (nodeChild.data.action === ServiceInstanceActions.Create) {
130         if (!_.isNil(nodeChild.data) && !_.isNil(nodeChild.data.menuActions) && !_.isNil(nodeChild.data.menuActions['remove'])) {
131           nodeChild.data.menuActions['remove']['method'](nodeChild, serviceModelId);
132         }
133       } else {
134         if (!_.isNil(nodeChild.data) && !_.isNil(nodeChild.data.menuActions) && !_.isNil(nodeChild.data.menuActions['delete'])) {
135           nodeChild.data.menuActions['delete']['method'](nodeChild, serviceModelId);
136         }
137       }
138     }
139     callback(node, serviceModelId);
140   }
141
142
143   /**********************************************
144    * should undo delete child instance's
145    **********************************************/
146   undoDeleteAllChild(node, serviceModelId: string, callback): void {
147     for (let nodeChild of node.children) {
148       if (!_.isNil(nodeChild.data) && !_.isNil(nodeChild.data.menuActions) && !_.isNil(nodeChild.data.menuActions['undoDelete'])) {
149         nodeChild.data.menuActions['undoDelete']['method'](nodeChild, serviceModelId);
150       }
151     }
152     callback(node, serviceModelId);
153   }
154
155   /**********************************************
156    * should return true if can delete
157    **********************************************/
158   shouldShowDelete(node, serviceModelId): boolean {
159     return this.shouldShowButtonGeneric(node, "delete", serviceModelId)
160   }
161
162   /**********************************************
163    * should return true if can undo delete
164    **********************************************/
165   shouldShowUndoDelete(node): boolean {
166     const mode = this._store.getState().global.drawingBoardStatus;
167     if (mode === DrawingBoardModes.EDIT && !_.isNil(node.data.action) && !_.isNil(node.data.menuActions['undoDelete'])) {
168       if (node.data.action === ServiceInstanceActions.Create || node.data.action === ServiceInstanceActions.Delete) {
169         return false;
170       } else if (node.data.action.split('_').pop() === 'Delete') {
171         return true
172       }
173       return false;
174     }
175     return false;
176   }
177   /**********************************************
178    * should return true if can remove or edit
179    * enabled only on edit/design mode and for new instances
180    **********************************************/
181   shouldShowRemoveAndEdit(node): boolean {
182     const mode = this._store.getState().global.drawingBoardStatus;
183     if (!_.isNil(node) && !_.isNil(node.data) && !_.isNil(node.data.action) && node.data.action === ServiceInstanceActions.Create &&
184       mode !== DrawingBoardModes.VIEW && mode !== DrawingBoardModes.RETRY) {
185       return true;
186     }
187     return false;
188   }
189   /**********************************************
190    * enabled only on edit/design
191    * enabled only if there's a newer version for VNF-M
192    **********************************************/
193   upgradeBottomUp(node,serviceModelId: string): void {
194     this.iterateOverTreeBranchAndRunAction(node, serviceModelId, VNFMethods.UPGRADE);
195     this._store.dispatch(upgradeService(serviceModelId));
196   }
197
198   private iterateOverTreeBranchAndRunAction(node, serviceModelId: string, actionMethod) {
199     while (_.has(node.parent, 'data') && _.has(node.parent.data, 'menuActions')
200     && !_.isNil(node.parent.data.menuActions[actionMethod])) {
201       node = node.parent;
202       node.data.menuActions[actionMethod]['method'](node, serviceModelId);
203     }
204   }
205
206   /****************************************************
207    * should return true if customer can upgrade a VFM *
208    ****************************************************/
209   shouldShowUpgrade(node, serviceModelId): boolean {
210     if (FeatureFlagsService.getFlagState(Features.FLAG_FLASH_REPLACE_VF_MODULE, this._store) &&
211       this.isThereAnUpdatedLatestVersion(serviceModelId)) {
212       return this.shouldShowButtonGeneric(node, VNFMethods.UPGRADE, serviceModelId);
213     }
214     else {
215       return false
216     }
217   }
218
219   private isThereAnUpdatedLatestVersion(serviceModelId) : boolean{
220     let serviceInstance = this.getServiceInstance(serviceModelId);
221     return !_.isNil(serviceInstance.latestAvailableVersion) && (Number(serviceInstance.modelInfo.modelVersion) < serviceInstance.latestAvailableVersion);
222   }
223
224   private getServiceInstance(serviceModelId): any {
225     return this._store.getState().service.serviceInstance[serviceModelId];
226   }
227
228   shouldShowButtonGeneric(node, method, serviceModelId) {
229     const mode = this._store.getState().global.drawingBoardStatus;
230     const isMacro = !(this.getServiceInstance(serviceModelId).isALaCarte);
231
232     if (isMacro) { //if macro action allowed only for service level
233       return false;
234     }
235
236     if (!_.isNil(node) && !_.isNil(node.data) && !_.isNil(node.data.action) && !_.isNil(node.data.menuActions[method])) {
237       if (mode !== DrawingBoardModes.EDIT || node.data.action === ServiceInstanceActions.Create) {
238         return false;
239       }
240       else if (node.data.action === ServiceInstanceActions.None) {
241         return true
242       }
243     }
244     return false;
245   }
246
247   /**********************************************
248    * return boolean according to
249    * current defined action of VFModule node
250    **********************************************/
251   shouldShowUndoUpgrade(node): boolean {
252     const mode = this._store.getState().global.drawingBoardStatus;
253     if (mode === DrawingBoardModes.EDIT && !_.isNil(node.data.action) && !_.isNil(node.data.menuActions[VNFMethods.UNDO_UPGRADE])) {
254       if (node.data.action === ServiceInstanceActions.Upgrade) {
255         return false;
256       } else if (node.data.action.split('_').pop() === ServiceInstanceActions.Upgrade) {
257         return true
258       }
259       return false;
260     }
261     return false;
262   }
263   /**********************************************
264    * enabled only on edit/design
265    * enabled only if there's a newer version for VNF-M
266    **********************************************/
267   undoUpgradeBottomUp(node,serviceModelId: string): void {
268     this.iterateOverTreeBranchAndRunAction(node, serviceModelId, VNFMethods.UNDO_UPGRADE);
269     this._store.dispatch(undoUpgradeService(serviceModelId));
270   }
271   /**********************************************
272    * should return true if can duplicate by mode
273    **********************************************/
274   shouldShowDuplicate(node): boolean {
275     const mode = this._store.getState().global.drawingBoardStatus;
276     return !mode.includes('RETRY');
277   }
278
279   /**********************************************
280    * should return true if can audit info
281    **********************************************/
282   shouldShowAuditInfo(node): boolean {
283     return this.isRetryMode() || (!_.isNil(node.data) && !_.isNil(node.data.action) && node.data.action !== ServiceInstanceActions.Create);
284   }
285
286
287   isRetryMode(): boolean {
288     const mode = this._store.getState().global.drawingBoardStatus;
289     return mode.includes('RETRY');
290   }
291
292
293   /**********************************************
294    * should return true if can add node instances
295    **********************************************/
296   shouldShowAddIcon(): boolean{
297     const mode = this._store.getState().global.drawingBoardStatus;
298     return mode === DrawingBoardModes.EDIT || mode=== DrawingBoardModes.CREATE || mode=== DrawingBoardModes.RECREATE;
299   }
300
301
302   isReachedToMaxInstances(properties, counter, flags): boolean{
303     let maxInstances  = Utils.getMaxFirstLevel(properties, flags);
304     if(_.isNil(maxInstances)){
305       return false;
306     }else {
307       return !(maxInstances > counter);
308     }
309   }
310   /************************************************
311    return number of instances with action Delete
312    @type: vnfs networks, vngGroups (not vfModule)
313    @node : node model from the left tree
314    ************************************************/
315   getExistingInstancesWithDeleteMode(node, serviceModelId: string, type: string): number {
316     let counter = 0;
317     const existingInstances = this.getServiceInstance(serviceModelId)[type];
318     const modelUniqueId = node.data.modelUniqueId;
319     if (!_.isNil(existingInstances)) {
320       for (let instanceKey in existingInstances) {
321         if (!_.isNil(existingInstances[instanceKey].action)) {
322           if (existingInstances[instanceKey].modelInfo.modelUniqueId === modelUniqueId && existingInstances[instanceKey].action.split('_').pop() === 'Delete') {
323             counter++;
324           }
325         }
326       }
327     }
328     return counter;
329   }
330
331
332   isServiceOnDeleteMode(serviceId: string): boolean {
333     return this._store.getState().service.serviceInstance[serviceId].action === ServiceInstanceActions.Delete;
334   }
335
336
337   openModal(node : any | any[] , serviceModelId : string, cb : Function) : void {
338     let type: string = _.isArray(node) ? 'Service' : node.data.typeName;
339     let messageBoxData: MessageBoxData = new MessageBoxData(
340       "Mark for Delete",
341       `You are about to mark for delete this ${type} this will also mark all its children and remove all new instances just added`,
342       <any>"warning",
343       <any>"md",
344       [
345         {
346           text: "Mark and remove",
347           size: "large",
348           callback: cb.bind(this, node, serviceModelId),
349           closeModal: true
350         },
351         {text: "Don’t Remove", size: "medium", closeModal: true}
352       ]);
353
354     MessageBoxService.openModal.next(messageBoxData);
355   }
356
357   someChildHasCreateAction(nodes: any | any[]) : boolean {
358     let nodesArr = _.isArray(nodes) ? nodes : [nodes];
359     for(const node of nodesArr){
360       if(node.action === ServiceInstanceActions.Create) {return true;}
361       if(node.children){
362         for (let nodeChild of node.children) {
363           if (nodeChild.action === ServiceInstanceActions.Create) {
364             return true;
365           }
366           if(nodeChild.children && nodeChild.children.length > 0){
367             for(let child of nodeChild.children){
368               let hasCreateAction = this.someChildHasCreateAction(child);
369               if(hasCreateAction) {
370                 return true;
371               }
372             }
373           }
374         }
375       }
376     }
377     return false;
378   }
379
380   shouldShowDeleteInstanceWithChildrenModal(node : any | any[] , serviceModelId : string, cb : Function) : void {
381     if(this.someChildHasCreateAction(node)){
382       this.openModal(node , serviceModelId, cb);
383     }else {
384       cb(node, serviceModelId)
385     }
386   }
387
388
389   isFailed(node): boolean {
390     return !_.isNil(node.data) ? node.data.isFailed : false;
391   }
392
393   /************************************************
394    in a case the node is failed e.g. not instantiated correctly
395    the function will call to openRetryInstanceAuditInfoModal
396    @node : node model from the left tree
397    @serviceModelId : serviceModelId
398    @instance : instance
399    @instanceType: instanceType
400    @modelInfoService : the model (vnf, vfmodule, network, vnfgroup)object that call to the function (this)
401    ************************************************/
402   openAuditInfoModal(node, serviceModelId, instance, instanceType, modelInfoService : ILevelNodeInfo){
403     AuditInfoModalComponent.openInstanceAuditInfoModal.next({
404       instanceId: serviceModelId,
405       type: instanceType,
406       model: modelInfoService.getModel(node.data.modelName, instance, this._store.getState().service.serviceHierarchy[serviceModelId]),
407       instance
408     });
409   }
410
411
412   addGeneralInfoItems(modelInfoSpecificItems: ModelInformationItem[], type: ComponentInfoType, model, instance):ComponentInfoModel {
413     let modelInfoItems: ModelInformationItem[] = [
414       ModelInformationItem.createInstance("Model version", model ? model.version : null),
415       ModelInformationItem.createInstance("Model customization ID", model ? model.customizationUuid : null),
416       ModelInformationItem.createInstance("Instance ID", instance ? instance.instanceId : null),
417       ModelInformationItem.createInstance("Instance type", instance ? instance.instanceType : null),
418       ModelInformationItem.createInstance("In maintenance", instance? instance.inMaint : null),
419     ];
420     modelInfoItems = modelInfoItems.concat(modelInfoSpecificItems);
421     return this.getComponentInfoModelByModelInformationItems(modelInfoItems, type, instance);
422   }
423
424   getComponentInfoModelByModelInformationItems(modelInfoItems: ModelInformationItem[], type: ComponentInfoType, instance){
425     const modelInfoItemsWithoutEmpty = _.filter(modelInfoItems, function(item){ return !item.values.every(_.isNil)});
426     return new ComponentInfoModel(type, modelInfoItemsWithoutEmpty, [], instance != null);
427   }
428
429   createMaximumToInstantiateModelInformationItem(model): ModelInformationItem {
430     return ModelInformationItem.createInstance(
431       "Max instances",
432       !_.isNil(model.max) ? String(model.max) : Constants.ModelInfo.UNLIMITED_DEFAULT
433     );
434   }
435 }