96e54d953c3b3f8a9b3de94aa29488eeb7ac7eec
[ccsdk/cds.git] / cds-ui / designer-client / src / app / modules / feature-modules / packages / configuration-dashboard / configuration-dashboard.component.ts
1 import { Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
2 import { ActivatedRoute, Router } from '@angular/router';
3 import { BluePrintDetailModel } from '../model/BluePrint.detail.model';
4 import { PackageCreationStore } from '../package-creation/package-creation.store';
5 import { FilesContent, FolderNodeElement } from '../package-creation/mapping-models/metadata/MetaDataTab.model';
6 import { MetadataTabComponent } from '../package-creation/metadata-tab/metadata-tab.component';
7 import * as JSZip from 'jszip';
8 import { ConfigurationDashboardService } from './configuration-dashboard.service';
9 import { TemplateTopology, CBADefinition } from '../package-creation/mapping-models/definitions/CBADefinition';
10 import { CBAPackage } from '../package-creation/mapping-models/CBAPacakge.model';
11 import { PackageCreationUtils } from '../package-creation/package-creation.utils';
12 import { PackageCreationModes } from '../package-creation/creationModes/PackageCreationModes';
13 import { PackageCreationBuilder } from '../package-creation/creationModes/PackageCreationBuilder';
14 import { saveAs } from 'file-saver';
15 import { DesignerStore } from '../designer/designer.store';
16 import { ToastrService } from 'ngx-toastr';
17 import { NgxFileDropEntry } from 'ngx-file-drop';
18 import { PackageCreationService } from '../package-creation/package-creation.service';
19 import { ComponentCanDeactivate } from '../../../../common/core/canDactivate/ComponentCanDeactivate';
20 import { PackageCreationExtractionService } from '../package-creation/package-creation-extraction.service';
21 import { distinctUntilChanged, takeUntil } from 'rxjs/operators';
22 import { Subject, throwError } from 'rxjs';
23 import { NgxUiLoaderService } from 'ngx-ui-loader';
24
25 @Component({
26     selector: 'app-configuration-dashboard',
27     templateUrl: './configuration-dashboard.component.html',
28     styleUrls: ['./configuration-dashboard.component.css'],
29 })
30 export class ConfigurationDashboardComponent extends ComponentCanDeactivate implements OnInit, OnDestroy {
31     viewedPackage: BluePrintDetailModel = new BluePrintDetailModel();
32     @ViewChild(MetadataTabComponent, { static: false })
33     metadataTabComponent: MetadataTabComponent;
34     public customActionName = '';
35
36     entryDefinitionKeys: string[] = ['template_tags', 'user-groups',
37         'author-email', 'template_version', 'template_name', 'template_author', 'template_description'];
38     @ViewChild('nameit', { static: true })
39     elementRef: ElementRef;
40     uploadedFiles = [];
41     zipFile: JSZip = new JSZip();
42     filesData: any = [];
43     folder: FolderNodeElement = new FolderNodeElement();
44     id: any;
45
46     currentBlob = new Blob();
47     vlbDefinition: CBADefinition = new CBADefinition();
48     isSaveEnabled = false;
49     versionPattern = '^(\\d+\\.)?(\\d+\\.)?(\\*|\\d+)$';
50     metadataClasses = 'nav-item nav-link active';
51     private cbaPackage: CBAPackage = new CBAPackage();
52     dataTarget: any = '';
53     ngUnsubscribe = new Subject();
54     private designerState: any;
55
56     constructor(
57         private route: ActivatedRoute,
58         private configurationDashboardService: ConfigurationDashboardService,
59         private packageCreationStore: PackageCreationStore,
60         private packageCreationService: PackageCreationService,
61         private packageCreationUtils: PackageCreationUtils,
62         private router: Router,
63         private designerStore: DesignerStore,
64         private toastService: ToastrService,
65         private ngxService: NgxUiLoaderService,
66         private packageCreationExtractionService: PackageCreationExtractionService
67     ) {
68         super();
69
70
71     }
72
73     ngOnInit() {
74         this.ngxService.start();
75         this.vlbDefinition.topology_template = new TemplateTopology();
76         this.packageCreationStore.state$
77             .pipe(distinctUntilChanged((a: any, b: any) => JSON.stringify(a) === JSON.stringify(b)),
78                 takeUntil(this.ngUnsubscribe))
79             .subscribe(
80                 cbaPackage => {
81                     this.cbaPackage = cbaPackage;
82                 });
83         this.designerStore.state$.pipe(
84             distinctUntilChanged((a: any, b: any) => JSON.stringify(a) === JSON.stringify(b)),
85             takeUntil(this.ngUnsubscribe))
86             .subscribe(state => {
87                 this.designerState = state;
88                 this.vlbDefinition.topology_template.content = this.packageCreationUtils.transformToJson(state.template);
89             });
90         this.elementRef.nativeElement.focus();
91         this.refreshCurrentPackage();
92         const regexp = RegExp(this.versionPattern);
93         if (this.cbaPackage && this.cbaPackage.metaData && this.cbaPackage.metaData.description
94             && this.cbaPackage.metaData.name && this.cbaPackage.metaData.version &&
95             regexp.test(this.cbaPackage.metaData.version)) {
96             if (!this.metadataClasses.includes('complete')) {
97                 this.metadataClasses += ' complete';
98             }
99         } else {
100             this.metadataClasses = this.metadataClasses.replace('complete', '');
101             this.isSaveEnabled = false;
102         }
103
104
105     }
106
107     private refreshCurrentPackage(id?) {
108         this.id = this.route.snapshot.paramMap.get('id');
109         console.log(this.id);
110         id = id ? id : this.id;
111         this.configurationDashboardService.getPagedPackages(id).subscribe(
112             (bluePrintDetailModels) => {
113                 if (bluePrintDetailModels) {
114                     this.viewedPackage = bluePrintDetailModels[0];
115                     this.downloadCBAPackage(bluePrintDetailModels);
116                     this.packageCreationStore.clear();
117                 }
118             }, err => { },
119             () => {
120                 //  this.ngxService.stop();
121             });
122     }
123
124     private downloadCBAPackage(bluePrintDetailModels: BluePrintDetailModel) {
125         this.configurationDashboardService.downloadResource(
126             this.viewedPackage.artifactName + '/' + this.viewedPackage.artifactVersion).subscribe(response => {
127                 const blob = new Blob([response], { type: 'application/octet-stream' });
128                 this.currentBlob = blob;
129                 this.packageCreationExtractionService.extractBlobToStore(blob);
130             }, err => { },
131                 () => {
132                     this.ngxService.stop();
133                 });
134     }
135
136     editBluePrint() {
137         this.ngxService.start();
138         this.configurationDashboardService.deletePackage(this.viewedPackage.id).subscribe(res => {
139             this.formTreeData();
140             this.saveBluePrintToDataBase();
141
142         });
143     }
144
145     private formTreeData() {
146         FilesContent.clear();
147         let packageCreationModes: PackageCreationModes;
148         this.cbaPackage = PackageCreationModes.mapModeType(this.cbaPackage);
149         this.cbaPackage.metaData = PackageCreationModes.setEntryPoint(this.cbaPackage.metaData);
150         packageCreationModes = PackageCreationBuilder.getCreationMode(this.cbaPackage);
151         packageCreationModes.execute(this.cbaPackage, this.packageCreationUtils);
152         this.filesData.push(this.folder.TREE_DATA);
153     }
154
155     saveMetaData() {
156         this.metadataTabComponent.saveMetaDataToStore();
157     }
158
159     saveBluePrintToDataBase() {
160         this.create();
161         this.zipFile.generateAsync({ type: 'blob' })
162             .then(blob => {
163                 this.packageCreationService.savePackage(blob).subscribe(
164                     bluePrintDetailModels => {
165                         if (bluePrintDetailModels) {
166                             const id = bluePrintDetailModels.toString().split('id')[1].split(':')[1].split('"')[1];
167                             this.toastService.info('package updated successfully ');
168                             this.isSaveEnabled = false;
169                             this.router.navigate(['/packages/package/' + id]);
170                             this.refreshCurrentPackage(id);
171                         }
172                     }, error => {
173                         this.toastService.error('error happened when editing ' + error.message);
174                         console.log('Error -' + error.message);
175                     }, () => {
176                         this.ngxService.stop();
177                     });
178             });
179     }
180
181     deletePackage() {
182         this.configurationDashboardService.deletePackage(this.id).subscribe(res => {
183             console.log('Deleted');
184             console.log(res);
185             this.isSaveEnabled = false;
186             this.router.navigate(['/packages']);
187         }, err => {
188             console.log(err);
189         });
190     }
191
192     create() {
193         this.zipFile = new JSZip();
194         FilesContent.getMapOfFilesNamesAndContent().forEach((value, key) => {
195             this.zipFile.folder(key.split('/')[0]);
196             this.zipFile.file(key, value);
197         });
198
199     }
200
201     discardChanges() {
202         this.refreshCurrentPackage();
203     }
204
205     downloadPackage(artifactName: string, artifactVersion: string) {
206         this.ngxService.start();
207         this.configurationDashboardService.downloadResource(artifactName + '/' + artifactVersion).subscribe(response => {
208             const blob = new Blob([response], { type: 'application/octet-stream' });
209             saveAs(blob, artifactName + '-' + artifactVersion + '-CBA.zip');
210
211         }, err => { }, () => {
212             this.ngxService.stop();
213         });
214     }
215
216     deployCurrentPackage() {
217         this.ngxService.start();
218         this.formTreeData();
219         this.deployPackage();
220
221     }
222
223     goToDesignerMode(id) {
224         this.router.navigate(['/packages/designer', id, { actionName: this.customActionName }]);
225     }
226
227     public dropped(files: NgxFileDropEntry[]) {
228
229     }
230
231     public fileOver(event) {
232         console.log(event);
233     }
234
235     public fileLeave(event) {
236         console.log(event);
237     }
238
239     textChanged($event: {}) {
240         this.cbaPackage.templateTopology.node_templates = this.designerState.template.node_templates;
241         this.cbaPackage.templateTopology.workflows = this.designerState.template.workflows;
242         this.cbaPackage.templateTopology.content = this.vlbDefinition.topology_template.content;
243     }
244
245     enrichBluePrint() {
246         this.ngxService.start();
247         this.packageCreationStore.addTopologyTemplate(this.cbaPackage.templateTopology);
248         this.formTreeData();
249         this.enrichPackage();
250         this.designerStore.clear();
251         this.packageCreationStore.clear();
252     }
253
254
255     private enrichPackage() {
256         this.create();
257         this.zipFile.generateAsync({ type: 'blob' })
258             .then(blob => {
259                 this.packageCreationService.enrichPackage(blob).subscribe(response => {
260                     console.log('success');
261                     const blobInfo = new Blob([response], { type: 'application/octet-stream' });
262                     this.currentBlob = blobInfo;
263                     this.packageCreationStore.clear();
264                     this.packageCreationExtractionService.extractBlobToStore(this.currentBlob);
265                     this.isSaveEnabled = true;
266                     this.toastService.info('enriched successfully ');
267                 }, err => {
268                     this.handleError(err);
269                 }, () => {
270                     this.ngxService.stop();
271                 });
272             }, error => {
273                 this.toastService.error('error happened when enrich ' + error.message);
274                 console.error('Error -' + error.message);
275             }, () => {
276                 this.ngxService.stop();
277             });
278     }
279
280     private deployPackage() {
281         this.create();
282         this.zipFile.generateAsync({ type: 'blob' })
283             .then(blob => {
284                 this.packageCreationService.deploy(blob).subscribe(response => {
285                     this.toastService.info('deployed successfully ');
286                     const id = response.toString().split('id')[1].split(':')[1].split('"')[1];
287                     this.isSaveEnabled = false;
288                     this.router.navigate(['/packages/package/' + id]);
289                 }, err => {
290                     this.handleError(err);
291                 }, () => {
292                     this.ngxService.stop();
293                 });
294             }, error => {
295                 this.handleError(error);
296             }, () => {
297                 this.ngxService.stop();
298             });
299     }
300
301     clickEvent() {
302         this.isSaveEnabled = true;
303     }
304
305     canDeactivate(): boolean {
306         return this.isSaveEnabled;
307     }
308
309     ngOnDestroy() {
310         this.ngUnsubscribe.next();
311         this.ngUnsubscribe.complete();
312     }
313
314     checkSkipTypesOfAction() {
315         console.log(this.cbaPackage);
316         if (this.cbaPackage.templateTopology && this.cbaPackage.templateTopology.node_templates
317             && this.cbaPackage.templateTopology.workflows) {
318             this.goToDesignerMode(this.id);
319         } else {
320             this.dataTarget = '#exampleModalLong';
321         }
322     }
323
324     handleError(error) {
325         let errorMessage = '';
326         if (error.error instanceof ErrorEvent) {
327             // client-side error
328             errorMessage = `Error: ${error.error.message}`;
329         } else {
330             // server-side error
331             errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
332         }
333         this.toastService.error('error happened when deploying ' + errorMessage);
334         console.log('Error -' + errorMessage);
335         this.ngxService.stop();
336         this.toastService.error('error happened when deploying' + error.message);
337         return throwError(errorMessage);
338     }
339 }
340