165578d0083e890fa54ceca1c2e6dd1023958d55
[sdc.git] /
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 /**
22  * Created by rcohen on 9/22/2016.
23  */
24 'use strict';
25 import * as _ from "lodash";
26 import {ComponentRef} from '@angular/core';
27 import {IWorkspaceViewModelScope} from "app/view-models/workspace/workspace-view-model";
28 import {ModalsHandler, ResourceType} from "app/utils";
29 import {ComponentType} from "app/utils/constants";
30 import {
31     Capability, PropertyModel, Requirement, Resource,
32     RelationshipTypesMap, NodeTypesMap, CapabilityTypesMap
33 } from "app/models";
34 import {ComponentGenericResponse} from "app/ng2/services/responses/component-generic-response";
35 import {ComponentServiceNg2} from "app/ng2/services/component-services/component.service";
36 import {ToscaTypesServiceNg2} from "app/ng2/services/tosca-types.service";
37 import {ModalComponent} from 'app/ng2/components/ui/modal/modal.component';
38 import {ModalService} from 'app/ng2/services/modal.service';
39 import {RequirementsEditorComponent} from 'app/ng2/pages/req-and-capabilities-editor/requirements-editor/requirements-editor.component';
40 import {CapabilitiesEditorComponent} from 'app/ng2/pages/req-and-capabilities-editor/capabilities-editor/capabilities-editor.component';
41 import {ModalService as ModalServiceSdcUI} from "sdc-ui/lib/angular/modals/modal.service";
42 import {IModalConfig} from "sdc-ui/lib/angular/modals/models/modal-config";
43 import {ModalButtonComponent} from "sdc-ui/lib/angular/components";
44
45 export class SortTableDefined {
46     reverse:boolean;
47     sortByField:string;
48 }
49
50 class RequirementUI extends Requirement {
51     isCreatedManually: boolean;
52
53     constructor(input: Requirement, componentUniqueId: string) {
54         super(input);
55         this.isCreatedManually = input.ownerId === componentUniqueId;
56     }
57 }
58 class CapabilityUI extends Capability {
59     isCreatedManually: boolean;
60
61     constructor(input: Capability, componentUniqueId: string) {
62         super(input);
63         this.isCreatedManually = input.ownerId === componentUniqueId;
64     }
65 }
66
67 interface IReqAndCapabilitiesViewModelScope extends IWorkspaceViewModelScope {
68     requirementsTableHeadersList:Array<any>;
69     editableRequirementsTableHeadersList: Array<any>;
70     capabilitiesTableHeadersList:Array<any>;
71     editableCapabilitiesTableHeadersList: Array<any>;
72     capabilityPropertiesTableHeadersList:Array<any>;
73     requirementsSortTableDefined:SortTableDefined;
74     capabilitiesSortTableDefined:SortTableDefined;
75     propertiesSortTableDefined:SortTableDefined;
76     requirements: Array<RequirementUI>;
77     filteredRequirementsList: Array<RequirementUI>;
78     capabilities: Array<CapabilityUI>;
79     filteredCapabilitiesList: Array<CapabilityUI>;
80     mode:string;
81     filteredProperties:Array<Array<PropertyModel>>;
82     searchText:string;
83     isEditable: boolean;
84     modalInstance: ComponentRef<ModalComponent>;
85     filter: {txt: string; show: boolean};
86
87     sort(sortBy:string, sortByTableDefined:SortTableDefined):void;
88     sortByIsCreatedManually(arrToSort: Array<RequirementUI|CapabilityUI>): Array<any>;
89     updateProperty(property:PropertyModel, indexInFilteredProperties:number):void;
90     allCapabilitiesSelected(selected:boolean):void;
91     onAddBtnClicked(): void;
92     onEditRequirement(req: RequirementUI): void;
93     onEditCapability(cap: CapabilityUI): void;
94     onDeleteReq(event, req: RequirementUI): void;
95     onDeleteCap(event, cap: CapabilityUI): void;
96     onFilter(): void;
97     isListEmpty(): boolean;
98     onSwitchTab(): void;
99     onSearchIconClick(): void;
100     cutToscaTypePrefix(valToCut: string, textToStartCut: string): string;
101     isReadonly(): boolean;
102 }
103
104 export class ReqAndCapabilitiesViewModel {
105
106     static '$inject' = [
107         '$scope',
108         '$filter',
109         'ModalsHandler',
110         'ComponentServiceNg2',
111         'ToscaTypesServiceNg2',
112         'ModalServiceNg2',
113         'ModalServiceSdcUI'
114     ];
115
116
117     constructor(private $scope:IReqAndCapabilitiesViewModelScope,
118                 private $filter:ng.IFilterService,
119                 private ModalsHandler:ModalsHandler,
120                 private ComponentServiceNg2: ComponentServiceNg2,
121                 private ToscaTypesServiceNg2: ToscaTypesServiceNg2,
122                 private ModalServiceNg2: ModalService,
123                 private ModalServiceSdcUI: ModalServiceSdcUI) {
124
125         this.initCapabilitiesAndRequirements();
126         this.fetchCapabilitiesRelatedData();
127     }
128
129     private initCapabilitiesAndRequirements = (): void => {
130
131         this.$scope.isEditable = this.getIsEditableByComponentType();
132         this.$scope.isLoading = true;
133         this.ComponentServiceNg2.getCapabilitiesAndRequirements(this.$scope.component.componentType, this.$scope.component.uniqueId).subscribe((response: ComponentGenericResponse) => {
134             this.$scope.component.capabilities = response.capabilities;
135             this.$scope.component.requirements = response.requirements;
136             this.initScope();
137             this.$scope.isLoading = false;
138         }, () => {
139             this.$scope.isLoading = false;
140         });
141
142     }
143
144     private openEditPropertyModal = (property:PropertyModel, indexInFilteredProperties:number):void => {
145         //...because there is not be api
146         _.forEach(this.$scope.filteredProperties[indexInFilteredProperties], (prop:PropertyModel)=> {
147             prop.readonly = true;
148         });
149         this.ModalsHandler.openEditPropertyModal(property, this.$scope.component, this.$scope.filteredProperties[indexInFilteredProperties], false, "component", this.$scope.component.uniqueId).then(() => {
150
151         });
152     };
153
154     private initScope = (currentMode = 'requirements'): void => {
155         this.$scope.isReadonly = (): boolean => {
156             return this.$scope.isViewMode() || !this.$scope.isDesigner();
157         };
158         this.$scope.filter = {txt: '', show: false};
159         this.$scope.requirementsSortTableDefined = {
160             reverse: false,
161             sortByField: this.$scope.isEditable ? 'other' : 'name'
162         };
163         this.$scope.capabilitiesSortTableDefined = {
164             reverse: false,
165             sortByField: this.$scope.isEditable ? 'other' : 'name'
166         };
167         this.$scope.propertiesSortTableDefined = {
168             reverse: false,
169             sortByField: 'name'
170         };
171
172         this.$scope.setValidState(true);
173         this.$scope.requirementsTableHeadersList = [
174             {title: 'Name', property: 'name'},
175             {title: 'Capability', property: 'capability'},
176             {title: 'Node', property: 'node'},
177             {title: 'Relationship', property: 'relationship'},
178             {title: 'Connected To', property: ''},
179             {title: 'Occurrences', property: ''}
180         ];
181         this.$scope.capabilitiesTableHeadersList = [
182             {title: 'Name', property: 'name'},
183             {title: 'Type', property: 'type'},
184             {title: 'Description', property: ''},
185             {title: 'Valid Source', property: ''},
186             {title: 'Occurrences', property: ''}
187         ];
188         this.$scope.editableRequirementsTableHeadersList = [
189             {title: 'Name', property: 'name'},
190             {title: 'Capability', property: 'capability'},
191             {title: 'Node', property: 'node'},
192             {title: 'Relationship', property: 'relationship'},
193             {title: 'Occurrences', property: 'occurrences'},
194             {title: '●●●', property: 'other'}
195         ];
196         this.$scope.editableCapabilitiesTableHeadersList = [
197             {title: 'Name', property: 'name'},
198             {title: 'Type', property: 'type'},
199             {title: 'Description', property: 'description'},
200             {title: 'Valid Sources', property: 'valid-sources'},
201             {title: 'Occurrences', property: 'occurrences'},
202             {title: '●●●', property: 'other'}
203         ];
204         this.$scope.capabilityPropertiesTableHeadersList = [
205             {title: 'Name', property: 'name'},
206             {title: 'Type', property: 'type'},
207             {title: 'Schema', property: 'schema.property.type'},
208             {title: 'Description', property: 'description'},
209         ];
210         this.$scope.filteredProperties = [];
211
212         this.$scope.mode = currentMode;
213         this.$scope.requirements = [];
214         _.forEach(this.$scope.component.requirements, (req:Array<Requirement>, capName)=> {
215             let reqUIList: Array<RequirementUI> = _.map(req, reqObj => new RequirementUI(reqObj, this.$scope.component.uniqueId));
216             this.$scope.requirements = this.$scope.requirements.concat(reqUIList);
217         });
218         this.$scope.filteredRequirementsList = this.$scope.requirements;
219
220         this.$scope.capabilities = [];
221         _.forEach(this.$scope.component.capabilities, (cap:Array<Capability>, capName)=> {
222             let capUIList: Array<CapabilityUI> = _.map(cap, capObj => new CapabilityUI(capObj, this.$scope.component.uniqueId));
223             this.$scope.capabilities = this.$scope.capabilities.concat(capUIList);
224         });
225
226         this.$scope.sortByIsCreatedManually = (arrToSort: Array<RequirementUI|CapabilityUI>): Array<any> => {
227             return arrToSort.sort((elem1: RequirementUI|CapabilityUI, elem2: RequirementUI|CapabilityUI) => +elem2.isCreatedManually - (+elem1.isCreatedManually));
228         };
229         this.$scope.filteredCapabilitiesList = this.$scope.sortByIsCreatedManually(this.$scope.capabilities);
230         this.$scope.filteredRequirementsList = this.$scope.sortByIsCreatedManually(this.$scope.requirements);
231
232         this.$scope.sort = (sortBy:string, sortByTableDefined:SortTableDefined):void => {
233             sortByTableDefined.reverse = (sortByTableDefined.sortByField === sortBy) ? !sortByTableDefined.reverse : false;
234             sortByTableDefined.sortByField = sortBy;
235         };
236
237         this.$scope.updateProperty = (property:PropertyModel, indexInFilteredProperties:number):void => {
238             this.openEditPropertyModal(property, indexInFilteredProperties);
239         };
240
241         this.$scope.allCapabilitiesSelected = (selected:boolean):void => {
242             _.forEach(this.$scope.capabilities, (cap:Capability)=> {
243                 cap.selected = selected;
244             });
245         };
246         this.$scope.onAddBtnClicked = (): void => {
247             switch (this.$scope.mode) {
248                 case 'requirements':
249                     this.openRequirementsModal();
250                     break;
251                 case 'capabilities':
252                     this.openCapabilitiesModal();
253                     break;
254             }
255         };
256         this.$scope.onEditRequirement = (req: RequirementUI): void => {
257             this.openRequirementsModal(req);
258         };
259         this.$scope.onEditCapability = (cap: CapabilityUI): void => {
260             this.openCapabilitiesModal(cap);
261         };
262         this.$scope.onDeleteReq = (event: Event, req: RequirementUI): void => {
263             event.stopPropagation();
264             this.ModalServiceSdcUI.openAlertModal('Delete Requirement',
265                 `Are you sure you want to delete requirement: ${req.name}?`, 'OK', () => this.deleteRequirement(req), 'Cancel');
266         };
267         this.$scope.onDeleteCap = (event: Event, cap: CapabilityUI): void => {
268             event.stopPropagation();
269             this.ModalServiceSdcUI.openAlertModal('Delete Capability',
270                 `Are you sure you want to delete capability: ${cap.name}?`, 'OK', () => this.deleteCapability(cap), 'Cancel');
271         };
272         this.$scope.onSearchIconClick = (): void => {
273             this.$scope.filter.show = !!this.$scope.filter.txt || !this.$scope.filter.show;
274         };
275         this.$scope.onFilter = (): void => {
276             switch (this.$scope.mode) {
277                 case 'requirements':
278                     this.$scope.filteredRequirementsList = _.filter(this.$scope.requirements, req => req.name.includes(this.$scope.filter.txt));
279                     break;
280                 case 'capabilities':
281                     this.$scope.filteredCapabilitiesList = _.filter(this.$scope.capabilities, cap => cap.name.includes(this.$scope.filter.txt));
282                     break;
283             }
284         };
285         this.$scope.isListEmpty = (): boolean => {
286             switch (this.$scope.mode) {
287                 case 'requirements':
288                     return this.$scope.requirements.length === 0;
289                 case 'capabilities':
290                     return this.$scope.capabilities.length === 0;
291             }
292         };
293         this.$scope.onSwitchTab = (): void => {
294             this.$scope.mode = this.$scope.mode === 'requirements' ? 'capabilities' : 'requirements';
295             this.$scope.filter.txt = '';
296             this.$scope.filter.show = false;
297             this.$scope.filteredRequirementsList = this.$scope.requirements;
298             this.$scope.filteredCapabilitiesList = this.$scope.capabilities;
299         };
300         this.$scope.cutToscaTypePrefix = (valToCut: string, textToStartCut: string): string => {
301             let index = valToCut.indexOf(textToStartCut);
302             return index !== -1 ? valToCut.substr(index + textToStartCut.length) : valToCut;
303         };
304     };
305
306     private getIsEditableByComponentType() {
307         if (this.$scope.componentType === ComponentType.SERVICE) {
308             return true;
309         }
310         if (this.$scope.component.isResource()) {
311             let componentAsResource: Resource = <Resource>this.$scope.component;
312             return componentAsResource.resourceType === ResourceType.VF ||
313                 componentAsResource.resourceType === ResourceType.PNF;
314         }
315         return false;
316     };
317
318     private fetchCapabilitiesRelatedData() {
319         if (this.$scope.isEditable) {
320             this.$scope.capabilityTypesList = [];
321             this.ToscaTypesServiceNg2.fetchCapabilityTypes().subscribe((result: CapabilityTypesMap) => {
322                 _.forEach(result, capabilityType => this.$scope.capabilityTypesList.push(capabilityType));
323             });
324             this.$scope.nodeTypesList = [];
325             this.ToscaTypesServiceNg2.fetchNodeTypes().subscribe((result: NodeTypesMap) => {
326                 _.forEach(result, nodeType => this.$scope.nodeTypesList.push(nodeType));
327             });
328             this.$scope.relationshipTypesList = [];
329             this.ToscaTypesServiceNg2.fetchRelationshipTypes().subscribe((result: RelationshipTypesMap) => {
330                 _.forEach(result, relshipType => this.$scope.relationshipTypesList.push(relshipType));
331             });
332         }
333     }
334
335     private openRequirementsModal(req?: RequirementUI) {
336         let modalConfig: IModalConfig = {
337             size: 'md',
338             title: (req ? 'Update' : 'Add') + ' Requirement',
339             type: 'custom',
340             buttons: [
341                 {
342                     id: 'saveButton',
343                     text: (req ? 'Update' : 'Create'),
344                     size: "'x-small'",
345                     callback: () => this.createOrUpdateRequirement(),
346                     closeModal: true
347                 },
348                 {text: "Cancel", size: "'x-small'", closeModal: true}]
349         };
350         let modalInputs = {
351             requirement: req,
352             relationshipTypesList: this.$scope.relationshipTypesList,
353             nodeTypesList: this.$scope.nodeTypesList,
354             capabilityTypesList: this.$scope.capabilityTypesList,
355             isReadonly: this.$scope.isViewMode() || !this.$scope.isDesigner(),
356             validityChangedCallback: this.getDisabled
357         };
358
359         this.ModalServiceSdcUI.openCustomModal(modalConfig, RequirementsEditorComponent, {input: modalInputs});
360     }
361
362     private openCapabilitiesModal(cap?: CapabilityUI) {
363         let modalConfig: IModalConfig = {
364             size: 'md',
365             title: (cap ? 'Update' : 'Add') + ' Capability',
366             type: 'custom',
367             buttons: [
368                 {
369                     id: 'saveButton',
370                     text: (cap ? 'Update' : 'Create'),
371                     size: "'x-small'",
372                     callback: () => this.createOrUpdateCapability(),
373                     closeModal: true
374                 },
375                 {text: "Cancel", size: "'x-small'", closeModal: true}]
376         };
377         let modalInputs = {
378             capability: cap,
379             capabilityTypesList: this.$scope.capabilityTypesList,
380             isReadonly: this.$scope.isViewMode() || !this.$scope.isDesigner(),
381             validityChangedCallback: this.getDisabled
382         };
383
384         this.ModalServiceSdcUI.openCustomModal(modalConfig, CapabilitiesEditorComponent, {input: modalInputs});
385     }
386
387     getDisabled = (shouldEnable: boolean): void => {
388         let saveButton: ModalButtonComponent = this.ModalServiceSdcUI.getCurrentInstance().getButtonById('saveButton');
389         saveButton.disabled = this.$scope.isViewMode() || !this.$scope.isDesigner() || !shouldEnable;
390     };
391
392     private createOrUpdateRequirement() {
393         let requirement = this.ModalServiceSdcUI.getCurrentInstance().innerModalContent.instance.requirementData;
394         this.$scope.isLoading = true;
395         if (!requirement.uniqueId) {
396             this.ComponentServiceNg2.createRequirement(this.$scope.component, requirement).subscribe(result => {
397                 this.$scope.requirements.unshift(new RequirementUI(result[0], this.$scope.component.uniqueId));
398                 this.$scope.isLoading = false;
399             }, () => {
400                 this.$scope.isLoading = false;
401             });
402         }
403         else {
404             this.ComponentServiceNg2.updateRequirement(this.$scope.component, requirement).subscribe(result => {
405                 let index = this.$scope.requirements.findIndex(req => result[0].uniqueId === req.uniqueId);
406                 this.$scope.requirements[index] = new RequirementUI(result[0], this.$scope.component.uniqueId);
407                 this.$scope.isLoading = false;
408                 this.$scope.$apply();
409             }, () => {
410                 this.$scope.isLoading = false;
411             });
412         }
413     }
414
415     private createOrUpdateCapability() {
416         let capability = this.ModalServiceSdcUI.getCurrentInstance().innerModalContent.instance.capabilityData;
417         this.$scope.isLoading = true;
418         if (!capability.uniqueId) {
419             this.ComponentServiceNg2.createCapability(this.$scope.component, capability).subscribe(result => {
420                 this.$scope.capabilities.unshift(new CapabilityUI(result[0], this.$scope.component.uniqueId));
421                 this.$scope.isLoading = false;
422             }, () => {
423                 this.$scope.isLoading = false;
424             });
425         }
426         else {
427             this.ComponentServiceNg2.updateCapability(this.$scope.component, capability).subscribe(result => {
428                 let index = this.$scope.capabilities.findIndex(cap => result[0].uniqueId === cap.uniqueId);
429                 this.$scope.capabilities[index] = new CapabilityUI(result[0], this.$scope.component.uniqueId);
430                 this.$scope.isLoading = false;
431                 this.$scope.$apply();
432             }, () => {
433                 this.$scope.isLoading = false;
434             });
435         }
436     }
437
438     private deleteRequirement(req) {
439         this.$scope.isLoading = true;
440         this.ComponentServiceNg2.deleteRequirement(this.$scope.component, req.uniqueId).subscribe(() => {
441             this.ComponentServiceNg2.getCapabilitiesAndRequirements(this.$scope.componentType, this.$scope.component.uniqueId).subscribe(response => {
442                 this.$scope.component.requirements = response.requirements;
443                 this.initScope('requirements');
444                 this.$scope.isLoading = false;
445             }, () => {
446                 this.$scope.isLoading = false;
447             });
448         }, () => {
449             this.$scope.isLoading = false;
450         });
451     }
452
453     private deleteCapability(cap) {
454         this.$scope.isLoading = true;
455         this.ComponentServiceNg2.deleteCapability(this.$scope.component, cap.uniqueId).subscribe(() => {
456             this.ComponentServiceNg2.getCapabilitiesAndRequirements(this.$scope.componentType, this.$scope.component.uniqueId).subscribe(response => {
457                 this.$scope.component.capabilities = response.capabilities;
458                 this.initScope('capabilities');
459                 this.$scope.isLoading = false;
460             }, () => {
461                 this.$scope.isLoading = false;
462             });
463         }, () => {
464             this.$scope.isLoading = false;
465         });
466     }
467 }
468