Revert "Renaming Files having BluePrint to have Blueprint"
[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                 this.ngxService.stop();
124             }, err => {
125                 this.ngxService.stop();
126             },
127             () => {
128                 //  this.ngxService.stop();
129             });
130     }
131
132     private downloadCBAPackage(bluePrintDetailModels: BluePrintDetailModel) {
133         this.configurationDashboardService.downloadResource(
134             this.viewedPackage.artifactName + '/' + this.viewedPackage.artifactVersion).subscribe(response => {
135                 const blob = new Blob([response], { type: 'application/octet-stream' });
136                 this.currentBlob = blob;
137                 this.packageCreationExtractionService.extractBlobToStore(blob);
138             }, err => {
139                 console.log(err);
140                 this.ngxService.stop();
141             },
142                 () => {
143                     this.ngxService.stop();
144                 });
145     }
146
147     editBluePrint() {
148         this.ngxService.start();
149         this.configurationDashboardService.deletePackage(this.packageId).subscribe(res => {
150             this.formTreeData();
151             this.saveBluePrintToDataBase();
152
153         });
154     }
155
156     private formTreeData() {
157         FilesContent.clear();
158         let packageCreationModes: PackageCreationModes;
159         this.cbaPackage = PackageCreationModes.mapModeType(this.cbaPackage);
160         this.cbaPackage.metaData = PackageCreationModes.setEntryPoint(this.cbaPackage.metaData);
161         packageCreationModes = PackageCreationBuilder.getCreationMode(this.cbaPackage);
162         packageCreationModes.execute(this.cbaPackage, this.packageCreationUtils);
163         this.filesData.push(this.folder.TREE_DATA);
164     }
165
166     saveMetaData() {
167         this.metadataTabComponent.saveMetaDataToStore();
168     }
169
170     saveBluePrintToDataBase() {
171         this.create();
172         this.zipFile.generateAsync({ type: 'blob' })
173             .then(blob => {
174                 this.packageCreationService.savePackage(blob).subscribe(
175                     bluePrintDetailModels => {
176                         if (bluePrintDetailModels) {
177                             const id = bluePrintDetailModels.toString().split('id')[1].split(':')[1].split('"')[1];
178                             this.toastService.success('Package Updated Successfully ');
179                             this.isSaveEnabled = false;
180                             this.router.navigate(['/packages/package/' + id]);
181                             this.refreshCurrentPackage(id);
182                         }
183                     }, error => {
184                         this.toastService.error('Error occured when editing ' + error.message);
185                         console.log('Error -' + error.message);
186                     }, () => {
187                         this.ngxService.stop();
188                     });
189             });
190     }
191
192     deletePackage() {
193         this.configurationDashboardService.deletePackage(this.id).subscribe(res => {
194             console.log('Deleted');
195             console.log(res);
196             this.isSaveEnabled = false;
197             this.router.navigate(['/packages']);
198         }, err => {
199             console.log(err);
200         });
201     }
202
203     create() {
204         this.zipFile = new JSZip();
205         FilesContent.getMapOfFilesNamesAndContent().forEach((value, key) => {
206             this.zipFile.folder(key.split('/')[0]);
207             this.zipFile.file(key, value);
208         });
209
210     }
211
212     discardChanges() {
213         this.refreshCurrentPackage();
214     }
215
216     downloadPackage(artifactName: string, artifactVersion: string) {
217         this.ngxService.start();
218         this.configurationDashboardService.downloadResource(artifactName + '/' + artifactVersion).subscribe(response => {
219             const blob = new Blob([response], { type: 'application/octet-stream' });
220             saveAs(blob, artifactName + '-' + artifactVersion + '-CBA.zip');
221
222         }, err => { }, () => {
223             this.ngxService.stop();
224         });
225     }
226
227     deployCurrentPackage() {
228         this.ngxService.start();
229         this.formTreeData();
230         this.deployPackage();
231
232     }
233
234     goToDesignerMode(id) {
235         this.router.navigate(['/packages/designer', id, { actionName: this.customActionName }]);
236     }
237
238     public dropped(files: NgxFileDropEntry[]) {
239
240     }
241
242     public fileOver(event) {
243         console.log(event);
244     }
245
246     public fileLeave(event) {
247         console.log(event);
248     }
249
250     textChanged($event: {}) {
251         this.cbaPackage.templateTopology.node_templates = this.designerState.template.node_templates;
252         this.cbaPackage.templateTopology.workflows = this.designerState.template.workflows;
253         this.cbaPackage.templateTopology.content = this.vlbDefinition.topology_template.content;
254     }
255
256     enrichBluePrint() {
257         this.ngxService.start();
258         this.packageCreationStore.addTopologyTemplate(this.cbaPackage.templateTopology);
259         this.formTreeData();
260         this.enrichPackage();
261     }
262
263
264     private enrichPackage() {
265         this.create();
266         this.zipFile.generateAsync({ type: 'blob' })
267             .then(blob => {
268                 this.packageCreationService.enrichPackage(blob).subscribe(response => {
269                     console.log('success');
270                     const blobInfo = new Blob([response], { type: 'application/octet-stream' });
271                     this.currentBlob = blobInfo;
272                     this.packageCreationStore.clear();
273                     this.packageCreationExtractionService.extractBlobToStore(this.currentBlob);
274                     this.isSaveEnabled = true;
275                     this.toastService.success('Enriched Done Successfully');
276                 }, err => {
277                     this.handleError(err);
278                 }, () => {
279                     this.ngxService.stop();
280                 });
281             }, error => {
282                 this.toastService.error('Error occured during enrichment process' + error.message);
283                 console.error('Error -' + error.message);
284             }, () => {
285                 this.ngxService.stop();
286             });
287     }
288
289     private deployPackage() {
290         this.create();
291         this.zipFile.generateAsync({ type: 'blob' })
292             .then(blob => {
293                 this.packageCreationService.deploy(blob).subscribe(response => {
294                     this.toastService.info('Package Deployed Successfully ');
295                     const id = response.toString().split('id')[1].split(':')[1].split('"')[1];
296                     this.isSaveEnabled = false;
297                     this.router.navigate(['/packages/package/' + id]);
298                 }, err => {
299                     this.handleError(err);
300                 }, () => {
301                     this.ngxService.stop();
302                 });
303             }, error => {
304                 this.handleError(error);
305             }, () => {
306                 this.ngxService.stop();
307             });
308     }
309
310     clickEvent() {
311         this.isSaveEnabled = true;
312     }
313
314     canDeactivate(): boolean {
315         return this.isSaveEnabled;
316     }
317
318     ngOnDestroy() {
319         this.ngUnsubscribe.next();
320         this.ngUnsubscribe.complete();
321     }
322
323     checkSkipTypesOfAction() {
324         console.log(this.cbaPackage);
325         if (this.cbaPackage.templateTopology && this.cbaPackage.templateTopology.node_templates
326             && this.cbaPackage.templateTopology.workflows) {
327             this.goToDesignerMode(this.id);
328         } else {
329             this.dataTarget = '#exampleModalLong';
330         }
331     }
332
333     handleError(error) {
334         let errorMessage = '';
335         if (error.error instanceof ErrorEvent) {
336             // client-side error
337             errorMessage = `Error: ${error.error.message}`;
338         } else {
339             // server-side error
340             errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
341         }
342         this.toastService.error('Error occured when deploying ' + errorMessage);
343         console.log('Error -' + errorMessage);
344         this.ngxService.stop();
345         this.toastService.error('Error occured when deploying' + error.message);
346         return throwError(errorMessage);
347     }
348 }
349