Provide timeout field in interface operation implementation
[sdc.git] / catalog-ui / src / app / ng2 / pages / composition / interface-operatons / interface-operations.component.ts
1 /*
2 * ============LICENSE_START=======================================================
3 * SDC
4 * ================================================================================
5 *  Copyright (C) 2021 Nordix Foundation. 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 *  Unless required by applicable law or agreed to in writing, software
13 *  distributed under the License is distributed on an "AS IS" BASIS,
14 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 *  See the License for the specific language governing permissions and
16 *  limitations under the License.
17 *
18 *  SPDX-License-Identifier: Apache-2.0
19 *  ============LICENSE_END=========================================================
20 */
21
22 import {Component, ComponentRef, Inject, Input} from '@angular/core';
23 import {
24     TopologyTemplateService
25 } from '../../../services/component-services/topology-template.service';
26 import {TranslateService} from "../../../shared/translator/translate.service";
27 import {ModalService} from 'app/ng2/services/modal.service';
28 import {CompositionService} from "app/ng2/pages/composition/composition.service";
29 import {ModalComponent} from 'app/ng2/components/ui/modal/modal.component';
30 import {Component as TopologyTemplate} from "../../../../models/components/component";
31 import {PluginsService} from "app/ng2/services/plugins.service";
32 import {SelectedComponentType} from "../common/store/graph.actions";
33 import {InstanceFeDetails} from "../../../../models/instance-fe-details";
34 import {WorkspaceService} from "../../workspace/workspace.service";
35 import {
36     ComponentInterfaceDefinitionModel,
37     InterfaceOperationModel
38 } from "../../../../models/interfaceOperation";
39 import {
40     InterfaceOperationHandlerComponent
41 } from "./operation-creator/interface-operation-handler.component";
42
43 import {
44     ArtifactModel,
45     ButtonModel,
46     ComponentInstance,
47     ComponentMetadata,
48     InputBEModel,
49     InterfaceModel,
50     ModalModel
51 } from 'app/models';
52 import {ArtifactGroupType} from "../../../../utils/constants";
53 import {
54     DropdownValue
55 } from "../../../components/ui/form-components/dropdown/ui-element-dropdown.component";
56 import {ToscaArtifactService} from "../../../services/tosca-artifact.service";
57 import {ToscaArtifactModel} from "../../../../models/toscaArtifact";
58
59 export class UIInterfaceOperationModel extends InterfaceOperationModel {
60     isCollapsed: boolean = true;
61     isEllipsis: boolean;
62     MAX_LENGTH = 75;
63
64     constructor(operation: InterfaceOperationModel) {
65         super(operation);
66
67         if (!operation.description) {
68             this.description = '';
69         }
70
71         if (this.description.length > this.MAX_LENGTH) {
72             this.isEllipsis = true;
73         } else {
74             this.isEllipsis = false;
75         }
76     }
77
78     getDescriptionEllipsis(): string {
79         if (this.isCollapsed && this.description.length > this.MAX_LENGTH) {
80             return this.description.substr(0, this.MAX_LENGTH - 3) + '...';
81         }
82         return this.description;
83     }
84
85     toggleCollapsed(e) {
86         e.stopPropagation();
87         this.isCollapsed = !this.isCollapsed;
88     }
89 }
90
91 class ModalTranslation {
92     EDIT_TITLE: string;
93     CANCEL_BUTTON: string;
94     CLOSE_BUTTON: string;
95     SAVE_BUTTON: string;
96
97     constructor(private translateService: TranslateService) {
98         this.translateService.languageChangedObservable.subscribe(lang => {
99             this.EDIT_TITLE = this.translateService.translate('INTERFACE_EDIT_TITLE');
100             this.CANCEL_BUTTON = this.translateService.translate("INTERFACE_CANCEL_BUTTON");
101             this.CLOSE_BUTTON = this.translateService.translate("INTERFACE_CLOSE_BUTTON");
102             this.SAVE_BUTTON = this.translateService.translate("INTERFACE_SAVE_BUTTON");
103         });
104     }
105 }
106
107 export class UIInterfaceModel extends ComponentInterfaceDefinitionModel {
108     isCollapsed: boolean = false;
109
110     constructor(interf?: any) {
111         super(interf);
112         this.operations = _.map(
113             this.operations,
114             (operation) => new UIInterfaceOperationModel(operation)
115         );
116     }
117
118     toggleCollapse() {
119         this.isCollapsed = !this.isCollapsed;
120     }
121 }
122
123 @Component({
124     selector: 'app-interface-operations',
125     templateUrl: './interface-operations.component.html',
126     styleUrls: ['./interface-operations.component.less'],
127     providers: [ModalService, TranslateService]
128 })
129 export class InterfaceOperationsComponent {
130     interfaces: UIInterfaceModel[];
131     inputs: Array<InputBEModel>;
132     isLoading: boolean;
133     interfaceTypes: { [interfaceType: string]: string[] };
134     topologyTemplate: TopologyTemplate;
135     componentMetaData: ComponentMetadata;
136     componentInstanceSelected: ComponentInstance;
137     modalInstance: ComponentRef<ModalComponent>;
138     modalTranslation: ModalTranslation;
139     componentInstancesInterfaces: Map<string, InterfaceModel[]>;
140
141     deploymentArtifactsFilePath: Array<DropdownValue> = [];
142     toscaArtifactTypes: Array<DropdownValue> = [];
143     componentInstanceMap: Map<string, InstanceFeDetails> = new Map<string, InstanceFeDetails>();
144     validImplementationProps: boolean = true;
145
146     @Input() component: ComponentInstance;
147     @Input() isViewOnly: boolean;
148     @Input() enableMenuItems: Function;
149     @Input() disableMenuItems: Function;
150     @Input() componentType: SelectedComponentType;
151
152
153     constructor(
154         private translateService: TranslateService,
155         private pluginsService: PluginsService,
156         private topologyTemplateService: TopologyTemplateService,
157         private toscaArtifactService: ToscaArtifactService,
158         private modalServiceNg2: ModalService,
159         private compositionService: CompositionService,
160         private workspaceService: WorkspaceService,
161         @Inject("Notification") private Notification: any,
162     ) {
163         this.modalTranslation = new ModalTranslation(translateService);
164     }
165
166     ngOnInit(): void {
167         this.componentMetaData = this.workspaceService.metadata;
168         this.loadComponentInstances();
169         this.loadDeployedArtifacts();
170         this.loadToscaArtifacts()
171     }
172
173     private loadComponentInstances() {
174         this.isLoading = true;
175         this.topologyTemplateService.getComponentInstances(this.componentMetaData.componentType, this.componentMetaData.uniqueId)
176         .subscribe((response) => {
177             this.componentInstanceSelected = response.componentInstances.find(ci => ci.uniqueId === this.component.uniqueId);
178             this.initComponentInstanceInterfaceOperations();
179             this.isLoading = false;
180         });
181     }
182
183     private initComponentInstanceInterfaceOperations() {
184         this.initInterfaces(this.componentInstanceSelected.interfaces);
185         this.sortInterfaces();
186     }
187
188     private initInterfaces(interfaces: ComponentInterfaceDefinitionModel[]): void {
189         this.interfaces = _.map(interfaces, (interfaceModel) => new UIInterfaceModel(interfaceModel));
190     }
191
192     private sortInterfaces(): void {
193         this.interfaces = _.filter(this.interfaces, (interf) => interf.operations && interf.operations.length > 0); // remove empty interfaces
194         this.interfaces.sort((a, b) => a.type.localeCompare(b.type)); // sort interfaces alphabetically
195         _.forEach(this.interfaces, (interf) => {
196             interf.operations.sort((a, b) => a.name.localeCompare(b.name)); // sort operations alphabetically
197         });
198     }
199
200     collapseAll(value: boolean = true): void {
201         _.forEach(this.interfaces, (interf) => {
202             interf.isCollapsed = value;
203         });
204     }
205
206     isAllCollapsed(): boolean {
207         return _.every(this.interfaces, (interf) => interf.isCollapsed);
208     }
209
210     isAllExpanded(): boolean {
211         return _.every(this.interfaces, (interf) => !interf.isCollapsed);
212     }
213
214     isListEmpty(): boolean {
215         return _.filter(
216             this.interfaces,
217             (interf) => interf.operations && interf.operations.length > 0
218         ).length === 0;
219     }
220
221     private disableSaveButton = (): boolean => {
222         let disable:boolean = true;
223         if(this.isViewOnly) {
224             return disable;
225         }
226
227         let enableAddArtifactImplementation = this.modalInstance.instance.dynamicContent.instance.enableAddArtifactImplementation;
228         if(enableAddArtifactImplementation) {
229             const validImplementationProps = this.modalInstance.instance.dynamicContent.instance.validImplementationProps;
230             const toscaArtifactTypeSelected = this.modalInstance.instance.dynamicContent.instance.toscaArtifactTypeSelected;
231             const isToscaArtifactType:boolean = !(typeof toscaArtifactTypeSelected == 'undefined' || _.isEmpty(toscaArtifactTypeSelected));
232             disable = !isToscaArtifactType || !validImplementationProps;
233             return disable;
234         }
235         disable = false;
236         return disable;
237     }
238
239     onSelectInterfaceOperation(interfaceModel: UIInterfaceModel, operation: InterfaceOperationModel) {
240
241         const buttonList = [];
242         if (this.isViewOnly) {
243             const closeButton: ButtonModel = new ButtonModel(this.modalTranslation.CLOSE_BUTTON, 'outline white', this.cancelAndCloseModal);
244             buttonList.push(closeButton);
245         } else {
246             const saveButton: ButtonModel = new ButtonModel(this.modalTranslation.SAVE_BUTTON, 'blue', () =>
247                 this.updateInterfaceOperation(), this.disableSaveButton);
248             const cancelButton: ButtonModel = new ButtonModel(this.modalTranslation.CANCEL_BUTTON, 'outline white', this.cancelAndCloseModal);
249             buttonList.push(saveButton);
250             buttonList.push(cancelButton);
251         }
252         const modalModel: ModalModel = new ModalModel('l', this.modalTranslation.EDIT_TITLE, '', buttonList, 'custom');
253         this.modalInstance = this.modalServiceNg2.createCustomModal(modalModel);
254
255         const componentInstances = this.compositionService.getComponentInstances()
256         if (componentInstances) {
257             componentInstances.forEach(value => {
258                 this.componentInstanceMap.set(value.uniqueId, <InstanceFeDetails>{
259                     name: value.name
260                 });
261             });
262         }
263
264         this.modalServiceNg2.addDynamicContentToModal(
265             this.modalInstance,
266             InterfaceOperationHandlerComponent,
267             {
268                 deploymentArtifactsFilePath: this.deploymentArtifactsFilePath,
269                 componentInstanceMap: this.componentInstanceMap,
270                 toscaArtifactTypes: this.toscaArtifactTypes,
271                 selectedInterface: interfaceModel ? interfaceModel : new UIInterfaceModel(),
272                 selectedInterfaceOperation: operation ? operation : new InterfaceOperationModel(),
273                 validityChangedCallback: this.disableSaveButton,
274                 isViewOnly: this.isViewOnly,
275                 validImplementationProps: this.validImplementationProps,
276                 isEdit: true,
277                 modelName: this.componentMetaData.model
278             }
279         );
280         this.modalInstance.instance.open();
281     }
282
283     private cancelAndCloseModal = () => {
284         this.loadComponentInstances();
285         return this.modalServiceNg2.closeCurrentModal();
286     }
287
288     private updateInterfaceOperation() {
289         this.modalServiceNg2.currentModal.instance.dynamicContent.instance.isLoading = true;
290         const interfaceOperationHandlerComponentInstance: InterfaceOperationHandlerComponent = this.modalInstance.instance.dynamicContent.instance;
291         const operationUpdated: InterfaceOperationModel = interfaceOperationHandlerComponentInstance.operationToUpdate;
292         let timeout = null;
293         if (operationUpdated.implementation && operationUpdated.implementation.timeout != null) {
294             timeout = operationUpdated.implementation.timeout;
295         }
296         const isArtifactChecked = interfaceOperationHandlerComponentInstance.enableAddArtifactImplementation;
297         if (!isArtifactChecked) {
298             let artifactName = interfaceOperationHandlerComponentInstance.artifactName;
299             artifactName = artifactName === undefined ? '' : artifactName;
300             operationUpdated.implementation = new ArtifactModel({'artifactName': artifactName, 'artifactVersion': ''} as ArtifactModel);
301         }
302         if (timeout != null) {
303             operationUpdated.implementation.timeout = timeout;
304         }
305         this.topologyTemplateService.updateComponentInstanceInterfaceOperation(
306             this.componentMetaData.uniqueId,
307             this.componentMetaData.componentType,
308             this.componentInstanceSelected.uniqueId,
309             operationUpdated)
310         .subscribe((updatedComponentInstance: ComponentInstance) => {
311             this.componentInstanceSelected = new ComponentInstance(updatedComponentInstance);
312             this.initComponentInstanceInterfaceOperations();
313             this.modalServiceNg2.currentModal.instance.dynamicContent.instance.isLoading = false;
314             this.modalServiceNg2.closeCurrentModal();
315         }, () => {
316             this.modalServiceNg2.currentModal.instance.dynamicContent.instance.isLoading = false;
317             this.modalServiceNg2.closeCurrentModal();
318         });
319     }
320
321     loadDeployedArtifacts() {
322         this.topologyTemplateService.getArtifactsByType(this.componentMetaData.componentType, this.componentMetaData.uniqueId, ArtifactGroupType.DEPLOYMENT)
323         .subscribe(response => {
324             let artifactsDeployment = response.deploymentArtifacts;
325             if (artifactsDeployment) {
326                 let deploymentArtifactsFound = <ArtifactModel[]>_.values(artifactsDeployment)
327                 deploymentArtifactsFound.forEach(value => {
328                     this.deploymentArtifactsFilePath.push(new DropdownValue(value, value.artifactType.concat('->').concat(value.artifactName)));
329                 });
330             }
331         }, error => {
332             this.Notification.error({
333                 message: 'Failed to Load the Deployed Artifacts:' + error,
334                 title: 'Failure'
335             });
336         });
337     }
338
339     loadToscaArtifacts() {
340         this.toscaArtifactService.getToscaArtifacts(this.componentMetaData.model).subscribe(response => {
341             if (response) {
342                 let toscaArtifactsFound = <ToscaArtifactModel[]>_.values(response);
343                 toscaArtifactsFound.forEach(value => this.toscaArtifactTypes.push(new DropdownValue(value, value.type)));
344             }
345         }, error => {
346             this.Notification.error({
347                 message: 'Failed to Load Tosca Artifacts:' + error,
348                 title: 'Failure'
349             });
350         });
351     }
352
353 }