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