Block interface operation edit in checkedin VFC
[sdc.git] / catalog-ui / src / app / ng2 / pages / interface-definition / interface-definition.page.component.ts
1 /*
2 * ============LICENSE_START=======================================================
3 * SDC
4 * ================================================================================
5 *  Copyright (C) 2022 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 import {Component, ComponentRef, Inject, Input} from '@angular/core';
22 import {Component as IComponent} from 'app/models/components/component';
23 import {WorkflowServiceNg2} from 'app/ng2/services/workflow.service';
24
25 import {ISdcConfig, SdcConfigToken} from "app/ng2/config/sdc-config.config";
26 import {TranslateService} from "app/ng2/shared/translator/translate.service";
27 import {IModalButtonComponent, SdcUiServices} from 'onap-ui-angular';
28 import {ModalComponent} from 'app/ng2/components/ui/modal/modal.component';
29
30 import {ModalService} from 'app/ng2/services/modal.service';
31 import {
32     ArtifactModel,
33     ButtonModel,
34     CapabilitiesGroup,
35     InputBEModel,
36     InterfaceModel,
37     ModalModel,
38     OperationModel,
39     WORKFLOW_ASSOCIATION_OPTIONS
40 } from 'app/models';
41
42 import {ComponentServiceNg2} from 'app/ng2/services/component-services/component.service';
43 import {TopologyTemplateService} from "../../services/component-services/topology-template.service";
44 import {InterfaceOperationModel} from "../../../models/interfaceOperation";
45 import {InterfaceOperationHandlerComponent} from "../composition/interface-operatons/operation-creator/interface-operation-handler.component";
46 import {DropdownValue} from "../../components/ui/form-components/dropdown/ui-element-dropdown.component";
47 import {ToscaArtifactModel} from "../../../models/toscaArtifact";
48 import {ToscaArtifactService} from "../../services/tosca-artifact.service";
49 import {InterfaceOperationComponent} from "../interface-operation/interface-operation.page.component";
50 import {Observable} from "rxjs/Observable";
51 import {PluginsService} from 'app/ng2/services/plugins.service';
52
53 export class UIOperationModel extends OperationModel {
54     isCollapsed: boolean = true;
55     isEllipsis: boolean;
56     MAX_LENGTH = 75;
57
58     constructor(operation: OperationModel) {
59         super(operation);
60         if (!operation.description) {
61             this.description = '';
62         }
63
64         if (this.description.length > this.MAX_LENGTH) {
65             this.isEllipsis = true;
66         } else {
67             this.isEllipsis = false;
68         }
69     }
70
71     getDescriptionEllipsis(): string {
72         if (this.isCollapsed && this.description.length > this.MAX_LENGTH) {
73             return this.description.substr(0, this.MAX_LENGTH - 3) + '...';
74         }
75         return this.description;
76     }
77
78     toggleCollapsed(e) {
79         e.stopPropagation();
80         this.isCollapsed = !this.isCollapsed;
81     }
82 }
83
84 class ModalTranslation {
85     CREATE_TITLE: string;
86     EDIT_TITLE: string;
87     DELETE_TITLE: string;
88     CANCEL_BUTTON: string;
89     SAVE_BUTTON: string;
90     CREATE_BUTTON: string;
91     DELETE_BUTTON: string;
92     deleteText: Function;
93
94     constructor(private TranslateService: TranslateService) {
95         this.TranslateService.languageChangedObservable.subscribe(lang => {
96             this.CREATE_TITLE = this.TranslateService.translate("INTERFACE_CREATE_TITLE");
97             this.EDIT_TITLE = this.TranslateService.translate('INTERFACE_EDIT_TITLE');
98             this.DELETE_TITLE = this.TranslateService.translate("INTERFACE_DELETE_TITLE");
99             this.CANCEL_BUTTON = this.TranslateService.translate("INTERFACE_CANCEL_BUTTON");
100             this.SAVE_BUTTON = this.TranslateService.translate("INTERFACE_SAVE_BUTTON");
101             this.CREATE_BUTTON = this.TranslateService.translate("INTERFACE_CREATE_BUTTON");
102             this.DELETE_BUTTON = this.TranslateService.translate("INTERFACE_DELETE_BUTTON");
103             this.deleteText = (operationName) => this.TranslateService.translate("INTERFACE_DELETE_TEXT", {operationName});
104         });
105     }
106 }
107
108 export class UIInterfaceModel extends InterfaceModel {
109     isCollapsed: boolean = false;
110
111     constructor(interf?: any) {
112         super(interf);
113         if (this.operations) {
114             this.operations = this.operations.map((operation) => new UIOperationModel(operation));
115         }
116     }
117
118     toggleCollapse() {
119         this.isCollapsed = !this.isCollapsed;
120     }
121 }
122
123 @Component({
124     selector: 'interface-definition',
125     templateUrl: './interface-definition.page.component.html',
126     styleUrls: ['interface-definition.page.component.less'],
127     providers: [ModalService, TranslateService, InterfaceOperationComponent]
128 })
129 export class InterfaceDefinitionComponent {
130
131     modalInstance: ComponentRef<ModalComponent>;
132     interfaces: UIInterfaceModel[];
133     inputs: InputBEModel[];
134
135     deploymentArtifactsFilePath: Array<DropdownValue> = [];
136
137     toscaArtifactTypes: Array<DropdownValue> = [];
138     interfaceTypesTest: Array<DropdownValue> = [];
139     interfaceTypesMap: Map<string, string[]>;
140
141     isLoading: boolean;
142     interfaceTypes: { [interfaceType: string]: string[] };
143     modalTranslation: ModalTranslation;
144     workflows: any[];
145     capabilities: CapabilitiesGroup;
146
147     openOperation: OperationModel;
148     enableWorkflowAssociation: boolean;
149     workflowIsOnline: boolean;
150
151     @Input() component: IComponent;
152     @Input() readonly: boolean;
153     @Input() enableMenuItems: Function;
154     @Input() disableMenuItems: Function;
155
156     constructor(
157         @Inject(SdcConfigToken) private sdcConfig: ISdcConfig,
158         @Inject("$state") private $state: ng.ui.IStateService,
159         @Inject("Notification") private notification: any,
160         private translateService: TranslateService,
161         private componentServiceNg2: ComponentServiceNg2,
162         private modalServiceNg2: ModalService,
163         private modalServiceSdcUI: SdcUiServices.ModalService,
164         private topologyTemplateService: TopologyTemplateService,
165         private toscaArtifactService: ToscaArtifactService,
166         private ComponentServiceNg2: ComponentServiceNg2,
167         private WorkflowServiceNg2: WorkflowServiceNg2,
168         private ModalServiceSdcUI: SdcUiServices.ModalService,
169         private PluginsService: PluginsService
170     ) {
171         this.modalTranslation = new ModalTranslation(translateService);
172         this.interfaceTypesMap = new Map<string, string[]>();
173     }
174
175     ngOnInit(): void {
176         this.isLoading = true;
177         this.interfaces = [];
178         this.workflowIsOnline = !_.isUndefined(this.PluginsService.getPluginByStateUrl('workflowDesigner'));
179         Observable.forkJoin(
180             this.ComponentServiceNg2.getInterfaceOperations(this.component),
181             this.ComponentServiceNg2.getComponentInputs(this.component),
182             this.ComponentServiceNg2.getInterfaceTypes(this.component),
183             this.ComponentServiceNg2.getCapabilitiesAndRequirements(this.component.componentType, this.component.uniqueId)
184         ).subscribe((response: any[]) => {
185             const callback = (workflows) => {
186                 this.isLoading = false;
187                 this.initInterfaces(response[0].interfaces);
188                 this.sortInterfaces();
189                 this.inputs = response[1].inputs;
190                 this.interfaceTypes = response[2];
191                 this.workflows = (workflows.items) ? workflows.items : workflows;
192                 this.capabilities = response[3].capabilities;
193             };
194             if (this.enableWorkflowAssociation && this.workflowIsOnline) {
195                 this.WorkflowServiceNg2.getWorkflows().subscribe(
196                     callback,
197                     (err) => {
198                         this.workflowIsOnline = false;
199                         callback([]);
200                     }
201                 );
202             } else {
203                 callback([]);
204             }
205         });
206         this.loadToscaArtifacts();
207     }
208
209     initInterfaces(interfaces: InterfaceModel[]): void {
210         if (interfaces) {
211             this.interfaces = interfaces.map((interf) => new UIInterfaceModel(interf));
212         }
213     }
214
215     private cancelAndCloseModal = () => {
216         return this.modalServiceNg2.closeCurrentModal();
217     }
218
219     private disableSaveButton = (): boolean => {
220         return this.readonly ||
221             (this.isEnableAddArtifactImplementation()
222                 && (!this.modalInstance.instance.dynamicContent.toscaArtifactTypeSelected ||
223                     !this.modalInstance.instance.dynamicContent.artifactName)
224             );
225     }
226
227     onSelectInterfaceOperation(interfaceModel: UIInterfaceModel, operation: InterfaceOperationModel) {
228         const isEdit = operation !== undefined;
229         const modalButtons = [];
230         if (!this.readonly) {
231             const saveButton: ButtonModel = new ButtonModel(this.modalTranslation.SAVE_BUTTON, 'blue',
232                 () => isEdit ? this.updateOperation() : this.createOperationCallback(),
233                 this.disableSaveButton
234             );
235             modalButtons.push(saveButton);
236         }
237         modalButtons.push(new ButtonModel(this.modalTranslation.CANCEL_BUTTON, 'outline white', this.cancelAndCloseModal));
238         const interfaceDataModal: ModalModel =
239             new ModalModel('l', this.modalTranslation.EDIT_TITLE, '', modalButtons, 'custom');
240         this.modalInstance = this.modalServiceNg2.createCustomModal(interfaceDataModal);
241
242         this.modalServiceNg2.addDynamicContentToModal(
243             this.modalInstance,
244             InterfaceOperationHandlerComponent,
245             {
246                 deploymentArtifactsFilePath: this.deploymentArtifactsFilePath,
247                 toscaArtifactTypes: this.toscaArtifactTypes,
248                 selectedInterface: interfaceModel ? interfaceModel : new UIInterfaceModel(),
249                 selectedInterfaceOperation: operation ? operation : new InterfaceOperationModel(),
250                 validityChangedCallback: this.disableSaveButton,
251                 isViewOnly: this.readonly,
252                 'isEdit': isEdit,
253                 interfaceTypesMap: this.interfaceTypesMap,
254                 modelName: this.component.model
255             }
256         );
257         this.modalInstance.instance.open();
258     }
259
260     private updateOperation = (): void => {
261         this.modalServiceNg2.currentModal.instance.dynamicContent.instance.isLoading = true;
262         const interfaceOperationHandlerComponentInstance: InterfaceOperationHandlerComponent = this.modalInstance.instance.dynamicContent.instance;
263         const operationToUpdate = this.modalInstance.instance.dynamicContent.instance.operationToUpdate;
264         const isArtifactChecked = interfaceOperationHandlerComponentInstance.enableAddArtifactImplementation;
265         if (!isArtifactChecked) {
266             const artifactName = interfaceOperationHandlerComponentInstance.artifactName ?
267                 interfaceOperationHandlerComponentInstance.artifactName : '';
268             operationToUpdate.implementation = new ArtifactModel({'artifactName': artifactName, 'artifactVersion': ''} as ArtifactModel);
269         }
270         this.componentServiceNg2.updateComponentInterfaceOperation(this.component.uniqueId, operationToUpdate)
271         .subscribe((newOperation: InterfaceOperationModel) => {
272             let oldOpIndex;
273             let oldInterf;
274             this.interfaces.forEach(interf => {
275                 interf.operations.forEach(op => {
276                     if (op.uniqueId === newOperation.uniqueId) {
277                         oldInterf = interf;
278                         oldOpIndex = interf.operations.findIndex((el) => el.uniqueId === op.uniqueId);
279                     }
280                 });
281             });
282             oldInterf.operations.splice(oldOpIndex, 1);
283             oldInterf.operations.push(new InterfaceOperationModel(newOperation));
284         }, error => {
285             this.modalServiceNg2.currentModal.instance.dynamicContent.instance.isLoading = false;
286         }, () => {
287             this.sortInterfaces();
288             this.modalServiceNg2.currentModal.instance.dynamicContent.instance.isLoading = false;
289             this.modalServiceNg2.closeCurrentModal();
290         });
291     }
292
293     private createOperationCallback(): void {
294         this.modalServiceNg2.currentModal.instance.dynamicContent.instance.isLoading = true;
295         const operationToUpdate = this.modalInstance.instance.dynamicContent.instance.operationToUpdate;
296         console.log('createOperationCallback', operationToUpdate);
297         console.log('this.component', this.component);
298         this.componentServiceNg2.createComponentInterfaceOperation(this.component.uniqueId, this.component.getTypeUrl(), operationToUpdate)
299         .subscribe((newOperation: InterfaceOperationModel) => {
300             const foundInterface = this.interfaces.find(value => value.type === newOperation.interfaceType);
301             if (foundInterface) {
302                 foundInterface.operations.push(new UIOperationModel(new OperationModel(newOperation)));
303             } else {
304                 const uiInterfaceModel = new UIInterfaceModel();
305                 uiInterfaceModel.type = newOperation.interfaceType;
306                 uiInterfaceModel.uniqueId = newOperation.interfaceType;
307                 uiInterfaceModel.operations = [];
308                 uiInterfaceModel.operations.push(new UIOperationModel(new OperationModel(newOperation)));
309                 this.interfaces.push(uiInterfaceModel);
310             }
311         }, error => {
312             this.modalServiceNg2.currentModal.instance.dynamicContent.instance.isLoading = false;
313         }, () => {
314             this.modalServiceNg2.currentModal.instance.dynamicContent.instance.isLoading = false;
315             this.modalServiceNg2.closeCurrentModal();
316         });
317     }
318
319     private handleEnableAddArtifactImplementation = (newOperation: InterfaceOperationModel): InterfaceOperationModel => {
320         if (!this.isEnableAddArtifactImplementation()) {
321             newOperation.implementation.artifactType = null;
322             newOperation.implementation.artifactVersion = null;
323         }
324         return newOperation;
325     }
326
327     private isEnableAddArtifactImplementation = (): boolean => {
328         return this.modalInstance.instance.dynamicContent.enableAddArtifactImplementation;
329     }
330
331     private initInterfaceDefinition() {
332         this.isLoading = true;
333         this.interfaces = [];
334         this.topologyTemplateService.getComponentInterfaceOperations(this.component.componentType, this.component.uniqueId)
335         .subscribe((response) => {
336             if (response.interfaces) {
337                 this.interfaces = response.interfaces.map((interfaceModel) => new UIInterfaceModel(interfaceModel));
338             }
339             this.isLoading = false;
340         });
341     }
342
343     private loadToscaArtifacts() {
344         this.toscaArtifactService.getToscaArtifacts(this.component.model).subscribe(response => {
345             if (response) {
346                 let toscaArtifactsFound = <ToscaArtifactModel[]>_.values(response);
347                 toscaArtifactsFound.forEach(value => this.toscaArtifactTypes.push(new DropdownValue(value, value.type)));
348             }
349         }, error => {
350             this.notification.error({
351                 message: 'Failed to Load Tosca Artifacts:' + error,
352                 title: 'Failure'
353             });
354         });
355     }
356
357     private loadInterfaceTypes() {
358         this.componentServiceNg2.getInterfaceTypes(this.component).subscribe(response => {
359             if (response) {
360                 console.info("loadInterfaceTypes ", response);
361                 for (const interfaceType in response) {
362                     this.interfaceTypesMap.set(interfaceType, response[interfaceType]);
363                     this.interfaceTypesTest.push(new DropdownValue(interfaceType, interfaceType));
364                 }
365             }
366         }, error => {
367             this.notification.error({
368                 message: 'Failed to Load Interface Types:' + error,
369                 title: 'Failure'
370             });
371         });
372     }
373
374     collapseAll(value: boolean = true): void {
375         this.interfaces.forEach(interfaceData => {
376             interfaceData.isCollapsed = value;
377         });
378     }
379
380     isAllCollapsed(): boolean {
381         return this.interfaces.every((interfaceData) => interfaceData.isCollapsed);
382     }
383
384     isAllExpanded(): boolean {
385         return this.interfaces.every((interfaceData) => !interfaceData.isCollapsed);
386     }
387
388     isInterfaceListEmpty(): boolean {
389         return this.interfaces.length === 0;
390     }
391
392     isOperationListEmpty(): boolean {
393         return this.interfaces.filter((interfaceData) => interfaceData.operations && interfaceData.operations.length > 0).length > 0;
394     }
395
396     onRemoveOperation(operation: OperationModel): void {
397         if (this.readonly) {
398             return;
399         }
400
401         const deleteButton: IModalButtonComponent = {
402             id: 'deleteButton',
403             text: this.modalTranslation.DELETE_BUTTON,
404             type: 'primary',
405             size: 'small',
406             closeModal: true,
407             callback: () => {
408                 this.ComponentServiceNg2
409                 .deleteInterfaceOperation(this.component, operation)
410                 .subscribe(() => {
411                     const curInterf = this.interfaces.find((interf) => interf.type === operation.interfaceType);
412                     const index = curInterf.operations.findIndex((el) => el.uniqueId === operation.uniqueId);
413                     curInterf.operations.splice(index, 1);
414                     if (!curInterf.operations.length) {
415                         const interfIndex = this.interfaces.findIndex((interf) => interf.type === operation.interfaceType);
416                         this.interfaces.splice(interfIndex, 1);
417                     }
418                 });
419             }
420         };
421
422         const cancelButton: IModalButtonComponent = {
423             id: 'cancelButton',
424             text: this.modalTranslation.CANCEL_BUTTON,
425             type: 'secondary',
426             size: 'small',
427             closeModal: true,
428             callback: () => {
429                 this.openOperation = null;
430             },
431         };
432
433         this.ModalServiceSdcUI.openWarningModal(
434             this.modalTranslation.DELETE_TITLE,
435             this.modalTranslation.deleteText(operation.name),
436             'deleteOperationModal',
437             [deleteButton, cancelButton],
438         );
439     }
440
441     private createOperation = (operation: OperationModel): void => {
442         this.ComponentServiceNg2.createInterfaceOperation(this.component, operation).subscribe((response: OperationModel) => {
443             this.openOperation = null;
444
445             let curInterf = this.interfaces.find((interf) => interf.type === operation.interfaceType);
446
447             if (!curInterf) {
448                 curInterf = new UIInterfaceModel({
449                     type: response.interfaceType,
450                     uniqueId: response.uniqueId,
451                     operations: []
452                 });
453                 this.interfaces.push(curInterf);
454             }
455
456             const newOpModel = new UIOperationModel(response);
457             curInterf.operations.push(newOpModel);
458             this.sortInterfaces();
459
460             if (operation.workflowAssociationType === WORKFLOW_ASSOCIATION_OPTIONS.EXTERNAL && operation.artifactData) {
461                 this.ComponentServiceNg2.uploadInterfaceOperationArtifact(this.component, newOpModel, operation).subscribe();
462             } else if (response.workflowId && operation.workflowAssociationType === WORKFLOW_ASSOCIATION_OPTIONS.EXISTING) {
463                 this.WorkflowServiceNg2.associateWorkflowArtifact(this.component, response).subscribe();
464             } else if (operation.workflowAssociationType === WORKFLOW_ASSOCIATION_OPTIONS.NEW) {
465                 this.$state.go('workspace.plugins', {path: 'workflowDesigner'});
466             }
467         });
468     }
469
470     private enableOrDisableSaveButton = (shouldEnable: boolean): void => {
471         const saveButton = this.modalInstance.instance.dynamicContent.getButtonById('saveButton');
472         saveButton.disabled = !shouldEnable;
473     }
474
475     private sortInterfaces(): void {
476         this.interfaces = this.interfaces.filter((interf) => interf.operations && interf.operations.length > 0); // remove empty interfaces
477         this.interfaces.sort((a, b) => a.type.localeCompare(b.type)); // sort interfaces alphabetically
478         this.interfaces.forEach((interf) => {
479             interf.operations.sort((a, b) => a.name.localeCompare(b.name)); // sort operations alphabetically
480         });
481     }
482
483 }