forked from ooyinloy/Final-Forking
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.gs
More file actions
1464 lines (1165 loc) · 55.2 KB
/
server.gs
File metadata and controls
1464 lines (1165 loc) · 55.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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// globals
var API_BASE = '/services/v5_0/RestService.svc/projects/',
API_BASE_NO_SLASH = '/services/v5_0/RestService.svc/projects',
ART_ENUMS = {
requirements: 1,
testCases: 2,
incidents: 3,
releases: 4,
testRuns: 5,
tasks: 6,
testSteps: 7,
testSets: 8
},
INITIAL_HIERARCHY_OUTDENT = -20,
FIELD_MANAGEMENT_ENUMS = {
all: 1,
standard: 2,
subType: 3
},
STATUS_ENUM = {
allSuccess: 1,
allError: 2,
someError: 3
},
INLINE_STYLING = "style='font-family: sans-serif'";
/*
* ======================
* INITIAL LOAD FUNCTIONS
* ======================
*
* These functions are needed for initialization
* All Google App Script (GAS) files are bundled by the engine
* at start up so any non-scoped variables declared will be available globally.
*
*/
// App script boilerplate install function
// opens app on install
function onInstall(e) {
onOpen(e);
}
// App script boilerplate open function
// opens sidebar
// Method `addItem` is related to the 'Add-on' menu items. Currently just one is listed 'Start' in the dropdown menu
function onOpen(e) {
SpreadsheetApp.getUi().createAddonMenu().addItem('Start', 'showSidebar').addToUi();
}
// side bar function gets index.html and opens in side window
function showSidebar() {
var ui = HtmlService.createTemplateFromFile('index')
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('SpiraTeam by Inflectra');
SpreadsheetApp.getUi().showSidebar(ui);
}
// This function is part of the google template engine and allows for modularization of code
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
/*
*
* ========================
* TEMPLATE PANEL FUNCTIONS
* ========================
*
*/
// copy the first sheet into a new sheet in the same spreadsheet
function save() {
// pop up telling the user that their data will be saved
var ui = SpreadsheetApp.getUi();
var response = ui.alert('This will save the current sheet in a new sheet on this spreadsheet. Continue?', ui.ButtonSet.YES_NO);
// returns with user choice
if (response == ui.Button.YES) {
// get first sheet of active spreadsheet
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadSheet.getSheets()[0];
// get entire open spreadsheet id
var id = spreadSheet.getId();
// set current spreadsheet file as destination
var destination = SpreadsheetApp.openById(id);
// copy sheet to current spreadsheet in new sheet
sheet.copyTo(destination);
// returns true to queue success popup
return true;
} else {
// returns false to ignore success popup
return false;
}
}
//clears first sheet in spreadsheet
function clearAll() {
// get first active spreadsheet
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadSheet.getSheets()[0];
// clear all formatting and content
var lastColumn = sheet.getMaxColumns(),
lastRow = sheet.getMaxRows();
sheet.clear(); //.showColumns(1, lastColumn)
// clears data validations and notes from the entire sheet
var range = sheet.getRange(1, 1, lastRow, lastColumn);
range.clearDataValidations().clearNote();
// remove any protections on the sheet
var protections = spreadSheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
for (var i = 0; i < protections.length; i++) {
var protection = protections[i];
if (protection.canEdit()) {
protection.remove();
}
}
// Reset sheet name
sheet.setName('Sheet');
}
/*
*
* ====================
* DATA "GET" FUNCTIONS
* ====================
*
* functions used to retrieve data from Spira - things like projects and users, not specific records
*
*/
// General fetch function, using Google's built in fetch api
// @param: currentUser - user object storing login data from client
// @param: fetcherUrl - url string passed in to connect with Spira
function fetcher(currentUser, fetcherURL) {
//google base 64 encoded string utils
var decoded = Utilities.base64Decode(currentUser.api_key);
var APIKEY = Utilities.newBlob(decoded).getDataAsString();
//build URL from args
var fullUrl = currentUser.url + fetcherURL + "username=" + currentUser.userName + APIKEY;
//set MIME type
var params = { 'content-type': 'application/json' };
//call Google fetch function
var response = UrlFetchApp.fetch(fullUrl, params);
//returns parsed JSON
//unparsed response contains error codes if needed
return JSON.parse(response);
}
// Gets projects accessible by current logged in user
// This function is called on initial log in and therefore also acts as user validation
// @param: currentUser - object with details about the current user
function getProjects(currentUser) {
var fetcherURL = API_BASE_NO_SLASH + '?';
return fetcher(currentUser, fetcherURL);
}
// Gets components for selected project.
// @param: currentUser - object with details about the current user
// @param: projectId - int id for current project
function getComponents(currentUser, projectId) {
var fetcherURL = API_BASE + projectId + '/components?active_only=true&include_deleted=false&';
return fetcher(currentUser, fetcherURL);
}
// Gets custom fields for selected project and artifact
// @param: currentUser - object with details about the current user
// @param: projectId - int id for current project
// @param: artifactName - string name of the current artifact
function getCustoms(currentUser, projectId, artifactName) {
var fetcherURL = API_BASE + projectId + '/custom-properties/' + artifactName + '?';
return fetcher(currentUser, fetcherURL);
}
// Gets releases for selected project
// @param: currentUser - object with details about the current user
// @param: projectId - int id for current project
function getReleases(currentUser, projectId) {
var fetcherURL = API_BASE + projectId + '/releases?';
return fetcher(currentUser, fetcherURL);
}
// Gets users for selected project
// @param: currentUser - object with details about the current user
// @param: projectId - int id for current project
function getUsers(currentUser, projectId) {
var fetcherURL = API_BASE + projectId + '/users?';
return fetcher(currentUser, fetcherURL);
}
/*
*
* =======================
* CREATE "POST" FUNCTIONS
* =======================
*
* functions to create new records in Spira - eg add new requirements
*
*/
// General fetch function, using Google's built in fetch api
// @param: body - json object
// @param: currentUser - user object storing login data from client
// @param: postUrl - url string passed in to connect with Spira
function poster(body, currentUser, postUrl) {
//encryption
var decoded = Utilities.base64Decode(currentUser.api_key);
var APIKEY = Utilities.newBlob(decoded).getDataAsString();
//build URL from args
var fullUrl = currentUser.url + postUrl + "username=" + currentUser.userName + APIKEY;
//POST headers
var params = {
'method': 'post',
'contentType': 'application/json',
'muteHttpExceptions': true,
'payload': body
};
//call Google fetch function
var response = UrlFetchApp.fetch(fullUrl, params);
//returns parsed JSON
//unparsed response contains error codes if needed
return response;
//return JSON.parse(response);
}
// effectively a switch to manage which artifact we have and therefore which API call to use with what data
// returns the response from the specific post service to Spira
// @param: entry - object of single specific entry to send to Spira
// @param: user - user object
// @param: projectId - int of the current project
// @param: artifactId - int of the current artifact
// @param: parentId - optional int of the relevant parent to attach the artifact too
function postArtifactToSpira(entry, user, projectId, artifactId, parentId) {
//stringify
var JSON_body = JSON.stringify(entry),
response = "",
postUrl = "";
//send JSON object of new item to artifact specific export function
switch (artifactId) {
// REQUIREMENTS
case ART_ENUMS.requirements:
// url to post initial RQ to ensure it is fully outdented
if (entry.indentPosition === 0 ) {
postUrl = API_BASE + projectId + '/requirements/indent/' + INITIAL_HIERARCHY_OUTDENT + '?';
// if no parentId then post as a regular RQ
} else if (parentId === -1) {
postUrl = API_BASE + projectId + '/requirements?';
// we should have a parent Id set so add this RQ as its child
} else {
postUrl = API_BASE + projectId + '/requirements/parent/' + parentId + '?';
}
response = poster(JSON_body, user, postUrl);
break;
// TEST CASES
case ART_ENUMS.testCases:
postUrl = API_BASE + projectId + '/test-cases?';
response = poster(JSON_body, user, postUrl);
break;
// INCIDENTS
case ART_ENUMS.incidents:
postUrl = API_BASE + projectId + '/incidents?';
response = poster(JSON_body, user, postUrl);
break;
// RELEASES
case ART_ENUMS.releases:
// if no parentId then post as a regular release
if (parentId === -1) {
postUrl = API_BASE + projectId + '/releases?';
// we should have a parent Id set so add this RQ as its child
} else {
postUrl = API_BASE + projectId + '/releases/' + parentId + '?';
}
response = poster(JSON_body, user, postUrl);
break;
// TASKS
case ART_ENUMS.tasks:
postUrl = API_BASE + projectId + '/tasks?';
response = poster(JSON_body, user, postUrl);
break;
// TEST STEPS
case ART_ENUMS.testSteps:
postUrl = API_BASE + projectId + '/test-cases/' + parentId + '/test-steps?';
// only post the test step if we have a parent id
response = parentId !== -1 ? poster(JSON_body, user, postUrl) : null;
break;
}
return response;
}
/*
*
* ==============
* ERROR MESSAGES
* ==============
*
*/
// Error notification function
// Assigns string value and routes error call from client.js.html
// @param: type - string identifying the message to be displayed
function error(type) {
if (type == 'impExp') {
okWarn('There was an input error. Please check that your entries are correct.');
} else if (type == 'unknown') {
okWarn('Unkown error. Please try again later or contact your system administrator');
} else {
okWarn('Network error. Please check your username, url, and password. If correct make sure you have the correct permissions.');
}
}
// Pop-up notification function
// @param: string - message to be displayed
function success(string) {
// Show a 2-second popup with the title "Status" and a message passed in as an argument.
SpreadsheetApp.getActiveSpreadsheet().toast(string, 'Success', 2);
}
// Alert pop up for data clear warning
// @param: string - message to be displayed
function warn(string) {
var ui = SpreadsheetApp.getUi();
//alert popup with yes and no button
var response = ui.alert(string, ui.ButtonSet.YES_NO);
//returns with user choice
if (response == ui.Button.YES) {
return true;
} else {
return false;
}
}
// Alert pop up for export success
// @param: message - string sent from the export function
function exportSuccess(message) {
if (message == STATUS_ENUM.allSuccess) {
okWarn("All done! To send more data over, clear the sheet first.");
} else if (message == STATUS_ENUM.someError) {
okWarn("Sorry, but there were some problems. Check the notes on the relevant ID field for explanations.");
} else if (message == STATUS_ENUM.alLError){
okWarn("We're really sorry, but we couldn't send anything to SpiraTeam - please check notes on the ID fields for more information.");
}
}
// Alert pop up for no template present
function noTemplate() {
okWarn('Please load a template to continue.');
}
// Google alert popup with OK button
// @param: dialog - message to show
function okWarn(dialog) {
var ui = SpreadsheetApp.getUi();
var response = ui.alert(dialog, ui.ButtonSet.OK);
}
/*
* =================
* TEMPLATE CREATION
* =================
*
* This function creates a template based on the model template data
* TODO: currently only creates requirements/task template in non generic way
* Takes the entire data model as an argument
*
*/
// function that manages template creation - creating the header row, formatting cells, setting validation
// @param: model - full model object from client containing field data for specific artifact, list of project users, components, etc
// @param: fieldType - list of fieldType enums from client params object
function templateLoader(model, fieldType) {
// clear spreadsheet depending on user input, and unhide everything
clearAll();
// select open file and select first sheet
// TODO rework this to be the active sheet - not the first one
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet(),
sheet = spreadSheet.getSheets()[0],
fields = model.fields;
// set sheet (tab) name to model name
sheet.setName(model.currentProject.name + ' - ' + model.currentArtifact.name);
// heading row - sets names and formatting
headerSetter(sheet, fields, model.colors);
// set validation rules on the columns
contentValidationSetter(sheet, model, fieldType);
// set any extra formatting options
contentFormattingSetter(sheet, model);
}
// Sets headings for fields
// creates an array of the field names so that changes can be batched to the relevant range in one go for performance reasons
// @param: sheet - the sheet object
// @param: fields - full field data
// @param: colors - global colors used for formatting
function headerSetter (sheet, fields, colors) {
var headerNames = [],
backgrounds = [],
fontColors = [],
fontWeights = [],
fieldsLength = fields.length;
for (var i = 0; i < fieldsLength; i++) {
headerNames.push(fields[i].name);
// set field text depending on whether is required or not
var fontColor = (fields[i].required || fields[i].requiredForSubType) ? colors.headerRequired : colors.header;
var fontWeight = fields[i].required ? 'bold' : 'normal';
fontColors.push(fontColor);
fontWeights.push(fontWeight);
// set background colors based on if it is a subtype only field or not
var background = fields[i].isSubTypeField ? colors.bgHeaderSubType : colors.bgHeader;
backgrounds.push(background);
}
sheet.getRange(1, 1, 1, fieldsLength)
.setWrap(true)
// the arrays need to be in an array as methods expect a 2D array for managing 2D ranges
.setBackgrounds([backgrounds])
.setFontColors([fontColors])
.setFontWeights([fontWeights])
.setValues([headerNames])
.protect().setDescription("header row").setWarningOnly(true);
}
// Sets validation on a per column basis, based on the field type passed in by the model
// a switch statement checks for any type requiring validation and carries out necessary action
// @param: sheet - the sheet object
// @param: model - full data to acccess global params as well as all fields
// @param: fieldType - enums for field types
function contentValidationSetter (sheet, model, fieldType) {
var nonHeaderRows = sheet.getMaxRows() - 1;
for (var index = 0; index < model.fields.length; index++) {
var columnNumber = index + 1,
list = [];
switch (model.fields[index].type) {
// ID fields: restricted to numbers and protected
case fieldType.id:
case fieldType.subId:
setNumberValidation(sheet, columnNumber, nonHeaderRows, false);
protectColumn(
sheet,
columnNumber,
nonHeaderRows,
model.colors.bgReadOnly,
"ID field",
false
);
break;
// INT and NUM fields are both treated by Sheets as numbers
case fieldType.int:
case fieldType.num:
setNumberValidation(sheet, columnNumber, nonHeaderRows, false);
break;
// BOOL as Sheets has no bool validation, a yes/no dropdown is used
case fieldType.bool:
// 'True' and 'False' don't work as dropdown choices
list.push("Yes", "No");
setDropdownValidation(sheet, columnNumber, nonHeaderRows, list, false);
break;
// DATE fields get date validation
case fieldType.date:
setDateValidation(sheet, columnNumber, nonHeaderRows, false);
break;
// DROPDOWNS and MULTIDROPDOWNS are both treated as simple dropdowns (Sheets does not have multi selects)
case fieldType.drop:
case fieldType.multi:
var fieldList = model.fields[index].values;
for (var i = 0; i < fieldList.length; i++) {
list.push(fieldList[i].name);
}
setDropdownValidation(sheet, columnNumber, nonHeaderRows, list, false);
break;
// USER fields are dropdowns with the values coming from a project wide set list
case fieldType.user:
for (var j = 0; j < model.projectUsers.length; j++) {
list.push(model.projectUsers[j].name);
}
setDropdownValidation(sheet, columnNumber, nonHeaderRows, list, false);
break;
// COMPONENT fields are dropdowns with the values coming from a project wide set list
case fieldType.component:
for (var k = 0; k < model.projectComponents.length; k++) {
list.push(model.projectComponents[k].name);
}
setDropdownValidation(sheet, columnNumber, nonHeaderRows, list, false);
break;
// RELEASE fields are dropdowns with the values coming from a project wide set list
case fieldType.release:
for (var l = 0; l < model.projectReleases.length; l++) {
list.push(model.projectReleases[l].name);
}
setDropdownValidation(sheet, columnNumber, nonHeaderRows, list, false);
break;
// All other types
default:
//do nothing
break;
}
}
}
// create dropdown validation on set column based on specified values
// @param: sheet - the sheet object
// @param: columnNumber - int of the column to validate
// @param: rowLength - int of the number of rows for range (global param)
// @param: list - array of values to show in a dropdown and use for validation
// @param: allowInvalid - bool to state whether to restrict any values to those in validation or not
function setDropdownValidation (sheet, columnNumber, rowLength, list, allowInvalid) {
// create range
var range = sheet.getRange(2, columnNumber, rowLength);
// create the validation rule
// requireValueInList - params are the array to use, and whether to create a dropdown list
var rule = SpreadsheetApp.newDataValidation()
.requireValueInList(list, true)
.setAllowInvalid(allowInvalid)
.build();
range.setDataValidation(rule);
}
// create date validation on set column based on specified values
// @param: sheet - the sheet object
// @param: columnNumber - int of the column to validate
// @param: rowLength - int of the number of rows for range (global param)
// @param: allowInvalid - bool to state whether to restrict any values to those in validation or not
function setDateValidation (sheet, columnNumber, rowLength, allowInvalid) {
// create range
var range = sheet.getRange(2, columnNumber, rowLength);
// create the validation rule
var rule = SpreadsheetApp.newDataValidation()
.requireDate()
.setAllowInvalid(false)
.setHelpText('Must be a valid date')
.build();
range.setDataValidation(rule);
}
// create number validation on set column based on specified values
// @param: sheet - the sheet object
// @param: columnNumber - int of the column to validate
// @param: rowLength - int of the number of rows for range (global param)
// @param: allowInvalid - bool to state whether to restrict any values to those in validation or not
function setNumberValidation (sheet, columnNumber, rowLength, allowInvalid) {
// create range
var range = sheet.getRange(2, columnNumber, rowLength);
// create the validation rule
//must be a valid number greater than -1 (also excludes 1.1.0 style numbers)
var rule = SpreadsheetApp.newDataValidation()
.requireNumberGreaterThan(-1)
.setAllowInvalid(allowInvalid)
.setHelpText('Must be a positive number')
.build();
range.setDataValidation(rule);
}
// format columns based on a potential rang of factors - eg hide unsupported columns
// @param: sheet - the sheet object
// @param: model - full model data set
function contentFormattingSetter (sheet, model) {
for (var i = 0; i < model.fields.length; i++) {
var columnNumber = i + 1;
// hide unsupported fields
if (model.fields[i].unsupported) {
protectColumn(
sheet,
columnNumber,
(sheet.getMaxRows() - 1),
model.colors.bgReadOnly,
model.fields[i].name + "unsupported",
true
);
}
}
}
// protects specific column. Edits still allowed - current user not excluded from edit list, but could in future
// @param: sheet - the sheet object
// @param: columnNumber - int of column to hide
// @param: rowLength - int of default number of rows to apply any formattting to
// @param: bgColor - string color to set on background as hex code (eg '#ffffff')
// @param: name - string description for the protected range
// @param: hide - optional bool to hide column completely
function protectColumn (sheet, columnNumber, rowLength, bgColor, name, hide) {
// create range
var range = sheet.getRange(2, columnNumber, rowLength);
range.setBackground(bgColor)
.protect()
.setDescription(name)
.setWarningOnly(true);
if(hide) {
sheet.hideColumns(columnNumber);
}
}
/*
* ================
* SENDING TO SPIRA
* ================
*
* The main function takes the entire data model and the artifact type
* and calls the child function to set various object values before
* sending the finished objects to SpiraTeam
*
*/
// function that manages exporting data from the sheet - creating an array of objects based on entered data, then sending to Spira
// @param: model - full model object from client containing field data for specific artifact, list of project users, components, etc
// @param: fieldType - list of fieldType enums from client params object
function exporter(model, fieldType) {
// 1. SETUP FUNCTION LEVEL VARS
// get the active spreadsheet and first sheet
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet(),
sheet = spreadSheet.getSheets()[0],
fields = model.fields,
artifact = model.currentArtifact,
artifactIsHierarchical = artifact.hierarchical,
artifactHasFolders = artifact.hasFolders,
lastRow = sheet.getLastRow() - 1 || 10, // hack to make sure we pass in some rows to the sheetRange, otherwise it causes an error
sheetRange = sheet.getRange(2,1, lastRow, fields.length),
sheetData = sheetRange.getValues(),
entriesForExport = [],
lastIndentPosition = null;
// 2. CREATE ARRAY OF ENTRIES
// loop to create artifact objects from each row taken from the spreadsheet
for (var rowToPrep = 0; rowToPrep < sheetData.length; rowToPrep++) {
// stop at the first row that is fully blank
if (sheetData[rowToPrep].join("") === "") {
break;
} else {
// check for required fields (for normal artifacts and those with sub types - eg test cases and steps)
var rowChecks = {
hasSubType: artifact.hasSubType,
totalFieldsRequired: countRequiredFieldsByType(fields, false),
totalSubTypeFieldsRequired: artifact.hasSubType ? countRequiredFieldsByType(fields, true) : 0,
countRequiredFields: rowCountRequiredFieldsByType(sheetData[rowToPrep], fields, false),
countSubTypeRequiredFields: artifact.hasSubType ? rowCountRequiredFieldsByType(sheetData[rowToPrep], fields, true) : 0,
subTypeIsBlocked: !artifact.hasSubType ? true : rowBlocksSubType(sheetData[rowToPrep], fields)
},
// create entry used to populate all relevant data for this row
entry = {};
// first check for errors
var hasProblems = rowHasProblems(rowChecks);
if (hasProblems) {
entry.validationMessage = hasProblems;
// if error free determine what field filtering is required - needed to choose type/subtype fields if subtype is present
} else {
var fieldsToFilter = relevantFields(rowChecks);
entry = createEntryFromRow( sheetData[rowToPrep], model, fieldType, artifactIsHierarchical, lastIndentPosition, fieldsToFilter );
// FOR SUBTYPE ENTRIES add flag on entry if it is a subtype
if (fieldsToFilter === FIELD_MANAGEMENT_ENUMS.subType) {
entry.isSubType = true;
}
// FOR HIERARCHICAL ARTIFACTS update the last indent position before going to the next entry to make sure relative indent is set correctly
if (artifactIsHierarchical) {
lastIndentPosition = entry.indentPosition;
}
}
entriesForExport.push(entry);
}
}
// 3. GET READY TO SEND DATA TO SPIRA
// Create and show a window to tell the user what is going on
if (!entriesForExport.length) {
var nothingToExportMessage = HtmlService.createHtmlOutput('<p ' + INLINE_STYLING + '>There are no entries to send to SpiraTeam</p>').setWidth(250).setHeight(75);
SpreadsheetApp.getUi().showModalDialog(nothingToExportMessage, 'Check Sheet');
return "nothing to send";
} else {
var exportMessageToUser = HtmlService.createHtmlOutput('<p ' + INLINE_STYLING + '>Preparing to send...</p>').setWidth(200).setHeight(75);
SpreadsheetApp.getUi().showModalDialog(exportMessageToUser, 'Progress');
// create required variables for managing responses for sending data to spirateam
var log = {
errorCount: 0,
successCount: 0,
entriesLength: entriesForExport.length,
entries: []
},
// set var for parent - used to designate eg a test case so it can be sent with the test step post
parentId = -1;
// 4. SEND DATA TO SPIRA AND MANAGE RESPONSES
// loop through objects to send
for (var i = 0; i < entriesForExport.length; i++) {
var response = {};
// skip if there was an error validating the sheet row
if (entriesForExport[i].validationMessage) {
response.error = true;
response.message = entriesForExport[i].validationMessage;
log.errorCount++;
// stop if the artifact is hierarchical because we don't know what side effects there could be to any further items.
if (artifact.hierarchical) {
response.message += " - no further entries were sent to avoid creating an incorrect hierarchy";
// make sure to push the response so that the client can process error message
log.entries.push(response);
break;
}
}
// skip if a sub type row does not have a parent to hook to
else if (entriesForExport[i].isSubType && !parentId) {
response.error = true;
response.message = "can't add a child type when there is no corresponding parent type";
log.errorCount++;
// send to Spira and update the response object
} else {
// set the correct parentId for hierarchical artifacts
// set before launching the API call as we need to look back through previous entries
if (artifact.hierarchical) {
parentId = getHierarchicalParentId(entriesForExport[i].indentPosition, log.entries);
}
var sentToSpira = manageSendingToSpira ( entriesForExport[i], model.user, model.currentProject.id, artifact, fields, fieldType, parentId );
// update the parent ID for a subtypes based on the successful API call
if (artifact.hasSubType) {
parentId = sentToSpira.parentId;
}
response.details = sentToSpira;
// handle success and error cases
if (sentToSpira.error) {
log.errorCount++;
response.error = true;
response.message = sentToSpira.errorMessage;
//Sets error HTML modals
if (artifact.hierarchical) {
// if there is an error on any hierarchical artifact row, break out of the loop to prevent entries being attached to wrong parent
htmlOutput = HtmlService.createHtmlOutput('<p ' + INLINE_STYLING + '>Error sending ' + (i + 1) + ' of ' + (entriesForExport.length) + ' - sending stopped to avoid indenting entries incorrectly</p>').setWidth(200).setHeight(75);
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Progress');
log.entries.push(response);
break;
} else {
htmlOutput = HtmlService.createHtmlOutput('<p ' + INLINE_STYLING + '>Error sending ' + (i + 1) + ' of ' + (entriesForExport.length) + '</p>').setWidth(200).setHeight(75);
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Progress');
}
} else {
log.successCount++;
response.newId = sentToSpira.newId;
// if artifact is hierarchical save relevant information to work out how to indent
if (artifact.hierarchical) {
response.details.hierarchyInfo = {
id: sentToSpira.newId,
indent: entriesForExport[i].indentPosition
}
}
//modal that displays the status of each artifact sent
htmlOutputSuccess = HtmlService.createHtmlOutput('<p ' + INLINE_STYLING + '>Sending ' + (i + 1) + ' of ' + (entriesForExport.length) + '...</p>').setWidth(200).setHeight(75);
SpreadsheetApp.getUi().showModalDialog(htmlOutputSuccess, 'Progress');
}
}
log.entries.push(response);
}
// review all activity and set final status
log.status = log.errorCount ? (log.errorCount == log.entriesLength ? STATUS_ENUM.allError : STATUS_ENUM.someError) : STATUS_ENUM.allSuccess;
// 5. SET MESSAGES AND FORMATTING ON SHEET
var bgColors = [],
notes = [],
values = [];
// first handle cell formatting
for (var row = 0; row < sheetData.length; row++) {
var rowBgColors = [],
rowNotes = [],
rowValues = [];
for (var col = 0; col < fields.length; col++) {
if (log.entries.length > row) {
var isSubType = (log.entries[row].details && log.entries[row].details.entry && log.entries[row].details.entry.isSubType) ? log.entries[row].details.entry.isSubType : false;
var bgColor = setFeedbackBgColor(sheetData[row][col], log.entries[row].error, fields[col], fieldType, artifact, model.colors ),
note = setFeedbackNote(sheetData[row][col], log.entries[row].error, fields[col], fieldType, log.entries[row].message ),
value = setFeedbackValue(sheetData[row][col], log.entries[row].error, fields[col], fieldType, log.entries[row].newId || "", isSubType );
rowBgColors.push(bgColor);
rowNotes.push(note);
rowValues.push(value);
} else {
rowBgColors.push(setFeedbackBgColor(sheetData[row][col], false, fields[col], fieldType, artifact, model.colors ));
rowNotes.push(null);
rowValues.push(sheetData[row][col]);
}
}
bgColors.push(rowBgColors);
notes.push(rowNotes);
values.push(rowValues);
}
sheetRange.setBackgrounds(bgColors).setNotes(notes).setValues(values);
return log;
}
}
// function that reviews a specific cell against it's field and errors for providing UI feedback on errors
// @param: cell - value contained in specific cell beinq queried
// @param: error - bool flag as to whether the entire row the cell is in contains an error
// @param: field - the field specific to the cell
// @param: fieldType - enum information about field types
// @param: artifact - the currently selected artifact
// @param: colors - object of colors to use based on different conditions
function setFeedbackBgColor (cell, error, field, fieldType, artifact, colors) {
if (error) {
// if we have a validation error, we can highlight the relevant cells if the art has no sub type
if (!artifact.hasSubType) {
if (field.required && cell === "") {
return colors.warning;
} else {
// keep original formatting
if (field.type == fieldType.subId || field.type == fieldType.id || field.unsupported) {
return colors.bgReadOnly;
} else {
return null;
}
}
// otherwise highlight the whole row as we don't know the cause of the problem
} else {
return colors.warning;
}
// no errors
} else {
// keep original formatting
if (field.type == fieldType.subId || field.type == fieldType.id || field.unsupported) {
return colors.bgReadOnly;
} else {
return null;
}
}
}
// function that reviews a specific cell against it's field and sets any notes required