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