be92f76200abbc4b7018d1c838dc691d49434310
[sdc.git] / catalog-ui / src / app / models / components / component.ts
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 'use strict';
22
23 import * as _ from "lodash";
24 import {AsdcComment, ArtifactModel, ArtifactGroupModel, IFileDownload, PropertyModel, PropertiesGroup, AttributeModel, AttributesGroup, ComponentInstance,
25     InputModel, DisplayModule, Module, IValidate, RelationshipModel, IMainCategory, RequirementsGroup, CapabilitiesGroup, AdditionalInformationModel,
26     Resource, IAppMenu, OperationModel, Service} from "../../models";
27
28 import {IComponentService} from "../../services/components/component-service";
29 import {CommonUtils} from "../../utils/common-utils";
30 import {QueueUtils} from "../../utils/functions";
31 import {ArtifactGroupType} from "../../utils/constants";
32 import {ComponentMetadata} from "../component-metadata";
33 import {Capability} from "../capability";
34 import {Requirement} from "../requirement";
35 import {Relationship} from "../graph/relationship";
36 import { PolicyInstance } from "app/models/graph/zones/policy-instance";
37 import { GroupInstance } from "../graph/zones/group-instance";
38 import { Metadata } from "app/models/metadata";
39
40
41 // import {}
42 export interface IComponent {
43
44     //---------------------------------------------- API CALLS ----------------------------------------------------//
45
46     //Component API
47     getComponent():ng.IPromise<Component>;
48     updateComponent():ng.IPromise<Component>;
49     createComponentOnServer():ng.IPromise<Component>;
50     changeLifecycleState(state:string, commentObj:AsdcComment):ng.IPromise<Component>;
51     validateName(newName:string):ng.IPromise<IValidate>;
52
53     //Artifacts API
54     addOrUpdateArtifact(artifact:ArtifactModel):ng.IPromise<ArtifactModel>;
55     deleteArtifact(artifactId:string, artifactLabel:string):ng.IPromise<ArtifactModel>;
56     downloadInstanceArtifact(artifactId:string):ng.IPromise<IFileDownload>;
57     downloadArtifact(artifactId:string):ng.IPromise<IFileDownload>;
58
59     //Property API
60     addOrUpdateProperty(property:PropertyModel):ng.IPromise<PropertyModel>;
61     deleteProperty(propertyId:string):ng.IPromise<PropertyModel>;
62
63     //Attribute API
64     deleteAttribute(attributeId:string):ng.IPromise<AttributeModel>;
65     addOrUpdateAttribute(attribute:AttributeModel):ng.IPromise<AttributeModel>;
66
67     //Modules
68     getModuleForDisplay(moduleId:string):ng.IPromise<DisplayModule>;
69     getModuleInstanceForDisplay(componentInstanceId:string, moduleId:string):ng.IPromise<DisplayModule>;
70     updateGroupMetadata(group:Module):ng.IPromise<Module>;
71
72     //---------------------------------------------- HELP FUNCTIONS ----------------------------------------------------//
73
74     getComponentSubType():string;
75     isAlreadyCertified():boolean;
76     isService():boolean;
77     isResource():boolean;
78     isComplex():boolean;
79     getAllVersionsAsSortedArray():Array<any>;
80     getStatus(sdcMenu:IAppMenu):string;
81 }
82
83
84 export abstract class Component implements IComponent {
85
86     //server data
87     public abstract:string;
88     public uniqueId:string;
89     public uuid:string;
90     public invariantUUID:string;
91     public name:string;
92     public version:string;
93     public creationDate:number;
94     public lastUpdateDate:number;
95     public description:string;
96     public lifecycleState:string;
97     public tags:Array<string>;
98     public icon:string;
99     public contactId:string;
100     public allVersions:any;
101     public creatorUserId:string;
102     public creatorFullName:string;
103     public lastUpdaterUserId:string;
104     public lastUpdaterFullName:string;
105     public componentType:string;
106     public deploymentArtifacts:ArtifactGroupModel;
107     public artifacts:ArtifactGroupModel;
108     public toscaArtifacts:ArtifactGroupModel;
109     public interfaceOperations:Array<OperationModel>;
110     public distributionStatus:string;
111     public categories:Array<IMainCategory>;
112     public categoryNormalizedName: string;
113     public subCategoryNormalizedName: string;
114     public componentInstancesProperties:PropertiesGroup;
115     public componentInstancesAttributes:AttributesGroup;
116     public componentInstancesRelations:Array<RelationshipModel>;
117     public componentInstances:Array<ComponentInstance>;
118     public inputs:Array<InputModel>;
119     public capabilities:CapabilitiesGroup;
120     public requirements:RequirementsGroup;
121     public additionalInformation:any;
122     public properties:Array<PropertyModel>;
123     public attributes:Array<AttributeModel>;
124     public highestVersion:boolean;
125     public vendorName:string;
126     public vendorRelease:string;
127     public derivedList:Array<any>;
128     public interfaces:any;
129     public normalizedName:string;
130     public systemName:string;
131     public policies:Array<PolicyInstance>;
132     public groupInstances:Array<GroupInstance>
133     public modules:Array<Module>;
134     //custom properties
135     public componentService:IComponentService;
136     public filterTerm:string;
137     public iconSprite:string;
138     public selectedInstance:ComponentInstance;
139     public mainCategory:string;
140     public subCategory:string;
141     public selectedCategory:string;
142     public showMenu:boolean;
143     public archived:boolean;
144     public vspArchived: boolean;
145     public componentMetadata: ComponentMetadata;
146     public categorySpecificMetadata: Metadata = new Metadata();
147     public derivedFromGenericType: string;
148     public derivedFromGenericVersion: string;
149
150     constructor(componentService:IComponentService, protected $q:ng.IQService, component?:Component) {
151         if (component) {
152             this.abstract = component.abstract;
153             this.uniqueId = component.uniqueId;
154             this.uuid = component.uuid;
155             this.invariantUUID = component.invariantUUID;
156             this.additionalInformation = component.additionalInformation;
157             this.artifacts = new ArtifactGroupModel(component.artifacts);
158             this.toscaArtifacts = new ArtifactGroupModel(component.toscaArtifacts);
159             this.interfaceOperations = component.interfaceOperations;
160             this.contactId = component.contactId;
161             this.categories = component.categories;
162             this.categoryNormalizedName = component.categoryNormalizedName;
163             this.subCategoryNormalizedName = component.subCategoryNormalizedName;
164             this.creatorUserId = component.creatorUserId;
165             this.creationDate = component.creationDate;
166             this.creatorFullName = component.creatorFullName;
167             this.description = component.description;
168             this.icon = component.icon;
169             this.lastUpdateDate = component.lastUpdateDate;
170             this.lastUpdaterUserId = component.lastUpdaterUserId;
171             this.lastUpdaterFullName = component.lastUpdaterFullName;
172             this.lifecycleState = component.lifecycleState;
173             this.componentInstancesRelations = CommonUtils.initComponentInstanceRelations(component.componentInstancesRelations);
174             this.componentInstancesProperties = new PropertiesGroup(component.componentInstancesProperties);
175             this.componentInstancesAttributes = new AttributesGroup(component.componentInstancesAttributes);
176             this.name = component.name;
177             this.version = component.version;
178             this.tags = [];
179             angular.copy(component.tags, this.tags);
180             this.capabilities = new CapabilitiesGroup(component.capabilities);
181             this.requirements = new RequirementsGroup(component.requirements);
182             this.allVersions = component.allVersions;
183             this.deploymentArtifacts = new ArtifactGroupModel(component.deploymentArtifacts);
184             this.componentType = component.componentType;
185             this.distributionStatus = component.distributionStatus;
186             this.highestVersion = component.highestVersion;
187             this.vendorName = component.vendorName;
188             this.vendorRelease = component.vendorRelease;
189             this.derivedList = component.derivedList;
190             this.interfaces = component.interfaces;
191             this.normalizedName = component.normalizedName;
192             this.systemName = component.systemName;
193             this.inputs = component.inputs;
194             this.componentInstances = CommonUtils.initComponentInstances(component.componentInstances);
195             this.properties = CommonUtils.initProperties(component.properties, this.uniqueId);
196             this.attributes = CommonUtils.initAttributes(component.attributes, this.uniqueId);
197             this.selectedInstance = component.selectedInstance;
198             this.iconSprite = component.iconSprite;
199             this.showMenu = true;
200             this.modules = component.modules;
201             this.groupInstances = component.groupInstances;
202             this.policies = component.policies;
203             this.archived = component.archived;
204             this.vspArchived = component.vspArchived;
205
206             if (component.categorySpecificMetadata && component.categories && component.categories[0]){
207                 this.copyCategoryMetadata(component);
208                 this.copySubcategoryMetadata(component);
209             }
210
211             this.derivedFromGenericType = component.derivedFromGenericType;
212             this.derivedFromGenericVersion = component.derivedFromGenericVersion;
213         }
214
215         //custom properties
216         this.componentService = componentService;
217     }
218
219     private copyCategoryMetadata = (component:Component):void => {
220         if (component.categories[0].metadataKeys){
221             for (let key of Object.keys(component.categorySpecificMetadata)) {
222                 if (component.categories[0].metadataKeys.some(metadataKey => metadataKey.name == key)) {
223                     this.categorySpecificMetadata[key] = component.categorySpecificMetadata[key];
224                 }
225             }
226         }
227     }
228     private copySubcategoryMetadata = (component:Component):void => {
229         if (component.categories[0].subcategories && component.categories[0].subcategories[0] && component.categories[0].subcategories[0].metadataKeys){
230             for (let key of Object.keys(component.categorySpecificMetadata)) {
231                 if (component.categories[0].subcategories[0].metadataKeys.some(metadataKey => metadataKey.name == key)) {
232                     this.categorySpecificMetadata[key] = component.categorySpecificMetadata[key];
233                 }
234             }
235         }
236     }
237
238     public setUniqueId = (uniqueId:string):void => {
239         this.uniqueId = uniqueId;
240     };
241
242     //------------------------------------------ API Calls ----------------------------------------------------------------//
243     public changeLifecycleState = (state:string, commentObj:AsdcComment):ng.IPromise<Component> => {
244         let deferred = this.$q.defer<Component>();
245         let onSuccess = (componentMetadata:ComponentMetadata):void => {
246             this.setComponentMetadata(componentMetadata);
247             // this.version = componentMetadata.version;
248             this.lifecycleState = componentMetadata.lifecycleState;
249
250             deferred.resolve(this);
251         };
252         let onError = (error:any):void => {
253             deferred.reject(error);
254         };
255         this.componentService.changeLifecycleState(this, state, commentObj).then(onSuccess, onError);
256         return deferred.promise;
257     };
258
259     public getComponent = ():ng.IPromise<Component> => {
260         return this.componentService.getComponent(this.uniqueId);
261     };
262
263     public createComponentOnServer = ():ng.IPromise<Component> => {
264         this.handleTags();
265         return this.componentService.createComponent(this);
266     };
267     
268     public importComponentOnServer = (): ng.IPromise<Component> => {
269         this.handleTags();
270         return this.componentService.importComponent(this);
271     };
272
273     public updateComponent = ():ng.IPromise<Component> => {
274         this.handleTags();
275         return this.componentService.updateComponent(this);
276     };
277
278     public validateName = (newName:string, subtype?:string):ng.IPromise<IValidate> => {
279         return this.componentService.validateName(newName, subtype);
280     };
281
282     public downloadArtifact = (artifactId: string): ng.IPromise<IFileDownload> => {
283         if(this.vendorName === 'IsService'){
284             return this.componentService.downloadArtifact(this.uniqueId, artifactId, this.vendorName);
285         }else{
286             return this.componentService.downloadArtifact(this.uniqueId, artifactId);
287         }
288     };
289
290     public addOrUpdateArtifact = (artifact:ArtifactModel):ng.IPromise<ArtifactModel> => {
291         let deferred = this.$q.defer<ArtifactModel>();
292         let onSuccess = (artifactObj:ArtifactModel):void => {
293             let newArtifact = new ArtifactModel(artifactObj);
294             let artifacts = this.getArtifactsByType(artifactObj.artifactGroupType);
295             artifacts[artifactObj.artifactLabel] = newArtifact;
296             deferred.resolve(newArtifact);
297         };
298         let onError = (error:any):void => {
299             deferred.reject(error);
300         };
301         this.componentService.addOrUpdateArtifact(this.uniqueId, artifact).then(onSuccess, onError);
302         return deferred.promise;
303     };
304
305     public deleteArtifact = (artifactId:string, artifactLabel:string):ng.IPromise<ArtifactModel> => {
306         let deferred = this.$q.defer<ArtifactModel>();
307         let onSuccess = (artifactObj:ArtifactModel):void => {
308             let newArtifact = new ArtifactModel(artifactObj);
309             let artifacts = this.getArtifactsByType(artifactObj.artifactGroupType);
310             if (newArtifact.mandatory || newArtifact.serviceApi) {
311                 artifacts[newArtifact.artifactLabel] = newArtifact;
312             }
313             else {
314                 delete artifacts[artifactLabel];
315             }
316             deferred.resolve(newArtifact);
317         };
318         this.componentService.deleteArtifact(this.uniqueId, artifactId, artifactLabel).then(onSuccess);
319         return deferred.promise;
320     };
321
322     public addOrUpdateProperty = (property:PropertyModel):ng.IPromise<PropertyModel> => {
323         let deferred = this.$q.defer<PropertyModel>();
324
325         let onError = (error:any):void => {
326             deferred.reject(error);
327         };
328
329         if (!property.uniqueId) {
330             let onSuccess = (property:PropertyModel):void => {
331                 let newProperty = new PropertyModel(property);
332                 this.properties.push(newProperty);
333                 deferred.resolve(newProperty);
334             };
335             this.componentService.addProperty(this.uniqueId, property).then(onSuccess, onError);
336         }
337         else {
338             let onSuccess = (newProperty:PropertyModel):void => {
339                 // find exist instance property in parent component for update the new value ( find bu uniqueId )
340                 let existProperty:PropertyModel = <PropertyModel>_.find(this.properties, {uniqueId: newProperty.uniqueId});
341                 let propertyIndex = this.properties.indexOf(existProperty);
342                 this.properties[propertyIndex] = newProperty;
343                 deferred.resolve(newProperty);
344             };
345             this.componentService.updateProperty(this.uniqueId, property).then(onSuccess, onError);
346         }
347         return deferred.promise;
348     };
349
350     public addOrUpdateAttribute = (attribute:AttributeModel):ng.IPromise<AttributeModel> => {
351         let deferred = this.$q.defer<AttributeModel>();
352
353         let onError = (error:any):void => {
354             deferred.reject(error);
355         };
356
357         if (!attribute.uniqueId) {
358             let onSuccess = (attribute:AttributeModel):void => {
359                 let newAttribute = new AttributeModel(attribute);
360                 this.attributes.push(newAttribute);
361                 deferred.resolve(newAttribute);
362             };
363             this.componentService.addAttribute(this.uniqueId, attribute).then(onSuccess, onError);
364         }
365         else {
366             let onSuccess = (newAttribute:AttributeModel):void => {
367                 let existAttribute:AttributeModel = <AttributeModel>_.find(this.attributes, {uniqueId: newAttribute.uniqueId});
368                 let attributeIndex = this.attributes.indexOf(existAttribute);
369                 newAttribute.readonly = this.uniqueId != newAttribute.parentUniqueId;
370                 this.attributes[attributeIndex] = newAttribute;
371                 deferred.resolve(newAttribute);
372             };
373             this.componentService.updateAttribute(this.uniqueId, attribute).then(onSuccess, onError);
374         }
375         return deferred.promise;
376     };
377
378     public deleteProperty = (propertyId:string):ng.IPromise<PropertyModel> => {
379         let deferred = this.$q.defer<PropertyModel>();
380         let onSuccess = ():void => {
381             console.log("Property deleted");
382             delete _.remove(this.properties, {uniqueId: propertyId})[0];
383             deferred.resolve();
384         };
385         let onFailed = ():void => {
386             console.log("Failed to delete property");
387             deferred.reject();
388         };
389         this.componentService.deleteProperty(this.uniqueId, propertyId).then(onSuccess, onFailed);
390         return deferred.promise;
391     };
392
393     public deleteAttribute = (attributeId:string):ng.IPromise<AttributeModel> => {
394         let deferred = this.$q.defer<AttributeModel>();
395         let onSuccess = ():void => {
396             console.log("Attribute deleted");
397             delete _.remove(this.attributes, {uniqueId: attributeId})[0];
398         };
399         let onFailed = ():void => {
400             console.log("Failed to delete attribute");
401         };
402         this.componentService.deleteAttribute(this.uniqueId, attributeId).then(onSuccess, onFailed);
403         return deferred.promise;
404     };
405
406     public downloadInstanceArtifact = (artifactId:string):ng.IPromise<IFileDownload> => {
407         return this.componentService.downloadInstanceArtifact(this.uniqueId, this.selectedInstance.uniqueId, artifactId);
408     };
409
410     public getModuleForDisplay = (moduleId:string):ng.IPromise<DisplayModule> => {
411
412         let deferred = this.$q.defer<DisplayModule>();
413         let onSuccess = (response:DisplayModule):void => {
414             deferred.resolve(response);
415         };
416         let onFailed = (error:any):void => {
417             deferred.reject(error);
418         };
419         this.componentService.getModuleForDisplay(this.uniqueId, moduleId).then(onSuccess, onFailed);
420         return deferred.promise;
421     };
422
423     public getModuleInstanceForDisplay = (componentInstanceId:string, moduleId:string):ng.IPromise<DisplayModule> => {
424
425         let deferred = this.$q.defer<DisplayModule>();
426         let onSuccess = (response:DisplayModule):void => {
427             deferred.resolve(response);
428         };
429         let onFailed = (error:any):void => {
430             deferred.reject(error);
431         };
432         this.componentService.getComponentInstanceModule(this.uniqueId, componentInstanceId, moduleId).then(onSuccess, onFailed);
433         return deferred.promise;
434     };
435
436     public updateGroupMetadata = (module:Module):ng.IPromise<Module> => {
437
438         let deferred = this.$q.defer<Module>();
439
440         let onSuccess = (updatedModule:Module):void => {
441             let groupIndex:number = _.indexOf(this.modules, _.find(this.modules, (module:Module) => {
442                 return module.uniqueId === updatedModule.uniqueId;
443             }));
444
445             if (groupIndex !== -1) {
446                 this.modules[groupIndex] = updatedModule;
447             }
448             deferred.resolve(updatedModule);
449         };
450         let onFailed = (error:any):void => {
451             deferred.reject(error);
452         };
453
454         this.componentService.updateGroupMetadata(this.uniqueId, module).then(onSuccess, onFailed);
455
456         return deferred.promise;
457     };
458
459     //------------------------------------------ Help Functions ----------------------------------------------------------------//
460
461     public isService = ():boolean => {
462         return this instanceof Service;
463     };
464
465     public isResource = ():boolean => {
466         return this instanceof Resource;
467     };
468
469     public getComponentSubType = ():string => {
470         return this.componentType;
471     };
472
473     public isAlreadyCertified = ():boolean => {
474         return parseInt(this.version) >= 1;
475     };
476
477     public isComplex = ():boolean => {
478         return true;
479     };
480
481     //sort string version value from hash to sorted version (i.e 1.9 before 1.11)
482     private sortVersions = (v1:string, v2:string):number => {
483         let ver1 = v1.split('.');
484         let ver2 = v2.split('.');
485         let diff = parseInt(_.first(ver1)) - parseInt(_.first(ver2));
486         if (!diff) {
487             return parseInt(_.last(ver1)) - parseInt(_.last(ver2));
488         }
489         return diff;
490     };
491
492     public getAllVersionsAsSortedArray = ():Array<any> => {
493         let res = [];
494         if (this.allVersions) {
495             let keys = Object.keys(this.allVersions).sort(this.sortVersions);
496             _.forEach(keys, (key)=> {
497                 res.push({
498                     versionNumber: key,
499                     versionId: this.allVersions[key]
500                 })
501             });
502         }
503         return res;
504     };
505
506     public isLatestVersion = ():boolean => {
507         if (this.allVersions) {
508             return this.version === _.last(Object.keys(this.allVersions).sort(this.sortVersions));
509         } else {
510             return true;
511         }
512
513     };
514
515
516     public handleTags = ():void => {
517         let isContainTag = _.find(this.tags, (tag)=> {
518             return tag === this.name;
519         });
520         if (!isContainTag) {
521             this.tags.push(this.name);
522         }
523     };
524
525     public getArtifactsByType = (artifactGroupType:string):ArtifactGroupModel => {
526         switch (artifactGroupType) {
527             case ArtifactGroupType.DEPLOYMENT:
528                 return this.deploymentArtifacts;
529             case ArtifactGroupType.INFORMATION:
530                 return this.artifacts;
531         }
532     };
533
534     public getStatus = (sdcMenu:IAppMenu):string => {
535         let status:string = sdcMenu.LifeCycleStatuses[this.lifecycleState].text;
536         if (this.lifecycleState == "CERTIFIED" && sdcMenu.DistributionStatuses[this.distributionStatus]) {
537             status = sdcMenu.DistributionStatuses[this.distributionStatus].text;
538         }
539         return status;
540     };
541
542     public abstract setComponentDisplayData():void;
543     public abstract getTypeUrl():string;
544
545     public setComponentMetadata(componentMetadata: ComponentMetadata) {
546         this.abstract = componentMetadata.abstract;
547         this.uniqueId = componentMetadata.uniqueId;
548         this.uuid = componentMetadata.uuid;
549         this.invariantUUID = componentMetadata.invariantUUID;
550         this.contactId = componentMetadata.contactId;
551         this.categories = componentMetadata.categories;
552         this.creatorUserId = componentMetadata.creatorUserId;
553         this.creationDate = componentMetadata.creationDate;
554         this.creatorFullName = componentMetadata.creatorFullName;
555         this.description = componentMetadata.description;
556         this.icon = componentMetadata.icon;
557         this.lastUpdateDate = componentMetadata.lastUpdateDate;
558         this.lastUpdaterUserId = componentMetadata.lastUpdaterUserId;
559         this.lastUpdaterFullName = componentMetadata.lastUpdaterFullName;
560         this.lifecycleState = componentMetadata.lifecycleState;
561         this.name = componentMetadata.name;
562         this.version = componentMetadata.version;
563         this.tags = angular.copy(componentMetadata.tags, this.tags);
564         this.allVersions = componentMetadata.allVersions;
565         this.componentType = componentMetadata.componentType;
566         this.distributionStatus = componentMetadata.distributionStatus;
567         this.highestVersion = componentMetadata.highestVersion;
568         this.vendorName = componentMetadata.vendorName;
569         this.vendorRelease = componentMetadata.vendorRelease;
570         this.derivedList = componentMetadata.derivedList;
571         this.normalizedName = componentMetadata.normalizedName;
572         this.systemName = componentMetadata.systemName;
573         this.categories = componentMetadata.categories;
574         this.archived = componentMetadata.archived || false;
575         this.vspArchived = componentMetadata.vspArchived;
576         this.componentMetadata = componentMetadata;
577         if (componentMetadata.categorySpecificMetadata){
578             this.categorySpecificMetadata = componentMetadata.categorySpecificMetadata;
579         } else {
580             this.categorySpecificMetadata = new Metadata();
581         }
582     }
583
584     public toJSON = ():any => {
585         let temp = angular.copy(this);
586         temp.componentService = undefined;
587         temp.filterTerm = undefined;
588         temp.iconSprite = undefined;
589         temp.mainCategory = undefined;
590         temp.subCategory = undefined;
591         temp.selectedInstance = undefined;
592         temp.showMenu = undefined;
593         temp.$q = undefined;
594         temp.selectedCategory = undefined;
595         temp.modules = undefined
596         temp.groupInstances = undefined;
597         temp.policies = undefined;
598         return temp;
599     };
600 }
601