eb121e98e530927e486f659af8aa009b2ed1a3f8
[ccsdk/cds.git] /
1 import {Component, ElementRef, 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, MetaDataTabModel} 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, VlbDefinition} from '../package-creation/mapping-models/definitions/VlbDefinition';
10 import {CBAPackage, DslDefinition} 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
22 @Component({
23     selector: 'app-configuration-dashboard',
24     templateUrl: './configuration-dashboard.component.html',
25     styleUrls: ['./configuration-dashboard.component.css'],
26 })
27 export class ConfigurationDashboardComponent extends ComponentCanDeactivate implements OnInit {
28     viewedPackage: BluePrintDetailModel = new BluePrintDetailModel();
29     @ViewChild(MetadataTabComponent, {static: false})
30     metadataTabComponent: MetadataTabComponent;
31     public customActionName = '';
32
33     entryDefinitionKeys: string[] = ['template_tags', 'user-groups',
34         'author-email', 'template_version', 'template_name', 'template_author', 'template_description'];
35     @ViewChild('nameit', {static: true})
36     elementRef: ElementRef;
37     uploadedFiles = [];
38     zipFile: JSZip = new JSZip();
39     filesData: any = [];
40     folder: FolderNodeElement = new FolderNodeElement();
41     id: any;
42
43     currentBlob = new Blob();
44     vlbDefinition: VlbDefinition = new VlbDefinition();
45     isSaveEnabled = false;
46     versionPattern = '^(\\d+\\.)?(\\d+\\.)?(\\*|\\d+)$';
47     metadataClasses = 'nav-item nav-link active';
48     private cbaPackage: CBAPackage = new CBAPackage();
49     dataTarget: any = '';
50
51     constructor(
52         private route: ActivatedRoute,
53         private configurationDashboardService: ConfigurationDashboardService,
54         private packageCreationStore: PackageCreationStore,
55         private packageCreationService: PackageCreationService,
56         private packageCreationUtils: PackageCreationUtils,
57         private router: Router,
58         private designerStore: DesignerStore,
59         private toastService: ToastrService,
60         private packageCreationExtractionService: PackageCreationExtractionService
61     ) {
62         super();
63
64         this.packageCreationStore.state$.subscribe(
65             cbaPackage => {
66                 this.cbaPackage = cbaPackage;
67             });
68
69
70     }
71
72     ngOnInit() {
73         this.vlbDefinition.topology_template = new TemplateTopology();
74
75         this.elementRef.nativeElement.focus();
76         this.refreshCurrentPackage();
77         const regexp = RegExp(this.versionPattern);
78         if (this.cbaPackage && this.cbaPackage.metaData && this.cbaPackage.metaData.description
79             && this.cbaPackage.metaData.name && this.cbaPackage.metaData.version &&
80             regexp.test(this.cbaPackage.metaData.version)) {
81             if (!this.metadataClasses.includes('complete')) {
82                 this.metadataClasses += ' complete';
83             }
84         } else {
85             this.metadataClasses = this.metadataClasses.replace('complete', '');
86             this.isSaveEnabled = false;
87         }
88
89
90     }
91
92
93     private refreshCurrentPackage(id?) {
94         this.id = this.route.snapshot.paramMap.get('id');
95         console.log(this.id);
96         id = id ? id : this.id;
97         this.configurationDashboardService.getPagedPackages(id).subscribe(
98             (bluePrintDetailModels) => {
99                 if (bluePrintDetailModels) {
100                     this.viewedPackage = bluePrintDetailModels[0];
101                     this.downloadCBAPackage(bluePrintDetailModels);
102                     this.packageCreationStore.clear();
103                 }
104             });
105     }
106
107     private downloadCBAPackage(bluePrintDetailModels: BluePrintDetailModel) {
108         this.configurationDashboardService.downloadResource(
109             this.viewedPackage.artifactName + '/' + this.viewedPackage.artifactVersion).subscribe(response => {
110             const blob = new Blob([response], {type: 'application/octet-stream'});
111             this.currentBlob = blob;
112             this.extractBlobToStore(blob, this.viewedPackage);
113         });
114     }
115
116     private extractBlobToStore(blob: Blob, bluePrintDetailModel: BluePrintDetailModel) {
117         this.zipFile.loadAsync(blob).then((zip) => {
118             Object.keys(zip.files).forEach((filename) => {
119                 zip.files[filename].async('string').then((fileData) => {
120                     console.log(filename);
121                     if (fileData) {
122                         if (filename.includes('Scripts/')) {
123                             this.setScripts(filename, fileData);
124                         } else if (filename.includes('Templates/')) {
125                             if (filename.includes('-mapping.')) {
126                                 this.setMapping(filename, fileData);
127                             } else if (filename.includes('-template.')) {
128                                 this.setTemplates(filename, fileData);
129                             }
130
131                         } else if (filename.includes('Definitions/')) {
132                             this.setImports(filename, fileData, bluePrintDetailModel);
133                         } else if (filename.includes('TOSCA-Metadata/')) {
134                             const metaDataTabInfo: MetaDataTabModel = this.getMetaDataTabInfo(fileData);
135                             this.setMetaData(metaDataTabInfo, bluePrintDetailModel);
136                         }
137                     }
138                 });
139             });
140         });
141     }
142
143     setScripts(filename: string, fileData: any) {
144         this.packageCreationStore.addScripts(filename, fileData);
145     }
146
147     setImports(filename: string, fileData: any, bluePrintDetailModels: BluePrintDetailModel) {
148         console.log(filename);
149         if (filename.includes(bluePrintDetailModels.artifactName)) {
150             let definition = new VlbDefinition();
151             definition = fileData as VlbDefinition;
152             definition = JSON.parse(fileData);
153             const dslDefinition = new DslDefinition();
154             dslDefinition.content = this.packageCreationUtils.transformToJson(definition.dsl_definitions);
155             const mapOfCustomKeys = new Map<string, string>();
156             for (const metadataKey in definition.metadata) {
157                 if (!this.entryDefinitionKeys.includes(metadataKey + '')) {
158                     mapOfCustomKeys.set(metadataKey + '', definition.metadata[metadataKey + '']);
159                 }
160             }
161             this.packageCreationStore.changeDslDefinition(dslDefinition);
162             this.packageCreationStore.setCustomKeys(mapOfCustomKeys);
163             if (definition.topology_template) {
164                 const content = {};
165                 const workflow = 'workflows';
166                 content[workflow] = definition.topology_template.workflows;
167                 const nodeTemplates = 'node_templates';
168                 content[nodeTemplates] = definition.topology_template.node_templates;
169                 this.designerStore.saveSourceContent(JSON.stringify(content));
170                 this.packageCreationStore.addTopologyTemplate(definition.topology_template);
171             }
172
173         }
174         this.packageCreationStore.addDefinition(filename, fileData);
175
176     }
177
178     setTemplates(filename: string, fileData: any) {
179         this.packageCreationStore.addTemplate(filename, fileData);
180     }
181
182     setMapping(fileName: string, fileData: string) {
183         this.packageCreationStore.addMapping(fileName, fileData);
184     }
185
186     editBluePrint() {
187         this.configurationDashboardService.deletePackage(this.viewedPackage.id).subscribe(res => {
188             this.formTreeData();
189             this.saveBluePrintToDataBase();
190
191         });
192     }
193
194     private formTreeData() {
195         FilesContent.clear();
196         let packageCreationModes: PackageCreationModes;
197         this.cbaPackage = PackageCreationModes.mapModeType(this.cbaPackage);
198         this.cbaPackage.metaData = PackageCreationModes.setEntryPoint(this.cbaPackage.metaData);
199         packageCreationModes = PackageCreationBuilder.getCreationMode(this.cbaPackage);
200         packageCreationModes.execute(this.cbaPackage, this.packageCreationUtils);
201         this.filesData.push(this.folder.TREE_DATA);
202     }
203
204     setMetaData(metaDataObject: MetaDataTabModel, bluePrintDetailModel: BluePrintDetailModel) {
205         metaDataObject.description = bluePrintDetailModel.artifactDescription;
206         this.packageCreationStore.changeMetaData(metaDataObject);
207
208     }
209
210     saveMetaData() {
211         this.metadataTabComponent.saveMetaDataToStore();
212
213     }
214
215     getMetaDataTabInfo(fileData: string) {
216         const metaDataTabModel = new MetaDataTabModel();
217         const arrayOfLines = fileData.split('\n');
218         metaDataTabModel.entryFileName = arrayOfLines[3].split(':')[1];
219         metaDataTabModel.name = arrayOfLines[4].split(':')[1];
220         metaDataTabModel.version = arrayOfLines[5].split(':')[1];
221         metaDataTabModel.mode = arrayOfLines[6].split(':')[1];
222         metaDataTabModel.templateTags = new Set<string>(arrayOfLines[7].split(':')[1].split(','));
223         return metaDataTabModel;
224     }
225
226     saveBluePrintToDataBase() {
227         this.create();
228         this.zipFile.generateAsync({type: 'blob'})
229             .then(blob => {
230                 this.packageCreationService.savePackage(blob).subscribe(
231                     bluePrintDetailModels => {
232                         if (bluePrintDetailModels) {
233                             const id = bluePrintDetailModels.toString().split('id')[1].split(':')[1].split('"')[1];
234                             this.toastService.info('package updated successfully ');
235                             this.isSaveEnabled = false;
236                             this.router.navigate(['/packages/package/' + id]);
237                             this.refreshCurrentPackage(id);
238                         }
239                     }, error => {
240                         this.toastService.error('error happened when editing ' + error.message);
241                         console.log('Error -' + error.message);
242                     });
243             });
244     }
245
246     deletePackage() {
247         this.configurationDashboardService.deletePackage(this.id).subscribe(res => {
248             console.log('Deleted');
249             console.log(res);
250             this.isSaveEnabled = false;
251             this.router.navigate(['/packages']);
252         }, err => {
253             console.log(err);
254         });
255     }
256
257     create() {
258         this.zipFile = new JSZip();
259         FilesContent.getMapOfFilesNamesAndContent().forEach((value, key) => {
260             this.zipFile.folder(key.split('/')[0]);
261             this.zipFile.file(key, value);
262         });
263
264     }
265
266     discardChanges() {
267         this.refreshCurrentPackage();
268     }
269
270     downloadPackage(artifactName: string, artifactVersion: string) {
271         this.configurationDashboardService.downloadResource(artifactName + '/' + artifactVersion).subscribe(response => {
272             const blob = new Blob([response], {type: 'application/octet-stream'});
273             saveAs(blob, artifactName + '-' + artifactVersion + '-CBA.zip');
274         });
275     }
276
277     deployCurrentPackage() {
278         this.formTreeData();
279         this.deployPackage();
280
281     }
282
283     goToDesignerMode(id) {
284         this.router.navigate(['/packages/designer', id, {actionName: this.customActionName}]);
285     }
286
287     public dropped(files: NgxFileDropEntry[]) {
288
289     }
290
291     public fileOver(event) {
292         console.log(event);
293     }
294
295     public fileLeave(event) {
296         console.log(event);
297     }
298
299     textChanged($event: {}) {
300         this.packageCreationStore.addTopologyTemplate(this.vlbDefinition.topology_template);
301     }
302
303     enrichBluePrint() {
304
305         this.formTreeData();
306         this.enrichPackage();
307     }
308
309
310     private enrichPackage() {
311         this.create();
312         this.zipFile.generateAsync({type: 'blob'})
313             .then(blob => {
314                 this.packageCreationService.enrichPackage(blob).subscribe(response => {
315                     console.log('success');
316                     const blobInfo = new Blob([response], {type: 'application/octet-stream'});
317                     this.currentBlob = blobInfo;
318                     this.packageCreationStore.clear();
319                     this.extractBlobToStore(this.currentBlob, this.viewedPackage);
320                     this.isSaveEnabled = true;
321                     this.toastService.info('enriched successfully ');
322                 });
323             }, error => {
324                 this.toastService.error('error happened when enrich ' + error.message);
325                 console.error('Error -' + error.message);
326             });
327     }
328
329     private deployPackage() {
330         this.create();
331         this.zipFile.generateAsync({type: 'blob'})
332             .then(blob => {
333                 this.packageCreationService.deploy(blob).subscribe(response => {
334                     this.toastService.info('deployed successfully ');
335                     const id = response.toString().split('id')[1].split(':')[1].split('"')[1];
336                     this.isSaveEnabled = false;
337                     this.router.navigate(['/packages/package/' + id]);
338                 });
339             }, error => {
340                 this.toastService.error('error happened when deploying ' + error.message);
341                 console.log('Error -' + error.message);
342             });
343     }
344
345     clickEvent() {
346         this.isSaveEnabled = true;
347     }
348
349     canDeactivate(): boolean {
350         return this.isSaveEnabled;
351     }
352
353     checkSkipTypesOfAction() {
354         if (this.cbaPackage.templateTopology.node_templates && this.cbaPackage.templateTopology.workflows) {
355             this.goToDesignerMode(this.id);
356         } else {
357             this.dataTarget = '#exampleModalLong';
358         }
359     }
360 }