added svcapi ui and camunda code
[it/otf.git] / otf-frontend / client / src / app / shared / modules / create-test-instance-form / create-test-instance-form.component.ts
1 /*  Copyright (c) 2019 AT&T Intellectual Property.                             #\r
2 #                                                                              #\r
3 #   Licensed under the Apache License, Version 2.0 (the "License");            #\r
4 #   you may not use this file except in compliance with the License.           #\r
5 #   You may obtain a copy of the License at                                    #\r
6 #                                                                              #\r
7 #       http://www.apache.org/licenses/LICENSE-2.0                             #\r
8 #                                                                              #\r
9 #   Unless required by applicable law or agreed to in writing, software        #\r
10 #   distributed under the License is distributed on an "AS IS" BASIS,          #\r
11 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #\r
12 #   See the License for the specific language governing permissions and        #\r
13 #   limitations under the License.                                             #\r
14 ##############################################################################*/\r
15 \r
16 \r
17 import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';\r
18 import 'codemirror/mode/yaml/yaml.js';\r
19 import { TestInstanceService } from '../../services/test-instance.service';\r
20 import { TestDefinitionService } from '../../services/test-definition.service';\r
21 import { SchedulingService } from '../../services/scheduling.service';\r
22 import { SelectStrategyModalComponent } from '../select-strategy-modal/select-strategy-modal.component';\r
23 import { MatDialog, MatSnackBar } from '@angular/material';\r
24 import { AlertModalComponent } from '../alert-modal/alert-modal.component';\r
25 import { Router } from '@angular/router';\r
26 import { AlertSnackbarComponent } from '../alert-snackbar/alert-snackbar.component';\r
27 import { ListService } from 'app/shared/services/list.service';\r
28 import { FileUploader, FileItem, ParsedResponseHeaders } from 'ng2-file-upload';\r
29 import { HttpClient, HttpHeaders } from "@angular/common/http";\r
30 import { AppGlobals } from "../../../app.global";\r
31 import { CookieService } from "ngx-cookie-service";\r
32 import * as  YAML from '../../../../../../node_modules/yamljs/lib/Yaml';\r
33 import 'codemirror/mode/javascript/javascript.js';\r
34 import beautify from 'json-beautify';\r
35 import { WorkflowRequest } from './instance.class';\r
36 import { PfloInputClass } from './instance.class';\r
37 import { GroupService } from 'app/shared/services/group.service';\r
38 import { ExecuteService } from 'app/shared/services/execute.service';\r
39 \r
40 const URL = AppGlobals.baseAPIUrl + 'files';\r
41 \r
42 \r
43 @Component({\r
44   selector: 'app-create-test-instance-form',\r
45   templateUrl: './create-test-instance-form.component.pug',\r
46   styleUrls: ['./create-test-instance-form.component.scss']\r
47 })\r
48 export class CreateTestInstanceFormComponent implements OnInit {\r
49   yaml;\r
50   //Variable sent between modules\r
51   @Input() public existingInstance: any;\r
52 \r
53   @Output() public childEvent = new EventEmitter();\r
54   public dataTemplate: any;\r
55   public configTemplate: any;\r
56 \r
57   public codeConfig = {\r
58     mode: "yaml",\r
59     theme: "eclipse",\r
60     lineNumbers: true\r
61   };\r
62 \r
63   public codeJsonConfig = {\r
64     mode: "application/json",\r
65     theme: "eclipse",\r
66     lineNumbers: true\r
67   }\r
68 \r
69   public testDefinition;\r
70   public testInstance;\r
71   public createResult;\r
72   public selectedDefinition;\r
73   public errorCount = 0;\r
74   public executionFailed = false;\r
75   public editMode = false;\r
76   public httpOptions;\r
77   public selectedBpmn;\r
78   public uploader: FileUploader;\r
79   public isZip = true;\r
80   public scriptFiles = [];\r
81   public uploaders = {};\r
82   public vthInput = {};\r
83   public pfloInput = {};\r
84   public argsToAdd = {};\r
85   public vthInputYaml = {};\r
86   public displayYAML = false;\r
87   public testHeadYAML = false;\r
88   public testHeadNames = {};\r
89   public tiNameLookup = {};\r
90   public instances;\r
91   public search;\r
92   public instanceAdded;\r
93   \r
94 \r
95   public uploadOptions = {\r
96     url: AppGlobals.baseAPIUrl + 'file-transfer',\r
97     authTokenHeader: 'Authorization',\r
98     authToken: 'Bearer ' + JSON.parse(this.cookie.get('access_token'))\r
99   };\r
100 \r
101   // , private http: HttpClient, private Params: ParamsService, private cookie: CookieService\r
102   constructor(private router: Router, private list: ListService, private dialog: MatDialog, private execute: ExecuteService, private testInstanceService: TestInstanceService, private testDefinitionService: TestDefinitionService, private snack: MatSnackBar, private http: HttpClient, private cookie: CookieService, private groupService: GroupService) {\r
103     this.http = http;\r
104     this.cookie = cookie;\r
105     // this.httpOptions = {\r
106     //     headers: new HttpHeaders({ \r
107     //       'Content-Type': 'application/json',\r
108     //       'Authorization': 'Bearer ' + JSON.parse(this.cookie.get('access_token'))\r
109     //     })\r
110     //   };\r
111   }\r
112   // testingSelect(){\r
113   //   console.log(this.selectedBpmn);\r
114   // }\r
115   myFilter(bpmn) {\r
116     return bpmn.isDeployed;\r
117   }\r
118   ngOnInit() {\r
119     this.search = {};\r
120     this.search.testInstanceName = '';\r
121     this.testInstance = {};\r
122     this.selectedDefinition = {};\r
123     this.selectedBpmn = {};\r
124     this.testInstance.useLatestTestDefinition = true;\r
125     this.testInstance.simulationVthInput = {};\r
126     let currentGroup;\r
127     //options required for the file uploader\r
128     currentGroup = this.groupService.getGroup();\r
129     this.groupService.groupChange().subscribe(group => {\r
130       currentGroup = group;\r
131     });\r
132     \r
133     this.testInstanceService.find({\r
134       groupId: currentGroup['_id'],\r
135       $limit: -1,\r
136       $sort: {\r
137         createdAt: -1,\r
138       },\r
139       $select: ['testInstanceName']\r
140     }).subscribe((result) => {\r
141       this.instances = result;\r
142       for(let i = 0; i < this.instances.length; i++){\r
143         this.instances[i].isSelected = false;\r
144       }\r
145     })\r
146 \r
147     //File Uploaders\r
148     //this.uploader = new FileUploader(uploadOptions);\r
149     //if the user is using this page for editing an existing instance\r
150     if (this.existingInstance) {\r
151       //console.log(this.existingInstance)\r
152       if (this.existingInstance.testInstance) {\r
153         this.testInstance = this.existingInstance.testInstance;\r
154         this.selectedDefinition = this.existingInstance.testInstance['testDefinitionId'];\r
155         \r
156         this.convertSimulationVth('string');\r
157         console.log(this.testInstance);\r
158 \r
159         //set the bpmn to the selected bpmn. Alert User if no bpmn versions are deployed\r
160         if (this.testInstance.useLatestTestDefinition) {\r
161           this.useLatest();\r
162         } else {\r
163           for (let i = 0; i < this.selectedDefinition.bpmnInstances.length; i++) {\r
164             if (this.selectedDefinition.bpmnInstances[i].processDefintionId === this.testInstance.processDefintionId) {\r
165               this.selectedBpmn = this.selectedDefinition.bpmnInstances[i];\r
166               break;\r
167             }\r
168           }\r
169         }\r
170 \r
171         if (this.testInstance.testData === '') {\r
172           this.displayYAML = true;\r
173         }\r
174 \r
175         if (!this.testInstance.simulationVthInput) {\r
176           this.testInstance.simulationVthInput = {};\r
177         }\r
178 \r
179 \r
180         //grab all robot test heads to assign uploaders to each and create the vthInput object\r
181         //for(let j = 0; j < this.selectedBpmn.testHeads.length; j++){\r
182 \r
183 \r
184         //}\r
185         //console.log(this.uploaders);\r
186         if (this.existingInstance.isEdit == true)\r
187           this.editMode = true;\r
188       }//if the user is creating a new instance from the test definition page\r
189       else if (this.existingInstance.testDefinition) {\r
190         this.selectedDefinition = this.existingInstance.testDefinition;\r
191         this.populateTIName();\r
192         //set the bpmn as the latest deployed version. Alert User if no bpmn versions are deployed\r
193         this.useLatest();\r
194         this.populateVthInput();\r
195         this.populatePfloInput();\r
196         //grab all robot test heads to assign uploaders to each and set the vthInput object\r
197         for (let j = 0; j < this.selectedBpmn.testHeads.length; j++) {\r
198 \r
199           if (this.selectedBpmn.testHeads[j].testHeadId['testHeadName'].toLowerCase() === 'robot') {\r
200             this.uploaders[this.selectedBpmn.testHeads[j].bpmnVthTaskId] = new FileUploader(this.uploadOptions);\r
201           }\r
202         }\r
203 \r
204         this.testInstance = {\r
205           "testInstanceDescription": "",\r
206           "testDefinitionId" : this.selectedDefinition["_id"],\r
207           "vthInput" : this.vthInput,\r
208           "pfloInput": this.pfloInput,\r
209           "vthInputYaml": this.vthInputYaml,\r
210           "testData": this.selectedBpmn.testDataTemplate,\r
211           "testDataJSON": this.selectedBpmn.testDataTemplateJSON,\r
212           "useLatestTestDefinition": true,\r
213           "internalTestData": {},\r
214           "simulationVthInput": {}\r
215         };\r
216 \r
217       }\r
218     }\r
219     \r
220   }\r
221 \r
222   convertSimulationVth(convertTo) {\r
223     for (let key in this.testInstance.simulationVthInput) {\r
224       if (this.testInstance.simulationVthInput.hasOwnProperty(key)) {\r
225         if(convertTo == 'json')\r
226           this.testInstance.simulationVthInput[key] = JSON.parse(this.testInstance.simulationVthInput[key]);\r
227         else if (convertTo == 'string')\r
228           this.testInstance.simulationVthInput[key] = beautify(this.testInstance.simulationVthInput[key], null, 2, 10);\r
229       }\r
230     }\r
231 \r
232   }\r
233  \r
234 \r
235 \r
236   simulationMode() {\r
237     let def = {\r
238       delay: 0, response: {}\r
239     };\r
240     //console.log(this.selectedBpmn);\r
241     if (this.testInstance.simulationMode) {\r
242       this.selectedBpmn.testHeads.forEach(e => {\r
243         if(!this.testInstance.simulationVthInput){\r
244           this.testInstance.simulationVthInput = {}\r
245         }\r
246         if (!this.testInstance.simulationVthInput[e.bpmnVthTaskId]) {\r
247           this.testInstance.simulationVthInput[e.bpmnVthTaskId] = beautify(def, null, 2, 10);\r
248         }\r
249       })\r
250     }\r
251   }\r
252 \r
253   populateTIName() {\r
254     let list;\r
255     this.testInstanceService.find({ $limit: -1, $select: ['testInstanceName'], testDefinitionId: this.selectedDefinition._id }).subscribe((res) => {\r
256       list = res;\r
257       //console.log(list);\r
258       let num = list.length;\r
259       if (num === 0) {\r
260         this.testInstance.testInstanceName = this.selectedDefinition.testName;\r
261       } else {\r
262         this.testInstance.testInstanceName = this.selectedDefinition.testName + num;\r
263       }\r
264       let isTaken = true;\r
265       let count = 0;\r
266       let alreadyExisted = false;\r
267       while (isTaken === true && count < 10000) {\r
268         for (let i = 0; i < list.length; i++) {\r
269           if (list[i]["testInstanceName"] === this.testInstance.testInstanceName) {\r
270             num++;\r
271             this.testInstance.testInstanceName = this.selectedDefinition.testName + num;\r
272             alreadyExisted = true;\r
273             break;\r
274           }\r
275         }\r
276         if (alreadyExisted) {\r
277           alreadyExisted = false;\r
278         } else {\r
279           isTaken = false;\r
280         }\r
281         count++;\r
282       }\r
283     });\r
284   }\r
285   //Section for implementing Paralell workflow data entry --------------------------------------------------------------------------------------\r
286   populatePfloInput(){\r
287     // this.pfloInput = {\r
288     //   "task123": new PfloInputClass\r
289     // }\r
290     //this.selectedBpmn.pflos = [{"bpmnPfloTaskId" : "task123", "label": "TestPFLO"}]\r
291     \r
292     if(this.testInstance.pfloInput){  \r
293       return;\r
294     }\r
295 \r
296     this.pfloInput = {};\r
297    \r
298     if(this.selectedBpmn == {} || !this.selectedBpmn.pflos){\r
299       \r
300       this.testInstance.pfloInput = this.pfloInput;\r
301       return;\r
302     }\r
303 \r
304     for(let i = 0; i < this.selectedBpmn.pflos.length; i++){\r
305       if(this.selectedBpmn.pflos[i]['bpmnPfloTaskId'] != null){\r
306         this.pfloInput[this.selectedBpmn.pflos[i]['bpmnPfloTaskId']] = new PfloInputClass;\r
307        \r
308         //this.pfloInput[this.selectedBpmn.pflos[i]['bpmnPfloTaskId'] + "pfloName"] = this.selectedBpmn.pflos[i]['label'];\r
309       }\r
310     }\r
311     this.testInstance.pfloInput = this.pfloInput;\r
312     \r
313   }\r
314 \r
315   \r
316   addInstancesToPflo(taskId){\r
317     for(let i = 0; i < this.instances.length; i++){\r
318       if(this.instances[i].isSelected){\r
319         this.tiNameLookup[this.instances[i]._id] = this.instances[i].testInstanceName;\r
320         this.addPfloInput(taskId, this.instances[i]._id);\r
321       }\r
322 \r
323     }\r
324   }\r
325 \r
326   addPfloInput(taskId, instanceId){\r
327      \r
328     this.testInstance.pfloInput[taskId].args.push(new WorkflowRequest(instanceId));\r
329    \r
330   }\r
331 \r
332   clearSelectedValues(){\r
333     this.search.testInstanceName = '';\r
334     for(let i = 0; i < this.instances.length; i++){\r
335       this.instances[i].isSelected = false;\r
336     }\r
337   }\r
338 \r
339   saveTestDataOptions(event) {\r
340     this.testInstance.testData = event.object;\r
341   }\r
342 \r
343   saveFormOptions(event) {\r
344     this.testInstance.vthInput[event.taskId] = event.object;\r
345     //console.log(this.testInstance);\r
346   }\r
347 \r
348   \r
349   checkPfloInputLength(){\r
350   \r
351     if(this.testInstance.pfloInput != null){\r
352       let temp =  Object.keys(this.testInstance.pfloInput);\r
353       if(temp.length)\r
354         return temp.length > 0;\r
355       else\r
356         return false;\r
357     }else{\r
358       return false;\r
359     }\r
360   }\r
361 \r
362   deleteWorkReq(pfloId, index){\r
363     this.testInstance.pfloInput[pfloId].args.splice(index, 1);\r
364     //FORCE REFRESH all connected forms to update their index\r
365   }\r
366 \r
367   saveWorkReqForm(event) {\r
368     this.testInstance.pfloInput[event.taskId].args[event.index] = event.object;\r
369     //console.log(this.testInstance);\r
370   }\r
371 \r
372   convertTestLevelYaml() {\r
373     if (this.displayYAML) {\r
374       this.testInstance.testDataJSON = YAML.parse(this.testInstance.testData);\r
375     } else {\r
376       this.testInstance.testData = YAML.stringify(this.testInstance.testDataJSON);\r
377     }\r
378   }\r
379 \r
380   convertVTHYaml() {\r
381     if (this.testHeadYAML) {\r
382       for (let key in this.testInstance.vthInputYaml) {\r
383         this.testInstance.vthInput[key] = YAML.parse(this.testInstance.vthInputYaml[key]);\r
384       }\r
385     } else {\r
386 \r
387       for (let key in this.testInstance.vthInput) {\r
388         this.testInstance.vthInputYaml[key] = YAML.stringify(this.testInstance.vthInput[key]);\r
389       }\r
390     }\r
391   }\r
392   //End of Paralell workflow data entry section --------------------------------------------------------------------------------------\r
393 \r
394   changeBpmn() {\r
395     //populate the vth inputs when bpmn changes\r
396     this.populateVthInput();\r
397     this.displayYAML = !this.displayYAML;\r
398     this.testInstance.testDataJSON = this.selectedBpmn.testDataTemplateJSON;\r
399     this.testInstance.testData = this.selectedBpmn.testDataTemplate;\r
400     this.convertTestLevelYaml();\r
401     setTimeout(() => {\r
402       this.displayYAML = !this.displayYAML;\r
403     }, 200);\r
404 \r
405   }\r
406   //toggle Yaml for test level data\r
407   toggleYaml() {\r
408     this.convertTestLevelYaml();\r
409     this.displayYAML = !this.displayYAML;\r
410   }\r
411   //toggles Yaml for testHeads\r
412   testHeadYaml() {\r
413     this.convertVTHYaml();\r
414     this.testHeadYAML = !this.testHeadYAML;\r
415   }\r
416   //onChange method for the use latest TD toggle\r
417   useLatest() {\r
418     if (this.testInstance.useLatestTestDefinition) {\r
419       let temp;\r
420       let orderNum;\r
421       let processKey;\r
422       for (let i = 0; i < this.selectedDefinition.bpmnInstances.length; i++) {\r
423         if (temp) {\r
424           processKey = this.selectedDefinition.bpmnInstances[i].processDefinitionId\r
425           if(processKey){\r
426             orderNum = processKey.split(":");\r
427             orderNum = orderNum[1];\r
428             //console.log("bpmn check : " + orderNum + " bpmn current: " + temp.processDefinitionId.split(':')[1]);\r
429             if (this.selectedDefinition.bpmnInstances[i].isDeployed && parseInt(orderNum) > parseInt(temp.processDefinitionId.split(':')[1])) {\r
430               temp = this.selectedDefinition.bpmnInstances[i];\r
431             }\r
432           }\r
433         } else {\r
434           if (this.selectedDefinition.bpmnInstances[i].isDeployed) {\r
435             temp = this.selectedDefinition.bpmnInstances[i];\r
436           }\r
437         }\r
438 \r
439       }\r
440       if (temp.isDeployed) {\r
441         this.selectedBpmn = temp;\r
442       } else {\r
443         this.dialog.open(AlertModalComponent, {\r
444           width: '450px',\r
445           data: {\r
446             type: 'alert',\r
447             message: 'Test Definition does not contain a deployed bpmn instance. Please return to the Test Definition page and deploy.'\r
448           }\r
449         });\r
450         this.testInstance.useLatestTestDefinition = false;\r
451       }\r
452       this.populateVthInput();\r
453     }\r
454     this.populatePfloInput();\r
455   }\r
456 \r
457  \r
458   //checks if the test instance has a required Name\r
459   allNamed() {\r
460     if (!this.testInstance.testInstanceName) {\r
461       return false;\r
462     }\r
463 \r
464     return true;\r
465   }\r
466   \r
467   //populate the vthInputYaml for newly created testInstances\r
468   populateVthInput() {\r
469     this.vthInputYaml = {};\r
470     this.vthInput = {};\r
471     for (let i = 0; i < this.selectedBpmn.testHeads.length; i++) {\r
472       this.vthInputYaml[this.selectedBpmn.testHeads[i].bpmnVthTaskId] = this.selectedBpmn.testHeads[i].testHeadId.vthInputTemplate;\r
473       this.vthInputYaml[this.selectedBpmn.testHeads[i].bpmnVthTaskId + "testHeadName"] = this.selectedBpmn.testHeads[i].testHeadId.testHeadName;\r
474       if (this.selectedBpmn.testHeads[i].testHeadId.vthInputTemplateJSON) {\r
475         this.vthInput[this.selectedBpmn.testHeads[i].bpmnVthTaskId] = this.selectedBpmn.testHeads[i].testHeadId.vthInputTemplateJSON;\r
476         this.vthInput[this.selectedBpmn.testHeads[i].bpmnVthTaskId + "testHeadName"] = this.selectedBpmn.testHeads[i].testHeadId.testHeadName;\r
477       }\r
478 \r
479     }\r
480 \r
481   }\r
482   //Used to grab all test definitions for the user to select.\r
483   getDefinition() {\r
484     const dialogRef = this.dialog.open(SelectStrategyModalComponent, {\r
485       width: '450px',\r
486       data: {}\r
487     });\r
488 \r
489     dialogRef.afterClosed().subscribe(result => {\r
490       //If the user already had a selected definition and selected a new one, prompt the user to be sure of change\r
491       if (result != '' && this.selectedDefinition.testName) {\r
492         this.dialog.open(AlertModalComponent, {\r
493           width: '450px',\r
494           data: {\r
495             type: 'confirmation',\r
496             message: 'Changing the Test Definition will erase the Instance you are currently writing.'\r
497           }\r
498         }).afterClosed().subscribe(response => {\r
499           if (response) {\r
500             this.selectedDefinition = result;            \r
501             this.populateTIName();\r
502             //set the bpmn as the latest deployed version. Alert User if no bpmn versions are deployed\r
503             this.useLatest();\r
504             this.populateVthInput();\r
505             this.populatePfloInput();\r
506             //grab all robot test heads to assign uploaders to each and initialize vthInput\r
507             for (let j = 0; j < this.selectedBpmn.testHeads.length; j++) {\r
508               if (this.selectedBpmn.testHeads[j].testHeadId['vthInputTemplateJSON']) {\r
509                 this.vthInput[this.selectedBpmn.testHeads[j].bpmnVthTaskId] = this.selectedBpmn.testHeads[j].testHeadId['vthInputTemplateJSON'];\r
510               }\r
511 \r
512               if (this.selectedBpmn.testHeads[j].testHeadId['testHeadName'].toLowerCase() === 'robot') {\r
513                 this.uploaders[this.selectedBpmn.testHeads[j].bpmnVthTaskId] = new FileUploader(this.uploadOptions);\r
514               }\r
515             }\r
516 \r
517             this.testInstance = {\r
518               "testInstanceDescription": "",\r
519               "groupId": this.selectedDefinition["groupId"],\r
520               "testDefinitionId": this.selectedDefinition["_id"],\r
521               "vthInput": this.vthInput,\r
522               "pfloInput": this.pfloInput,\r
523               "vthInputYaml": this.vthInputYaml,\r
524               "testData": this.selectedBpmn.testDataTemplate,\r
525               "testDataJSON": this.selectedBpmn.testDataTemplateJSON,\r
526               "useLatestTestDefinition": true,\r
527               "internalTestData": {},\r
528               "simulationVthInput": {}\r
529 \r
530             };\r
531           }\r
532         });\r
533 \r
534         //else they did not have a test definition currently selected\r
535       } else {\r
536         this.selectedDefinition = result;\r
537         this.populateTIName();\r
538         //set the bpmn as the latest deployed version. Alert User if no bpmn versions are deployed\r
539         this.useLatest();\r
540         this.populateVthInput();\r
541         this.populatePfloInput();\r
542         //grab all robot test heads to assign uploaders to each\r
543         for (let j = 0; j < this.selectedBpmn.testHeads.length; j++) {\r
544           if (this.selectedBpmn.testHeads[j].testHeadId['vthInputTemplateJSON']) {\r
545             this.vthInput[this.selectedBpmn.testHeads[j].bpmnVthTaskId] = this.selectedBpmn.testHeads[j].testHeadId['vthInputTemplateJSON'];\r
546           }\r
547           if (this.selectedBpmn.testHeads[j].testHeadId['testHeadName'].toLowerCase() === 'robot') {\r
548             this.uploaders[this.selectedBpmn.testHeads[j].bpmnVthTaskId] = new FileUploader(this.uploadOptions);\r
549           }\r
550         }\r
551              \r
552           \r
553          \r
554           this.testInstance = {\r
555             "testInstanceDescription": "",\r
556               "groupId": this.selectedDefinition["groupId"],\r
557               "testDefinitionId": this.selectedDefinition["_id"],\r
558               "vthInput": this.vthInput,\r
559               "pfloInput": this.pfloInput,\r
560               "vthInputYaml": this.vthInputYaml,\r
561               "testData": this.selectedBpmn.testDataTemplate,\r
562               "testDataJSON": this.selectedBpmn.testDataTemplateJSON,\r
563               "useLatestTestDefinition": true,\r
564               "internalTestData": {},\r
565               "simulationVthInput": {}\r
566           };\r
567           \r
568         }\r
569     });\r
570   }\r
571 \r
572   //Saves the Test Instance Object to the database \r
573   saveAll() {\r
574     if (!this.allNamed()) {\r
575       this.dialog.open(AlertModalComponent, {\r
576         width: '450px',\r
577         data: {\r
578           type: 'alert',\r
579           message: 'The Instance is not named! Please ensure the Instance are named.'\r
580         }\r
581       }).afterClosed().subscribe((result) => {\r
582         return;\r
583       });\r
584     } else {\r
585 \r
586       if (!this.testInstance.processDefinitionId) {\r
587         this.testInstance.processDefinitionId = this.selectedBpmn.processDefinitionId;\r
588       }\r
589       this.errorCount = 0;\r
590       if (!this.displayYAML) {\r
591         this.testInstance.testData = this.testInstance.testDataJSON;\r
592       }\r
593       if (this.testHeadYAML) {\r
594         this.testInstance.vthInput = this.testInstance.vthInputYaml;\r
595       }\r
596 \r
597       this.convertSimulationVth('json');\r
598 \r
599       this.testInstanceService.create(this.testInstance)\r
600         .subscribe(\r
601           (result) => {\r
602             if (Object.keys(this.uploaders).length > 0)\r
603               this.uploadFiles(result);\r
604 \r
605             this.snack.openFromComponent(AlertSnackbarComponent, {\r
606               duration: 1500,\r
607               data: {\r
608                 message: 'Test Instance Saved'\r
609               }\r
610             });\r
611             this.dialog.closeAll();\r
612           },\r
613           (error) => {\r
614             this.dialog.open(AlertModalComponent, {\r
615               width: '450px',\r
616               data: {\r
617                 type: 'Alert',\r
618                 message: error\r
619               }\r
620             });\r
621 \r
622           });\r
623     }\r
624   }\r
625 \r
626   updateInstance() {\r
627 \r
628 \r
629     if (!this.testInstance.processDefinitionId) {\r
630       this.testInstance.processDefinitionId = this.selectedBpmn.processDefinitionId;\r
631     }\r
632     this.errorCount = 0;\r
633     if (!this.displayYAML) {\r
634       this.testInstance.testData = this.testInstance.testDataJSON;\r
635     }\r
636     if (this.testHeadYAML) {\r
637       this.testInstance.vthInput = this.testInstance.vthInputYaml;\r
638     }\r
639 \r
640     this.convertSimulationVth('json');\r
641 \r
642     this.testInstanceService.update(this.testInstance)\r
643       .subscribe((result) => {\r
644         this.snack.openFromComponent(AlertSnackbarComponent, {\r
645           duration: 1500,\r
646           data: {\r
647             message: 'Test Instance Updated'\r
648           }\r
649         });\r
650         this.childEvent.emit();\r
651       });\r
652   }\r
653 \r
654   cancel() {\r
655     this.childEvent.emit();\r
656   }\r
657   uploadFiles(result) {\r
658     for (let i = 0; i < this.selectedBpmn.testHeads.length; i++) {\r
659       if (!this.uploaders[this.selectedBpmn.testHeads[i].bpmnVthTaskId]) {\r
660         continue;\r
661       }\r
662       let key = this.selectedBpmn.testHeads[i].bpmnVthTaskId;\r
663       let uploader = this.uploaders[key];\r
664       if (uploader.queue.length > 0) {\r
665         uploader.uploadAll();\r
666         uploader.onCompleteItem = (item: FileItem, response: string, status: Number, headers: ParsedResponseHeaders) => {\r
667           this.scriptFiles.push(JSON.parse(response)[0]);\r
668         }\r
669       }\r
670       uploader.onCompleteAll = () => {\r
671 \r
672         let scriptFilesId = [];\r
673         for (let i = 0; i < this.scriptFiles.length; i++) {\r
674           scriptFilesId.push(this.scriptFiles[i]['_id']);\r
675         }\r
676        \r
677         for (let i = 0; i < this.selectedBpmn.testHeads.length; i++) {\r
678           if (this.selectedBpmn.testHeads[i].testHeadId['testHeadName'].toLowerCase() === 'robot') {\r
679             this.testInstance.internalTestData[this.selectedBpmn.testHeads[i].bpmnVthTaskId] =\r
680               {\r
681                 "robotFileId": scriptFilesId[0]\r
682               };\r
683           }\r
684         }\r
685         let ti = {\r
686           '_id': result._id,\r
687           'internalTestData': this.testInstance.internalTestData\r
688         }\r
689 \r
690         this.testInstanceService.patch(ti).subscribe(\r
691           res => {\r
692             //console.log(res);\r
693             // resolve(res);\r
694           },\r
695           err => {\r
696             // console.log(err);\r
697             // reject(err);\r
698           }\r
699         );\r
700       }\r
701     }\r
702   }\r
703   //saves instance to the database and executes the test using the agenda scheduler\r
704   saveAndExecute() {\r
705     if (!this.allNamed()) {\r
706       this.dialog.open(AlertModalComponent, {\r
707         width: '450px',\r
708         data: {\r
709           type: 'alert',\r
710           message: 'One or more Instance is not named! Please ensure all Instances are named.'\r
711         }\r
712       }).afterClosed().subscribe((result) => {\r
713         return;\r
714       });\r
715     } else {\r
716 \r
717       if (!this.testInstance.processDefinitionId) {\r
718         this.testInstance.processDefinitionId = this.selectedBpmn.processDefinitionId;\r
719       }\r
720       this.errorCount = 0;\r
721       if (!this.displayYAML) {\r
722         this.testInstance.testData = this.testInstance.testDataJSON;\r
723       }\r
724       if (this.testHeadYAML) {\r
725         this.testInstance.vthInput = this.testInstance.vthInputYaml;\r
726       }\r
727 \r
728       this.convertSimulationVth('json')\r
729 \r
730       this.testInstanceService.create(this.testInstance)\r
731         .subscribe(\r
732           (result) => {\r
733             this.executionFailed = false;\r
734             this.createResult = result;\r
735             if (Object.keys(this.uploaders).length > 0)\r
736               this.uploadFiles(result);\r
737 \r
738 \r
739             this.execute.create({\r
740               _id: this.createResult._id,\r
741               async: true\r
742             })\r
743               .subscribe(\r
744                 (response) => {\r
745 \r
746                   this.childEvent.emit();\r
747                   this.snack.openFromComponent(AlertSnackbarComponent, {\r
748                     duration: 1500,\r
749                     data: {\r
750                       message: 'Test Instance Saved and Executed'\r
751                     }\r
752                   });\r
753                   this.router.navigateByUrl('/dashboard');\r
754                 },\r
755                 (error) => {\r
756                   this.executionFailed = true;\r
757                   this.dialog.open(AlertModalComponent, {\r
758                     width: '450px',\r
759                     data: {\r
760                       type: 'Alert',\r
761                       message: "Execution error: " + error\r
762                     }\r
763                   });\r
764                 });\r
765           },\r
766           (error) => {\r
767             this.dialog.open(AlertModalComponent, {\r
768               width: '450px',\r
769               data: {\r
770                 type: 'Alert',\r
771                 message: "Save Error: " + error\r
772               }\r
773             });\r
774           });\r
775     }\r
776   }\r
777 \r
778   createNewInstance() {\r
779     this.testInstance = {\r
780       'testInstanceName': '',\r
781       'testInstanceDescription': '',\r
782       'testDefinitionId': this.selectedDefinition._id,\r
783       'testData': '',\r
784       'simulationVthInput': {}\r
785 \r
786     }\r
787   }\r
788 }\r