forked from ooyinloy/Final-Forking
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.js.html
More file actions
782 lines (580 loc) · 22.2 KB
/
client.js.html
File metadata and controls
782 lines (580 loc) · 22.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
<script>
// The .js.html files will be bundled inline into the .html file on load
/*
*
* =================================
* UTILITIES & CROSS PANEL FUNCTIONS
* =================================
*
*/
let devMode = false;
// on init make sure to run any required startup functions
(function () {
// for dev mode only - comment out or set to false to disable any UI dev features
setDevStuff(devMode);
})();
// if devmode enabled, set the required fields and show the dev button
function setDevStuff (devMode) {
if (devMode) {
$("#btn-dev").removeClass("hidden");
model.user.url = "https://demo.spiraservice.net/gettingstarted";
model.user.userName = "administrator";
model.user.api_key = "{8604C226-E746-4629-9E47-AC0C8A52B631}";
}
}
// used to show or hide / hide / show a specific panel
// @param: panel - string. suffix for items to act on (eg if id = panel-help, choice = "help")
function panelToggle (panel) {
panelId = "#panel-" + panel;
$(panelId).toggleClass("offscreen");
}
function hidePanel (panel) {
panelId = "#panel-" + panel;
$(panelId).addClass("offscreen");
}
function showPanel (panel) {
panelId = "#panel-" + panel;
$(panelId).removeClass("offscreen");
}
// manage the loading spinner
function showLoadingSpinner () {
$('#loader').removeClass('hidden');
}
function hideLoadingSpinner () {
$('#loader').addClass('hidden');
}
// clear spreadsheet, model
function clearAddonData () {
clearSheet();
model = new Data;
setDevStuff(devMode);
}
// clears the first sheet in the book
// @param: shouldClear - optional bool to check
function clearSheet (shouldClear) {
var shouldClearToUse = typeof shouldClear !== 'undefined' ? shouldClear : true;
if (shouldClearToUse) google.script.run.clearAll();
}
// resets the sidebar following logout
function resetSidebar () {
// clear input field values
$('#input-url, #input-userName, #input-password').val('');
// hide other panels, so login page is visible
$(".panel:not(#panel-auth)").addClass("offscreen");
// disable buttons and dropdowns
$("#btn-template, #select-artifact, #btn-toSpira").prop("disabled", true);
// reset artifact dropdown to 'Select an Artifact'
$("#select-artifact option[value='Select an Artifact']").attr("selected", "selected");
// hide and clear the template info box
$("#template-data-box").hide();
$("#template-project").text("");
$("#template-artifact").text("");
// reset anything required if in devmode
setDevStuff();
}
// adds all options to a dropdown
// @param: selectId - is the id of the dom select element
// @param: array - the array of objects (with id, name, and optionally a disabled value, and hidden bool)
// @param: firstMessage - an optional text field to go at the top of the array - the initial choice
function setDropdown (selectId, array, firstMessage) {
// first make a deep copy of the array to stop any funny business
var arrayCopy = JSON.parse(JSON.stringify(array)),
$element = $("#" + selectId);
// if passed in, add default "select" option to top of project array
if(firstMessage) arrayCopy.unshift({
id: 0,
name: firstMessage
});
// clear the dropdown
$element.html('');
var options = arrayCopy.map(function(item) {
var disabledText = item.disabled ? " disabled='true'" : "",
option = "<option value=" + item.id + disabledText + ">" + item.name + "</option>"
return !item.hidden ? option : null;
}).join("");
// add all optoins to the dropdown
$element.append(options);
}
/*
*
* ============
* LOGIN SCREEN
* ============
*
*/
// get user data from input fields and store in user data object
// adds the 'api-key' text before the key to make creating the urls simpler
function getAuthDetails () {
model.user.url = $("#input-url").val();
model.user.userName = $("#input-userName").val();
model.user.api_key = btoa("&api-key=" + encodeURIComponent($("#input-password").val()));
}
// fill in mock values for easy log in development, enable dev button
function setAuthDetails () {
$('#input-url').val(model.user.url);
$('#input-userName').val(model.user.userName);
$('#input-password').val(model.user.api_key);
}
// handle the click of the login button
function loginAttempt () {
getAuthDetails();
login();
}
// login function that starts the intial data creation
function login() {
showLoadingSpinner();
// call server side function to get projects
// also serves as authentication check, if the user credentials aren't correct it will throw a network error
google.script.run
.withSuccessHandler(populateProjects)
.withFailureHandler(errorNetwork)
.getProjects(model.user);
}
// kick off prepping and showing main panel
// @param: projects - passed in projects data returned from the server following successful API call to Spira
function populateProjects (projects) {
// take projects data from Spira API call, strip out unwanted fields, add to data model
let pairedDownProjectsData = projects.map(function(project) {
let result = {
id: project.ProjectId,
name: project.Name
};
return result;
});
// now add paired down project array to data store
model.projects = pairedDownProjectsData;
// get UI logic ready for main panel
showMainPanel();
}
/*
*
* ===========
* MAIN SCREEN
* ===========
*
*/
// manage the switching of the UI off the login screen on succesful login and retrieval of projects
function showMainPanel () {
// displays the current logged in user name
$('#js--loggedInAs').html('Logged in as: ' + model.user.userName);
setDropdown("select-project", model.projects, "Select a project");
setDropdown("select-artifact", params.artifacts, "Select an artifact");
showPanel("main");
hideLoadingSpinner();
}
// run server side code to manage logout
function logoutAttempt () {
//warn user that all data on the first sheet will be lost. Returns true or false
google.script.run
.withSuccessHandler(logout)
.warn('All data on the first sheet will be deleted. Continue?');
}
// @param: shouldLogout - a true or false value from google
function logout (shouldLogout) {
if (shouldLogout) {
clearAddonData();
resetSidebar();
}
}
// handles changing project dropdown - what should be enabled or disabled
$('#select-project').change(function(e) {
// if the project field has not been selected all other selected buttons are disabled
if (e.target.value == 0) {
$("#select-artifact, #btn-template").prop('disabled', true);
uiSelection.currentProject = null;
} else {
// enable artifacts dropdown
$('#select-artifact').prop('disabled', false);
// get the project object and update project information if project has changed
let chosenProject = getSelectedProject();
if (chosenProject !== uiSelection.currentProject) {
//set the temp data store project to the one selected;
uiSelection.currentProject = chosenProject;
// enable template button only when all info is received - otherwise keep it disabled
manageTemplateBtnState();
// kick off API calls
getProjectSpecificInformation(model.user, uiSelection.currentProject.id);
}
}
});
// handles enabling the template button if the artifact drop down is properly selected.
$('#select-artifact').change(function(e) {
if (e.target.value == 0) {
$('#btn-template').prop('disabled', true);
uiSelection.currentArtifact = null;
}
// get the artifact object and update artifact information if artifact has changed
let chosenArtifact = getSelectedArtifact();
if (chosenArtifact !== uiSelection.currentArtifact) {
//set the temp date store artifact to the one selected;
uiSelection.currentArtifact = chosenArtifact;
// enable template button only when all info is received - otherwise keep it disabled
manageTemplateBtnState();
// kick off API calls
getArtifactSpecificInformation(model.user, uiSelection.currentProject.id, uiSelection.currentArtifact);
}
});
// disables and enables the template creation button based on status of required API calls
function manageTemplateBtnState() {
// initially disable the button, because required API calls not completed
$('#btn-template').prop('disabled', true);
// only try to enable the button when both a project and artifact have been chosen
if (uiSelection.currentProject && uiSelection.currentArtifact) {
// set a function to run repeatedly until all gets are done
// then enable the button, and stop the timer loop
var checkGetsSuccess = setInterval (updateButtonStatus, 500);
function updateButtonStatus() {
if ( allGetsSucceeded() ) {
$('#btn-template').prop('disabled', false);
clearInterval(checkGetsSuccess);
}
}
}
}
// starts the process to create a template from chosen options
function createTemplateAttempt() {
//warn the user data will be erased
google.script.run
.withSuccessHandler(createTemplate)
.warn('All data on the first sheet will be replaced. Continue?');
}
//@param: shouldClearForm - boolean response from confirmation dialog above
function createTemplate (shouldContinue) {
if (shouldContinue) {
clearSheet();
showLoadingSpinner();
// all data should already be loaded (as otherwise template button is disabled)
// but check again that all data is present before kicking off template creation
// if so, kicks off template creation, otherwise waits and tries again
if (allGetsSucceeded()) {
templateLoader();
// otherwise, run an interval loop (should never get called as template button should be disabled)
} else {
var checkGetsSuccess = setInterval (attemptTemplateLoader, 500);
function attemptTemplateLoader() {
if ( allGetsSucceeded() ) {
startTemplateLoader();
clearInterval(checkGetsSuccess);
}
}
}
}
}
// manages request from user to clear sheet - shows confirmation dialog
function clearSheetAttempt () {
//warn that data will be erased
google.script.run
.withSuccessHandler(clearSheet)
.warn('All data on the first sheet will be deleted. Continue?');
};
// current functionality is to clone existing sheet onto new sheet in same workbook
function saveSheetAttempt () {
//check to see if there is a template present
if (model.isTemplateLoaded) {
showLoadingSpinner();
//call save function
google.script.run
.withFailureHandler(errorUnknown)
.withSuccessHandler(saveSheet)
.save();
} else {
//if no template popup a warning
google.script.run.noTemplate();
}
}
function saveSheet (isSaved) {
hideLoadingSpinner()
if(isSaved){
//notify on success
google.script.run.success('Template saved in new sheet.');
}
}
function getFromSpiraAttempt () {
//this can be reimplemented in future versions but all code related to importing artifact data is commented out.
// if (model.templateData.isTemplateLoaded) {
// google.script.run.withSuccessHandler(importSuccess).withFailureHandler(errorNetwork).importer(model.userData.currentUser);
// } else {
// google.script.run.noTemplate();
// }
// function importSuccess() {
// google.script.run.success('Data loaded successfully.');
// }
}
function sendToSpiraAttempt () {
//check that template is loaded
if (model.isTemplateLoaded) {
showLoadingSpinner();
//call export function
google.script.run
.withFailureHandler(errorImpExp)
.withSuccessHandler(sendToSpira)
.exporter(model, params.fieldType);
} else {
//if no template popup a warning
google.script.run.noTemplate();
}
}
function sendToSpira (log) {
if (devMode) console.log(log);
//if array (which holds error responses) is present, and errors present
if (log.errorCount) {
errorMessages = log.entries
.filter(function(entry) { return entry.error})
.map(function(entry){ return entry.message });
}
hideLoadingSpinner();
//runs the export success function, passes a boolean flag, if there are errors the flag is true.
if (log && log.status) {
google.script.run.exportSuccess(log.status);
}
}
/*
*
* ===========
* HELP SCREEN
* ===========
*
*/
// manage showing the correct help section to the user
// @param: choice - string. suffix for items to select (eg if id = help-section-fields, choice = "fields")
function showChosenHelpSection (choice) {
// hide all sections and then only show the one the user wants
$(".help-section").addClass("hidden");
$("#help-section-" + choice).removeClass("hidden");
// set all buttons back to normal, then highlight one just clicked
$(".btn-help").removeClass("create");
$("#btn-help-" + choice).addClass("create");
}
/*
*
* =================
* CREATING TEMPLATE
* =================
*
*/
// retrieves the project object that matches the project selected in the dropdown
// returns a project object
function getSelectedProject () {
// store dropdown value
let projectDropdownVal = $('#select-project option:selected').val();
// filter the project lists to those chosen
let projectSelected = model.projects.filter(function(project) {
return project.id == projectDropdownVal;
})[0];
return projectSelected;
}
// retrieves the artifact object that matches the artifact selected in the dropdown
// returns an artifact object
function getSelectedArtifact() {
// store dropdown values
let artifactDropdownVal = $('#select-artifact option:selected').val();
// filter the artifact lists to those chosen
let artifactSelected = params.artifacts.filter(function(artifact) {
return artifact.id == artifactDropdownVal;
})[0];
return artifactSelected;
}
// kicks off all relevant API calls to get project specific information
// @param: user - the user object of the logged in user
// @param: projectId - int of the reqested project
function getProjectSpecificInformation(user, projectId) {
model.projectGetRequestsMade = 0;
// get project information
getUsers(user, projectId);
getComponents(user, projectId);
getReleases(user, projectId);
}
// kicks off all relevant API calls to get artifact specific information
// @param: user - the user object of the logged in user
// @param: projectId - int of the reqested project
// @param: artifact- object of the reqested artifact - needed to query on different parts of object
function getArtifactSpecificInformation(user, projectId, artifact) {
// first reset get counts
model.artifactGetRequestsMade = 0;
model.artifactGetRequestsToMake = model.baselineArtifactGetRequests;
// increase the count if any bespoke fields are present (eg folders or incident types)
if (artifact.bespokeFields && artifact.bespokeFields.length > 0) {
model.artifactGetRequestsToMake += artifact.besokeFields.length;
}
// get standard artifact information - eg custom fields
getCustoms(user, projectId, artifact.id);
// get any bespoke field information
}
// starts GET request to Spira for project components
// @param: user - the user object of the logged in user
// @param: projectId - int of the reqested project
function getComponents(user, projectId) {
// call server side fetch
google.script.run
.withSuccessHandler(getComponentsSuccess)
.withFailureHandler(errorNetwork)
.getComponents(user, projectId);
}
// formats and sets component data on the model
function getComponentsSuccess(data) {
// clear old values
uiSelection.projectComponents = [];
// add relevant data to the main model store
uiSelection.projectComponents = data
.filter(function(item) { return item.IsActive;})
.map(function(item) {
return {
id: item.ComponentId,
name: item.Name
}
});
model.projectGetRequestsMade++;
}
// starts GET request to Spira for project / artifact custom properties
// @param: user - the user object of the logged in user
// @param: projectId - int of the reqested project
// @param: artifactId - int of the reqested artifact
function getCustoms(user, projectId, artifactId) {
// call server side fetch
google.script.run
.withSuccessHandler(getCustomsSuccess)
.withFailureHandler(errorNetwork)
.getCustoms(user, projectId, artifactId);
}
// formats and sets custom field data on the model - adding to a temp holding area, to allow for changes before template creation
function getCustomsSuccess(data) {
// clear old values
uiSelection.artifactCustomFields = [];
// assign unparsed data to data object
// these values are parsed later depending on function needs
uiSelection.artifactCustomFields = data
.filter(function(item) { return !item.IsDeleted;})
.map(function(item) {
var customField = {
isCustom: true,
field: item.CustomPropertyFieldName,
name: item.Name,
propertyNumber: item.PropertyNumber,
type: item.CustomPropertyTypeId
};
// add array of values for dropdowns
if (item.CustomPropertyTypeId == params.fieldType.drop || item.CustomPropertyTypeId == params.fieldType.multi) {
customField.values = item.CustomList.Values.map(function(listItem) {
return {
id: listItem.CustomPropertyValueId,
name: listItem.Name
}
})
}
return customField;
}
);
model.artifactGetRequestsMade++;
}
// starts GET request to Spira for project releases properties
// @param: user - the user object of the logged in user
// @param: projectId - int of the reqested project
function getReleases(user, projectId, artifactId) {
// call server side fetch
google.script.run
.withSuccessHandler(getReleasesSuccess)
.withFailureHandler(errorNetwork)
.getReleases(user, projectId);
}
// formats and sets release data on the model
function getReleasesSuccess(data) {
// clear old values
uiSelection.projectReleases = [];
// add relevant data to the main model store
uiSelection.projectReleases = data.map(function(item) {
return {
id: item.ReleaseId,
name: item.Name
}
})
model.projectGetRequestsMade++;
}
// starts GET request to Spira for project users properties
// @param: user - the user object of the logged in user
// @param: projectId - int of the reqested project
function getUsers(user, projectId) {
// call server side fetch
google.script.run
.withSuccessHandler(getUsersSuccess)
.withFailureHandler(errorNetwork)
.getUsers(user, projectId)
}
// formats and sets user data on the model
function getUsersSuccess(data) {
// clear old values
uiSelection.projectUsers = [];
// map through user obj and assign names
uiSelection.projectUsers = data.map(function(item) {
return {
id: item.UserId,
username: item.UserName,
name: item.FullName,
}
})
model.projectGetRequestsMade++;;
}
// check to see that all project and artifact requests have been made - ie that successes match required requests
// returns boolean
function allGetsSucceeded () {
var projectGetsDone = model.projectGetRequestsToMake === model.projectGetRequestsMade,
artifactGetsDone = model.artifactGetRequestsToMake === model.artifactGetRequestsMade;
return projectGetsDone && artifactGetsDone;
}
// send data to server to manage the creation of the template on the relevant sheet
function templateLoader () {
// set the model based on data stored based on current dropdown selections
model.currentProject = uiSelection.currentProject;
model.currentArtifact = uiSelection.currentArtifact;
model.projectComponents = [];
model.projectReleases = [];
model.projectUsers = [];
model.projectComponents = uiSelection.projectComponents;
model.projectReleases = uiSelection.projectReleases;
model.projectUsers = uiSelection.projectUsers;
// collate standard fields and custom fields
var customs = uiSelection.artifactCustomFields,
fields = templateFields[model.currentArtifact.field];
model.fields = fields.concat(customs);
// call server side template function
google.script.run
.withSuccessHandler(templateLoaderSuccess)
.withFailureHandler(errorUnknown)
.templateLoader(model, params.fieldType);
}
// once template is loaded, enable the "send to Spira" button
function templateLoaderSuccess(data) {
model.isTemplateLoaded = true;
//turn off ajax spinner if it's on
hideLoadingSpinner();
//enable the send to spira button
$("#btn-toSpira").prop('disabled', false);
//show text in the sidebar that tells the user what the template is set to:
$("#template-project").text(model.currentProject.name);
$("#template-artifact").text(model.currentArtifact.name);
$("#template-data-box").show();
}
/*
*
* ==============
* ERROR HANDLING
* ==============
*
* These call a popup using google server side code
* most args are the HTTPResponse objects from the `withFailureHandler` promise
*
*/
function errorPopUp(err, type) {
google.script.run.error(type);
hideLoadingSpinner();
console.log(err);
}
function errorNetwork(err) {
errorPopUp(err);
}
function errorImpExp(err) {
errorPopUp(err, 'impExp');
}
function errorUnknown(err) {
errorPopUp(err, 'unknown');
}
</script>