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
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     packageId: any;
56
57     constructor(
58         private route: ActivatedRoute,
59         private configurationDashboardService: ConfigurationDashboardService,
60         private packageCreationStore: PackageCreationStore,
61         private packageCreationService: PackageCreationService,
62         private packageCreationUtils: PackageCreationUtils,
63         private router: Router,
64         private designerStore: DesignerStore,
65         private toastService: ToastrService,
66         private ngxService: NgxUiLoaderService,
67         private packageCreationExtractionService: PackageCreationExtractionService,
68         private activatedRoute: ActivatedRoute,
69     ) {
70         super();
71
72
73     }
74
75     ngOnInit() {
76         this.ngxService.start();
77         this.vlbDefinition.topology_template = new TemplateTopology();
78         this.packageCreationStore.state$
79             .pipe(distinctUntilChanged((a: any, b: any) => JSON.stringify(a) === JSON.stringify(b)),
80                 takeUntil(this.ngUnsubscribe))
81             .subscribe(
82                 cbaPackage => {
83                     this.cbaPackage = cbaPackage;
84                 });
85         this.designerStore.state$.pipe(
86             distinctUntilChanged((a: any, b: any) => JSON.stringify(a) === JSON.stringify(b)),
87             takeUntil(this.ngUnsubscribe))
88             .subscribe(state => {
89                 this.designerState = state;
90                 this.vlbDefinition.topology_template.content = this.packageCreationUtils.transformToJson(state.template);
91             });
92         this.elementRef.nativeElement.focus();
93         this.refreshCurrentPackage();
94         const regexp = RegExp(this.versionPattern);
95         if (this.cbaPackage && this.cbaPackage.metaData && this.cbaPackage.metaData.description
96             && this.cbaPackage.metaData.name && this.cbaPackage.metaData.version &&
97             regexp.test(this.cbaPackage.metaData.version)) {
98             if (!this.metadataClasses.includes('complete')) {
99                 this.metadataClasses += ' complete';
100             }
101         } else {
102             this.metadataClasses = this.metadataClasses.replace('complete', '');
103             this.isSaveEnabled = false;
104         }
105         this.activatedRoute.paramMap.subscribe(res => {
106             this.packageId = res.get('id');
107         });
108
109
110     }
111
112     private refreshCurrentPackage(id?) {
113         this.id = this.route.snapshot.paramMap.get('id');
114         console.log(this.id);
115         id = id ? id : this.id;
116         this.configurationDashboardService.getPagedPackages(id).subscribe(
117             (bluePrintDetailModels) => {
118                 if (bluePrintDetailModels) {
119                     this.viewedPackage = bluePrintDetailModels[0];
120                     this.downloadCBAPackage(bluePrintDetailModels);
121                     this.packageCreationStore.clear();
122                 }
123             }, err => { },
124             () => {
125                 //  this.ngxService.stop();
126             });
127     }
128
129     private downloadCBAPackage(bluePrintDetailModels: BluePrintDetailModel) {
130         this.configurationDashboardService.downloadResource(
131             this.viewedPackage.artifactName + '/' + this.viewedPackage.artifactVersion).subscribe(response => {
132                 const blob = new Blob([response], { type: 'application/octet-stream' });
133                 this.currentBlob = blob;
134                 this.packageCreationExtractionService.extractBlobToStore(blob);
135             }, err => { },
136                 () => {
137                     this.ngxService.stop();
138                 });
139     }
140
141     editBluePrint() {
142         this.ngxService.start();
143         this.configurationDashboardService.deletePackage(this.packageId).subscribe(res => {
144             this.formTreeData();
145             this.saveBluePrintToDataBase();
146
147         });
148     }
149
150     private formTreeData() {
151         FilesContent.clear();
152         let packageCreationModes: PackageCreationModes;
153         this.cbaPackage = PackageCreationModes.mapModeType(this.cbaPackage);
154         this.cbaPackage.metaData = PackageCreationModes.setEntryPoint(this.cbaPackage.metaData);
155         packageCreationModes = PackageCreationBuilder.getCreationMode(this.cbaPackage);
156         packageCreationModes.execute(this.cbaPackage, this.packageCreationUtils);
157         this.filesData.push(this.folder.TREE_DATA);
158     }
159
160     saveMetaData() {
161         this.metadataTabComponent.saveMetaDataToStore();
162     }
163
164     saveBluePrintToDataBase() {
165         this.create();
166         this.zipFile.generateAsync({ type: 'blob' })
167             .then(blob => {
168                 this.packageCreationService.savePackage(blob).subscribe(
169                     bluePrintDetailModels => {
170                         if (bluePrintDetailModels) {
171                             const id = bluePrintDetailModels.toString().split('id')[1].split(':')[1].split('"')[1];
172                             this.toastService.info('Package Updated Successfully ');
173                             this.isSaveEnabled = false;
174                             this.router.navigate(['/packages/package/' + id]);
175                             this.refreshCurrentPackage(id);
176                         }
177                     }, error => {
178                         this.toastService.error('Error occured when editing ' + error.message);
179                         console.log('Error -' + error.message);
180                     }, () => {
181                         this.ngxService.stop();
182                     });
183             });
184     }
185
186     deletePackage() {
187         this.configurationDashboardService.deletePackage(this.id).subscribe(res => {
188             console.log('Deleted');
189             console.log(res);
190             this.isSaveEnabled = false;
191             this.router.navigate(['/packages']);
192         }, err => {
193             console.log(err);
194         });
195     }
196
197     create() {
198         this.zipFile = new JSZip();
199         FilesContent.getMapOfFilesNamesAndContent().forEach((value, key) => {
200             this.zipFile.folder(key.split('/')[0]);
201             this.zipFile.file(key, value);
202         });
203
204     }
205
206     discardChanges() {
207         this.refreshCurrentPackage();
208     }
209
210     downloadPackage(artifactName: string, artifactVersion: string) {
211         this.ngxService.start();
212         this.configurationDashboardService.downloadResource(artifactName + '/' + artifactVersion).subscribe(response => {
213             const blob = new Blob([response], { type: 'application/octet-stream' });
214             saveAs(blob, artifactName + '-' + artifactVersion + '-CBA.zip');
215
216         }, err => { }, () => {
217             this.ngxService.stop();
218         });
219     }
220
221     deployCurrentPackage() {
222         this.ngxService.start();
223         this.formTreeData();
224         this.deployPackage();
225
226     }
227
228     goToDesignerMode(id) {
229         this.router.navigate(['/packages/designer', id, { actionName: this.customActionName }]);
230     }
231
232     public dropped(files: NgxFileDropEntry[]) {
233
234     }
235
236     public fileOver(event) {
237         console.log(event);
238     }
239
240     public fileLeave(event) {
241         console.log(event);
242     }
243
244     textChanged($event: {}) {
245         this.cbaPackage.templateTopology.node_templates = this.designerState.template.node_templates;
246         this.cbaPackage.templateTopology.workflows = this.designerState.template.workflows;
247         this.cbaPackage.templateTopology.content = this.vlbDefinition.topology_template.content;
248     }
249
250     enrichBluePrint() {
251         this.ngxService.start();
252         this.packageCreationStore.addTopologyTemplate(this.cbaPackage.templateTopology);
253         this.formTreeData();
254         this.enrichPackage();
255         this.designerStore.clear();
256         this.packageCreationStore.clear();
257     }
258
259
260     private enrichPackage() {
261         this.create();
262         this.zipFile.generateAsync({ type: 'blob' })
263             .then(blob => {
264                 this.packageCreationService.enrichPackage(blob).subscribe(response => {
265                     console.log('success');
266                     const blobInfo = new Blob([response], { type: 'application/octet-stream' });
267                     this.currentBlob = blobInfo;
268                     this.packageCreationStore.clear();
269                     this.packageCreationExtractionService.extractBlobToStore(this.currentBlob);
270                     this.isSaveEnabled = true;
271                     this.toastService.success('Enriched Done Successfully');
272                 }, err => {
273                     this.handleError(err);
274                 }, () => {
275                     this.ngxService.stop();
276                 });
277             }, error => {
278                 this.toastService.error('Error occured during enrichment process' + error.message);
279                 console.error('Error -' + error.message);
280             }, () => {
281                 this.ngxService.stop();
282             });
283     }
284
285     private deployPackage() {
286         this.create();
287         this.zipFile.generateAsync({ type: 'blob' })
288             .then(blob => {
289                 this.packageCreationService.deploy(blob).subscribe(response => {
290                     this.toastService.info('Package Deployed Successfully ');
291                     const id = response.toString().split('id')[1].split(':')[1].split('"')[1];
292                     this.isSaveEnabled = false;
293                     this.router.navigate(['/packages/package/' + id]);
294                 }, err => {
295                     this.handleError(err);
296                 }, () => {
297                     this.ngxService.stop();
298                 });
299             }, error => {
300                 this.handleError(error);
301             }, () => {
302                 this.ngxService.stop();
303             });
304     }
305
306     clickEvent() {
307         this.isSaveEnabled = true;
308     }
309
310     canDeactivate(): boolean {
311         return this.isSaveEnabled;
312     }
313
314     ngOnDestroy() {
315         this.ngUnsubscribe.next();
316         this.ngUnsubscribe.complete();
317     }
318
319     checkSkipTypesOfAction() {
320         console.log(this.cbaPackage);
321         if (this.cbaPackage.templateTopology && this.cbaPackage.templateTopology.node_templates
322             && this.cbaPackage.templateTopology.workflows) {
323             this.goToDesignerMode(this.id);
324         } else {
325             this.dataTarget = '#exampleModalLong';
326         }
327     }
328
329     handleError(error) {
330         let errorMessage = '';
331         if (error.error instanceof ErrorEvent) {
332             // client-side error
333             errorMessage = `Error: ${error.error.message}`;
334         } else {
335             // server-side error
336             errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
337         }
338         this.toastService.error('Error occured when deploying ' + errorMessage);
339         console.log('Error -' + errorMessage);
340         this.ngxService.stop();
341         this.toastService.error('Error occured when deploying' + error.message);
342         return throwError(errorMessage);
343     }
344 }
345