Add CDS version and apply minor css style changes
[ccsdk/cds.git] / cds-ui / designer-client / src / app / modules / feature-modules / packages / configuration-dashboard / configuration-dashboard.component.ts
index eb121e9..b3894fe 100644 (file)
@@ -1,38 +1,41 @@
-import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
-import {ActivatedRoute, Router} from '@angular/router';
-import {BluePrintDetailModel} from '../model/BluePrint.detail.model';
-import {PackageCreationStore} from '../package-creation/package-creation.store';
-import {FilesContent, FolderNodeElement, MetaDataTabModel} from '../package-creation/mapping-models/metadata/MetaDataTab.model';
-import {MetadataTabComponent} from '../package-creation/metadata-tab/metadata-tab.component';
+import { Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
+import { ActivatedRoute, Router } from '@angular/router';
+import { BluePrintDetailModel } from '../model/BluePrint.detail.model';
+import { PackageCreationStore } from '../package-creation/package-creation.store';
+import { FilesContent, FolderNodeElement } from '../package-creation/mapping-models/metadata/MetaDataTab.model';
+import { MetadataTabComponent } from '../package-creation/metadata-tab/metadata-tab.component';
 import * as JSZip from 'jszip';
-import {ConfigurationDashboardService} from './configuration-dashboard.service';
-import {TemplateTopology, VlbDefinition} from '../package-creation/mapping-models/definitions/VlbDefinition';
-import {CBAPackage, DslDefinition} from '../package-creation/mapping-models/CBAPacakge.model';
-import {PackageCreationUtils} from '../package-creation/package-creation.utils';
-import {PackageCreationModes} from '../package-creation/creationModes/PackageCreationModes';
-import {PackageCreationBuilder} from '../package-creation/creationModes/PackageCreationBuilder';
-import {saveAs} from 'file-saver';
-import {DesignerStore} from '../designer/designer.store';
-import {ToastrService} from 'ngx-toastr';
-import {NgxFileDropEntry} from 'ngx-file-drop';
-import {PackageCreationService} from '../package-creation/package-creation.service';
-import {ComponentCanDeactivate} from '../../../../common/core/canDactivate/ComponentCanDeactivate';
-import {PackageCreationExtractionService} from '../package-creation/package-creation-extraction.service';
+import { ConfigurationDashboardService } from './configuration-dashboard.service';
+import { TemplateTopology, CBADefinition } from '../package-creation/mapping-models/definitions/CBADefinition';
+import { CBAPackage } from '../package-creation/mapping-models/CBAPacakge.model';
+import { PackageCreationUtils } from '../package-creation/package-creation.utils';
+import { PackageCreationModes } from '../package-creation/creationModes/PackageCreationModes';
+import { PackageCreationBuilder } from '../package-creation/creationModes/PackageCreationBuilder';
+import { saveAs } from 'file-saver';
+import { DesignerStore } from '../designer/designer.store';
+import { ToastrService } from 'ngx-toastr';
+import { NgxFileDropEntry } from 'ngx-file-drop';
+import { PackageCreationService } from '../package-creation/package-creation.service';
+import { ComponentCanDeactivate } from '../../../../common/core/canDactivate/ComponentCanDeactivate';
+import { PackageCreationExtractionService } from '../package-creation/package-creation-extraction.service';
+import { distinctUntilChanged, takeUntil } from 'rxjs/operators';
+import { Subject, throwError } from 'rxjs';
+import { NgxUiLoaderService } from 'ngx-ui-loader';
 
 @Component({
     selector: 'app-configuration-dashboard',
     templateUrl: './configuration-dashboard.component.html',
     styleUrls: ['./configuration-dashboard.component.css'],
 })
-export class ConfigurationDashboardComponent extends ComponentCanDeactivate implements OnInit {
+export class ConfigurationDashboardComponent extends ComponentCanDeactivate implements OnInit, OnDestroy {
     viewedPackage: BluePrintDetailModel = new BluePrintDetailModel();
-    @ViewChild(MetadataTabComponent, {static: false})
+    @ViewChild(MetadataTabComponent, { static: false })
     metadataTabComponent: MetadataTabComponent;
     public customActionName = '';
 
     entryDefinitionKeys: string[] = ['template_tags', 'user-groups',
         'author-email', 'template_version', 'template_name', 'template_author', 'template_description'];
-    @ViewChild('nameit', {static: true})
+    @ViewChild('nameit', { static: true })
     elementRef: ElementRef;
     uploadedFiles = [];
     zipFile: JSZip = new JSZip();
@@ -41,12 +44,15 @@ export class ConfigurationDashboardComponent extends ComponentCanDeactivate impl
     id: any;
 
     currentBlob = new Blob();
-    vlbDefinition: VlbDefinition = new VlbDefinition();
+    vlbDefinition: CBADefinition = new CBADefinition();
     isSaveEnabled = false;
     versionPattern = '^(\\d+\\.)?(\\d+\\.)?(\\*|\\d+)$';
     metadataClasses = 'nav-item nav-link active';
     private cbaPackage: CBAPackage = new CBAPackage();
     dataTarget: any = '';
+    ngUnsubscribe = new Subject();
+    private designerState: any;
+    packageId: any;
 
     constructor(
         private route: ActivatedRoute,
@@ -57,21 +63,32 @@ export class ConfigurationDashboardComponent extends ComponentCanDeactivate impl
         private router: Router,
         private designerStore: DesignerStore,
         private toastService: ToastrService,
-        private packageCreationExtractionService: PackageCreationExtractionService
+        private ngxService: NgxUiLoaderService,
+        private packageCreationExtractionService: PackageCreationExtractionService,
+        private activatedRoute: ActivatedRoute,
     ) {
         super();
 
-        this.packageCreationStore.state$.subscribe(
-            cbaPackage => {
-                this.cbaPackage = cbaPackage;
-            });
-
 
     }
 
     ngOnInit() {
+        this.ngxService.start();
         this.vlbDefinition.topology_template = new TemplateTopology();
-
+        this.packageCreationStore.state$
+            .pipe(distinctUntilChanged((a: any, b: any) => JSON.stringify(a) === JSON.stringify(b)),
+                takeUntil(this.ngUnsubscribe))
+            .subscribe(
+                cbaPackage => {
+                    this.cbaPackage = cbaPackage;
+                });
+        this.designerStore.state$.pipe(
+            distinctUntilChanged((a: any, b: any) => JSON.stringify(a) === JSON.stringify(b)),
+            takeUntil(this.ngUnsubscribe))
+            .subscribe(state => {
+                this.designerState = state;
+                this.vlbDefinition.topology_template.content = this.packageCreationUtils.transformToJson(state.template);
+            });
         this.elementRef.nativeElement.focus();
         this.refreshCurrentPackage();
         const regexp = RegExp(this.versionPattern);
@@ -85,11 +102,13 @@ export class ConfigurationDashboardComponent extends ComponentCanDeactivate impl
             this.metadataClasses = this.metadataClasses.replace('complete', '');
             this.isSaveEnabled = false;
         }
+        this.activatedRoute.paramMap.subscribe(res => {
+            this.packageId = res.get('id');
+        });
 
 
     }
 
-
     private refreshCurrentPackage(id?) {
         this.id = this.route.snapshot.paramMap.get('id');
         console.log(this.id);
@@ -101,90 +120,27 @@ export class ConfigurationDashboardComponent extends ComponentCanDeactivate impl
                     this.downloadCBAPackage(bluePrintDetailModels);
                     this.packageCreationStore.clear();
                 }
+            }, err => { },
+            () => {
+                //  this.ngxService.stop();
             });
     }
 
     private downloadCBAPackage(bluePrintDetailModels: BluePrintDetailModel) {
         this.configurationDashboardService.downloadResource(
             this.viewedPackage.artifactName + '/' + this.viewedPackage.artifactVersion).subscribe(response => {
-            const blob = new Blob([response], {type: 'application/octet-stream'});
-            this.currentBlob = blob;
-            this.extractBlobToStore(blob, this.viewedPackage);
-        });
-    }
-
-    private extractBlobToStore(blob: Blob, bluePrintDetailModel: BluePrintDetailModel) {
-        this.zipFile.loadAsync(blob).then((zip) => {
-            Object.keys(zip.files).forEach((filename) => {
-                zip.files[filename].async('string').then((fileData) => {
-                    console.log(filename);
-                    if (fileData) {
-                        if (filename.includes('Scripts/')) {
-                            this.setScripts(filename, fileData);
-                        } else if (filename.includes('Templates/')) {
-                            if (filename.includes('-mapping.')) {
-                                this.setMapping(filename, fileData);
-                            } else if (filename.includes('-template.')) {
-                                this.setTemplates(filename, fileData);
-                            }
-
-                        } else if (filename.includes('Definitions/')) {
-                            this.setImports(filename, fileData, bluePrintDetailModel);
-                        } else if (filename.includes('TOSCA-Metadata/')) {
-                            const metaDataTabInfo: MetaDataTabModel = this.getMetaDataTabInfo(fileData);
-                            this.setMetaData(metaDataTabInfo, bluePrintDetailModel);
-                        }
-                    }
+                const blob = new Blob([response], { type: 'application/octet-stream' });
+                this.currentBlob = blob;
+                this.packageCreationExtractionService.extractBlobToStore(blob);
+            }, err => { },
+                () => {
+                    this.ngxService.stop();
                 });
-            });
-        });
-    }
-
-    setScripts(filename: string, fileData: any) {
-        this.packageCreationStore.addScripts(filename, fileData);
-    }
-
-    setImports(filename: string, fileData: any, bluePrintDetailModels: BluePrintDetailModel) {
-        console.log(filename);
-        if (filename.includes(bluePrintDetailModels.artifactName)) {
-            let definition = new VlbDefinition();
-            definition = fileData as VlbDefinition;
-            definition = JSON.parse(fileData);
-            const dslDefinition = new DslDefinition();
-            dslDefinition.content = this.packageCreationUtils.transformToJson(definition.dsl_definitions);
-            const mapOfCustomKeys = new Map<string, string>();
-            for (const metadataKey in definition.metadata) {
-                if (!this.entryDefinitionKeys.includes(metadataKey + '')) {
-                    mapOfCustomKeys.set(metadataKey + '', definition.metadata[metadataKey + '']);
-                }
-            }
-            this.packageCreationStore.changeDslDefinition(dslDefinition);
-            this.packageCreationStore.setCustomKeys(mapOfCustomKeys);
-            if (definition.topology_template) {
-                const content = {};
-                const workflow = 'workflows';
-                content[workflow] = definition.topology_template.workflows;
-                const nodeTemplates = 'node_templates';
-                content[nodeTemplates] = definition.topology_template.node_templates;
-                this.designerStore.saveSourceContent(JSON.stringify(content));
-                this.packageCreationStore.addTopologyTemplate(definition.topology_template);
-            }
-
-        }
-        this.packageCreationStore.addDefinition(filename, fileData);
-
-    }
-
-    setTemplates(filename: string, fileData: any) {
-        this.packageCreationStore.addTemplate(filename, fileData);
-    }
-
-    setMapping(fileName: string, fileData: string) {
-        this.packageCreationStore.addMapping(fileName, fileData);
     }
 
     editBluePrint() {
-        this.configurationDashboardService.deletePackage(this.viewedPackage.id).subscribe(res => {
+        this.ngxService.start();
+        this.configurationDashboardService.deletePackage(this.packageId).subscribe(res => {
             this.formTreeData();
             this.saveBluePrintToDataBase();
 
@@ -201,44 +157,28 @@ export class ConfigurationDashboardComponent extends ComponentCanDeactivate impl
         this.filesData.push(this.folder.TREE_DATA);
     }
 
-    setMetaData(metaDataObject: MetaDataTabModel, bluePrintDetailModel: BluePrintDetailModel) {
-        metaDataObject.description = bluePrintDetailModel.artifactDescription;
-        this.packageCreationStore.changeMetaData(metaDataObject);
-
-    }
-
     saveMetaData() {
         this.metadataTabComponent.saveMetaDataToStore();
-
-    }
-
-    getMetaDataTabInfo(fileData: string) {
-        const metaDataTabModel = new MetaDataTabModel();
-        const arrayOfLines = fileData.split('\n');
-        metaDataTabModel.entryFileName = arrayOfLines[3].split(':')[1];
-        metaDataTabModel.name = arrayOfLines[4].split(':')[1];
-        metaDataTabModel.version = arrayOfLines[5].split(':')[1];
-        metaDataTabModel.mode = arrayOfLines[6].split(':')[1];
-        metaDataTabModel.templateTags = new Set<string>(arrayOfLines[7].split(':')[1].split(','));
-        return metaDataTabModel;
     }
 
     saveBluePrintToDataBase() {
         this.create();
-        this.zipFile.generateAsync({type: 'blob'})
+        this.zipFile.generateAsync({ type: 'blob' })
             .then(blob => {
                 this.packageCreationService.savePackage(blob).subscribe(
                     bluePrintDetailModels => {
                         if (bluePrintDetailModels) {
                             const id = bluePrintDetailModels.toString().split('id')[1].split(':')[1].split('"')[1];
-                            this.toastService.info('package updated successfully ');
+                            this.toastService.info('Package Updated Successfully ');
                             this.isSaveEnabled = false;
                             this.router.navigate(['/packages/package/' + id]);
                             this.refreshCurrentPackage(id);
                         }
                     }, error => {
-                        this.toastService.error('error happened when editing ' + error.message);
+                        this.toastService.error('Error occured when editing ' + error.message);
                         console.log('Error -' + error.message);
+                    }, () => {
+                        this.ngxService.stop();
                     });
             });
     }
@@ -268,20 +208,25 @@ export class ConfigurationDashboardComponent extends ComponentCanDeactivate impl
     }
 
     downloadPackage(artifactName: string, artifactVersion: string) {
+        this.ngxService.start();
         this.configurationDashboardService.downloadResource(artifactName + '/' + artifactVersion).subscribe(response => {
-            const blob = new Blob([response], {type: 'application/octet-stream'});
+            const blob = new Blob([response], { type: 'application/octet-stream' });
             saveAs(blob, artifactName + '-' + artifactVersion + '-CBA.zip');
+
+        }, err => { }, () => {
+            this.ngxService.stop();
         });
     }
 
     deployCurrentPackage() {
+        this.ngxService.start();
         this.formTreeData();
         this.deployPackage();
 
     }
 
     goToDesignerMode(id) {
-        this.router.navigate(['/packages/designer', id, {actionName: this.customActionName}]);
+        this.router.navigate(['/packages/designer', id, { actionName: this.customActionName }]);
     }
 
     public dropped(files: NgxFileDropEntry[]) {
@@ -297,48 +242,64 @@ export class ConfigurationDashboardComponent extends ComponentCanDeactivate impl
     }
 
     textChanged($event: {}) {
-        this.packageCreationStore.addTopologyTemplate(this.vlbDefinition.topology_template);
+        this.cbaPackage.templateTopology.node_templates = this.designerState.template.node_templates;
+        this.cbaPackage.templateTopology.workflows = this.designerState.template.workflows;
+        this.cbaPackage.templateTopology.content = this.vlbDefinition.topology_template.content;
     }
 
     enrichBluePrint() {
-
+        this.ngxService.start();
+        this.packageCreationStore.addTopologyTemplate(this.cbaPackage.templateTopology);
         this.formTreeData();
         this.enrichPackage();
+        this.designerStore.clear();
+        this.packageCreationStore.clear();
     }
 
 
     private enrichPackage() {
         this.create();
-        this.zipFile.generateAsync({type: 'blob'})
+        this.zipFile.generateAsync({ type: 'blob' })
             .then(blob => {
                 this.packageCreationService.enrichPackage(blob).subscribe(response => {
                     console.log('success');
-                    const blobInfo = new Blob([response], {type: 'application/octet-stream'});
+                    const blobInfo = new Blob([response], { type: 'application/octet-stream' });
                     this.currentBlob = blobInfo;
                     this.packageCreationStore.clear();
-                    this.extractBlobToStore(this.currentBlob, this.viewedPackage);
+                    this.packageCreationExtractionService.extractBlobToStore(this.currentBlob);
                     this.isSaveEnabled = true;
-                    this.toastService.info('enriched successfully ');
+                    this.toastService.success('Enriched Done Successfully');
+                }, err => {
+                    this.handleError(err);
+                }, () => {
+                    this.ngxService.stop();
                 });
             }, error => {
-                this.toastService.error('error happened when enrich ' + error.message);
+                this.toastService.error('Error occured during enrichment process' + error.message);
                 console.error('Error -' + error.message);
+            }, () => {
+                this.ngxService.stop();
             });
     }
 
     private deployPackage() {
         this.create();
-        this.zipFile.generateAsync({type: 'blob'})
+        this.zipFile.generateAsync({ type: 'blob' })
             .then(blob => {
                 this.packageCreationService.deploy(blob).subscribe(response => {
-                    this.toastService.info('deployed successfully ');
+                    this.toastService.info('Package Deployed Successfully ');
                     const id = response.toString().split('id')[1].split(':')[1].split('"')[1];
                     this.isSaveEnabled = false;
                     this.router.navigate(['/packages/package/' + id]);
+                }, err => {
+                    this.handleError(err);
+                }, () => {
+                    this.ngxService.stop();
                 });
             }, error => {
-                this.toastService.error('error happened when deploying ' + error.message);
-                console.log('Error -' + error.message);
+                this.handleError(error);
+            }, () => {
+                this.ngxService.stop();
             });
     }
 
@@ -350,11 +311,35 @@ export class ConfigurationDashboardComponent extends ComponentCanDeactivate impl
         return this.isSaveEnabled;
     }
 
+    ngOnDestroy() {
+        this.ngUnsubscribe.next();
+        this.ngUnsubscribe.complete();
+    }
+
     checkSkipTypesOfAction() {
-        if (this.cbaPackage.templateTopology.node_templates && this.cbaPackage.templateTopology.workflows) {
+        console.log(this.cbaPackage);
+        if (this.cbaPackage.templateTopology && this.cbaPackage.templateTopology.node_templates
+            && this.cbaPackage.templateTopology.workflows) {
             this.goToDesignerMode(this.id);
         } else {
             this.dataTarget = '#exampleModalLong';
         }
     }
+
+    handleError(error) {
+        let errorMessage = '';
+        if (error.error instanceof ErrorEvent) {
+            // client-side error
+            errorMessage = `Error: ${error.error.message}`;
+        } else {
+            // server-side error
+            errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
+        }
+        this.toastService.error('Error occured when deploying ' + errorMessage);
+        console.log('Error -' + errorMessage);
+        this.ngxService.stop();
+        this.toastService.error('Error occured when deploying' + error.message);
+        return throwError(errorMessage);
+    }
 }
+