-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCode.gs
1110 lines (972 loc) · 34.1 KB
/
Code.gs
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
// See https://github.com/elesel/callings-tracker
"use strict";
var VERSION = '0.7.7';
var ABOUT_URL = 'https://github.com/elesel/callings-tracker';
var NAME_PARSER_FNF = /^(.+)\s+(\S+)$/;
var NAME_PARSER_LNF = /^(\S+?),\s+(.+)$/;
var NAME_PARSER_LOOKUP = /^(.+)\s+\((.+)\)$/;
var HEADER_EMPTY = '<empty>';
var LOCK_WAIT = 30000;
var SIDEBAR_TITLE = 'Lookup Helper';
// Define Sheet class and methods
function Sheet(name) {
this.name = name;
this.ref = null;
this.topRow = null;
this.columns = null;
}
Sheet.prototype.exists = function(){
try {
this.getRef();
return true;
} catch (error) {
return false;
}
};
Sheet.prototype.getRef = function(){
if (this.ref) {
return this.ref;
}
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(this.name);
if (! sheet) {
throw "Can't find a sheet named '" + this.name + "'";
}
this.ref = sheet;
return this.ref;
};
Sheet.prototype.getName = function(){
return this.name;
}
Sheet.prototype.getTopRow = function(){
if (this.topRow) {
return this.topRow;
}
var frozenRows = this.getRef().getFrozenRows();
if (frozenRows == 0) {
throw "Header rows on sheet '" + this.name + "' aren't frozen";
}
this.topRow = frozenRows + 1;
return this.topRow;
};
Sheet.prototype.getColumns = function(){
if (this.columns) {
return this.columns;
}
// Create column map
var map = {};
var headerValues = this.getRef().getRange(1, 1, this.getTopRow() - 1, this.getRef().getLastColumn()).getValues();
for (var c = 0; c < headerValues[0].length; c++) {
// Create hierarchical header value
var headers = [];
for (var r = 0; r < headerValues.length; r++) {
var header = headerValues[r][c];
if (header) {
if (header != HEADER_EMPTY) {
headers.push(header);
}
} else {
// Assume it's part of a group of merged cells, look to the left until we find a value
for (var c2 = c; c2 >= 0; c2--) {
var header = headerValues[r][c2];
if (header) {
if (header != HEADER_EMPTY) {
headers.push(header);
headerValues[r][c] = header;
}
break;
}
}
}
}
var header = headers.join('/');
// Store in map
var cBase1 = c + 1;
if (header) {
if (header in map) {
// Multiple columns with the same name--handle as array
if (Array.isArray(map[header])) {
map[header].push(cBase1);
} else {
map[header] = [map[header], cBase1];
}
} else {
map[header] = cBase1;
}
}
}
Logger.log("columns in " + this.name + ": " + JSON.stringify(map));
this.columns = map;
return this.columns;
};
Sheet.prototype.hasColumn = function(name){
return name in this.getColumns();
};
Sheet.prototype.getColumn = function(name){
if (! this.columns) {
this.getColumns();
}
if (name in this.columns) {
return this.columns[name];
} else {
throw "Can't find column '" + name + "' on sheet '" + this.name + "'";
}
};
// Initialize sheets
var config = {};
loadConfiguration();
var sheets = {
pendingCallings: new Sheet("Callings - Pending"),
currentCallings: new Sheet("Callings - Current"),
archivedCallings: new Sheet("Callings - Archive"),
units: new Sheet("Units"),
leaders: new Sheet("Leaders"),
members: new Sheet("Members"),
positions: new Sheet("Positions"),
lifecycles: new Sheet("Lifecycles"),
actions: new Sheet("Actions")
};
function showProgressMessage(message) {
Logger.log("Showing message: " + message);
SpreadsheetApp.getActiveSpreadsheet().toast(message);
}
function onChange(e) {
Logger.log("In onChange()");
handleEvent(e);
}
function onEdit(e) {
Logger.log("In onEdit()");
handleEvent(e);
}
function handleEvent(e) {
Logger.log("In handleEvent()");
Logger.log("e= " + JSON.stringify(e));
// Look up sheet
var sheet = null;
var eventSheet = e.range ? e.range.getSheet() : SpreadsheetApp.getActiveSheet();
if (eventSheet) {
var eventSheetName = eventSheet.getName();
for (var property in sheets) {
if (sheets.hasOwnProperty(property)) {
if (eventSheetName == sheets[property].getName()) {
sheet = sheets[property];
break;
}
}
}
}
try {
if (! sheet) {
Logger.log("No sheet");
// Let's assume everything changed
addValidations();
return;
} else {
Logger.log('Sheet is ' + sheet.getName());
// Fire appropriate update functions depending on the sheet
if ((sheet === sheets.pendingCallings || sheet === sheets.currentCallings) && e.changeType !== 'REMOVE_ROW') {
if (e.range) {
var startRow = e.range.getRowIndex();
var numRows = e.range.getNumRows();
updateCallingStatus(sheet, startRow, numRows);
updatePendingMembers(startRow, numRows);
} else {
updateCallingStatus(sheet);
updatePendingMembers();
}
}
}
} catch (error) {
SpreadsheetApp.getUi().alert(error);
}
}
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Callings')
//.addItem('Show lookup helper', 'showSidebar')
.addItem('Sort callings', 'sortAllCallings')
.addItem('Organize callings', 'organizeCallings')
.addItem('Update calling status', 'updateAllCallingStatus')
.addItem('Format member list', 'formatMembers')
.addSubMenu(SpreadsheetApp.getUi().createMenu('Setup')
.addItem('Reload configuration', 'reloadConfiguration')
.addItem('Show/hide configuration sheets', 'toggleConfigurationSheets')
.addItem('Create triggers', 'checkAndCreateTriggers')
.addItem('Remove triggers', 'removeTriggers'))
.addItem('About', 'showAbout')
.addToUi();
};
/**
* @OnlyCurrentDoc
*/
function removeTriggers() {
// Check current triggers
var triggers = ScriptApp.getProjectTriggers();
var onChangeTrigger = null;
var onEditTrigger = null;
var triggersRemoved = 0;
triggers.forEach(function(trigger){
if (trigger.getEventType() === ScriptApp.EventType.ON_EDIT && trigger.getHandlerFunction() === 'onEdit') {
ScriptApp.deleteTrigger(trigger);
triggersRemoved++;
}
if (trigger.getEventType() === ScriptApp.EventType.ON_CHANGE && trigger.getHandlerFunction() === 'onChange') {
ScriptApp.deleteTrigger(trigger);
triggersRemoved++;
}
});
var ui = SpreadsheetApp.getUi();
ui.alert(triggersRemoved + ' trigger(s) removed.');
}
/**
* @OnlyCurrentDoc
*/
function checkAndCreateTriggers() {
// Check current triggers
var triggers = ScriptApp.getProjectTriggers();
var hasOnChange = false;
var hasOnEdit = false;
triggers.forEach(function(trigger){
if (trigger.getEventType() === ScriptApp.EventType.ON_EDIT && trigger.getHandlerFunction() === 'onEdit') {
hasOnEdit = true;
}
if (trigger.getEventType() === ScriptApp.EventType.ON_CHANGE && trigger.getHandlerFunction() === 'onChange') {
hasOnChange = true;
}
});
// Add triggers if necessary
var ui = SpreadsheetApp.getUi();
if (! (hasOnEdit && hasOnChange)) {
var response = ui.alert('Do you want to create and run triggers as yourself? Someone (but only one) needs to say yes to this question in order for the spreadsheet to function.', ui.ButtonSet.YES_NO);
if (response === ui.Button.YES) {
var spreadsheet = SpreadsheetApp.getActive();
var triggersCreated = 0;
if (! hasOnEdit) {
ScriptApp.newTrigger('onEdit')
.forSpreadsheet(spreadsheet)
.onEdit()
.create();
triggersCreated++;
}
if (!hasOnChange) {
ScriptApp.newTrigger('onChange')
.forSpreadsheet(spreadsheet)
.onChange()
.create();
triggersCreated++;
}
ui.alert(triggersCreated + ' trigger(s) created.');
}
} else {
ui.alert('Nothing to do! Triggers already created.');
}
}
function showSidebar() {
var ui = HtmlService.createTemplateFromFile('Sidebar')
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle(SIDEBAR_TITLE);
SpreadsheetApp.getUi().showSidebar(ui);
}
function getLookupForCurrentCell() {
var sheet = SpreadsheetApp.getActiveSheet();
var colNum = sheet.getActiveCell().getColumn();
return colNum;
}
function toggleConfigurationSheets() {
try {
var configurationSheets = [
sheets.units,
sheets.leaders,
sheets.members,
sheets.positions,
sheets.lifecycles,
sheets.actions
];
var doHide = null;
configurationSheets.forEach(function(sheet){
if (sheet.exists()) {
var sheetRef = sheet.getRef();
if (doHide == null) {
doHide = ! sheetRef.isSheetHidden();
}
if (doHide) {
sheetRef.hideSheet();
} else {
sheetRef.showSheet();
}
}
});
} catch (error) {
SpreadsheetApp.getUi().alert(error);
}
}
function reloadConfiguration() {
try {
var cache = CacheService.getDocumentCache();
config = {};
addConfigurationValidations();
addValidations();
getLifecycleActions_();
getPositionLifecycles_();
getActionSheets_();
cache.put('config', JSON.stringify(config));
Logger.log('Stored in cache: ' + Object.getOwnPropertyNames(config).sort());
} catch (error) {
SpreadsheetApp.getUi().alert(error);
}
}
function loadConfiguration() {
try {
var cache = CacheService.getDocumentCache();
var tempConfig = cache.get('config');
if (tempConfig != null) {
config = JSON.parse(tempConfig);
Logger.log('Loaded from cache: ' + Object.getOwnPropertyNames(config).sort());
}
} catch (error) {
SpreadsheetApp.getUi().alert(error);
config = {};
}
}
function getMembers_() {
if (config['members']) {
return config['members'];
}
// Get values
var list = getLookupValues_(sheets.members, "Lookup name");
config['members'] = list;
return list;
}
function sortUnits_() {
var sheet = sheets.units.getRef();
sheet.sort(sheets.units.getColumn("Abbreviation"));
sheet.sort(sheets.units.getColumn("Visible"));
}
function getUnits_() {
if (config['units']) {
return config['units'];
}
// Get values
var list = getLookupValues_(sheets.units, "Abbreviation", function(value, row, sheet){
return row[sheet.getColumn("Visible") - 1];
});
config['units'] = list;
return list;
}
function sortLeaders_() {
var sheet = sheets.leaders.getRef();
sheet.sort(sheets.leaders.getColumn("Name"));
sheet.sort(sheets.leaders.getColumn("Visible"));
}
function getLeaders_() {
if (config['leaders']) {
return config['leaders'];
}
// Get values
var list = getLookupValues_(sheets.leaders, "Name", function(value, row, sheet){
return row[sheet.getColumn("Visible") - 1];
});
config['leaders'] = list;
return list;
}
function getPositions_() {
if (config['positions']) {
return config['positions'];
}
// Get values
var list = getLookupValues_(sheets.positions, "Name", function(value, row, sheet){
return row[sheet.getColumn("Visible") - 1];
});
config['positions'] = list;
return list;
}
function getPositionLifecycles_() {
if (config['positionLifecycles']) {
return config['positionLifecycles'];
}
// Grab copy of all data
var sheet = sheets.positions;
var allData = getAllData_(sheet);
// Determine lookup names
var positions = {};
for (var r = 0; r < allData.length; r++) {
var row = allData[r];
var name = row[sheet.getColumn("Name") - 1];
var lifecycle = row[sheet.getColumn("Lifecycle") - 1];
if (name && lifecycle) {
positions[name] = lifecycle;
}
}
config['positionLifecycles'] = positions;
return positions;
}
function sortLifecycles_() {
var sheet = sheets.lifecycles.getRef();
sheet.sort(sheets.lifecycles.getColumn("Name"));
}
function getLifecycleNames_() {
if (config['lifecycles']) {
return config['lifecycles'];
}
// Get values
var list = getLookupValues_(sheets.lifecycles, "Name");
config['lifecycles'] = list;
return list;
}
function getLifecycleActions_() {
if (config['lifecycleActions']) {
return config['lifecycleActions'];
}
// Get all data
var sheet = sheets.lifecycles;
var allData = getAllData_(sheet);
// Get/check column counts
var columnColumns = sheet.getColumn("Column");
var actionColumns = sheet.getColumn("Action");
if (columnColumns.length != actionColumns.length) {
throw "Mismatch in number of Column and Action columns on " + sheets.lifecycles.getName() + " sheet";
}
// Get lifecycles
var lifecycles = {};
for (var r = 0; r < allData.length; r++) {
var row = allData[r];
var name = row[sheet.getColumn("Name") - 1];
// Only get active ones
var actions = [];
if (name) {
// Add default action
var action = row[sheet.getColumn("Default action") - 1];
actions.push({ column: null, action: action });
// Add other actions
for (var i = 0; i < columnColumns.length; i++) {
var column = row[columnColumns[i] - 1];
var action = row[actionColumns[i] - 1];
if (column && action) {
actions.push({ column: column, action: action });
}
}
lifecycles[name] = actions;
}
}
config['lifecycleActions'] = lifecycles;
return lifecycles;
}
function getActionNames_() {
if (config['actionNames']) {
return config['actionNames'];
}
// Get values
var list = getLookupValues_(sheets.actions, "Name");
config['actionNames'] = list;
return list;
}
function getActionSheets_() {
if (config['actionSheets']) {
return config['actionSheets'];
}
// Grab copy of all data
var sheet = sheets.actions;
var allData = getAllData_(sheet);
// Determine lookup names
var actions = {};
for (var r = 0; r < allData.length; r++) {
var row = allData[r];
var name = row[sheet.getColumn("Name") - 1];
var sheetName = row[sheet.getColumn("Sheet") - 1];
if (name && sheetName) {
// Translate sheet name into sheets object reference
for (var property in sheets) {
if (sheets.hasOwnProperty(property)) {
if (sheetName == sheets[property].getName()) {
actions[name] = sheets[property];
}
}
}
}
}
config['actionSheets'] = actions;
return actions;
}
function getAllData_(sheet) {
var startRow = sheet.getTopRow();
return sheet.getRef().getRange(startRow, 1, sheet.getRef().getLastRow() - startRow + 1, sheet.getRef().getLastColumn()).getValues();
}
function getAllCells_(sheet) {
var startRow = sheet.getTopRow();
return sheet.getRef().getRange(startRow, 1, sheet.getRef().getMaxRows() - startRow + 1, sheet.getRef().getMaxColumns()).getValues();
}
function getLookupValues_(sheet, columnName, validationFunction) {
var allData = getAllData_(sheet);
// Get lookup values
var list = [];
for (var r = 0; r < allData.length; r++) {
var row = allData[r];
var value = row[sheet.getColumn(columnName) - 1];
// Validate
if (typeof validationFunction == 'function') {
if (validationFunction(value, row, sheet)) {
list.push(value);
}
} else if (value) {
list.push(value);
}
}
return list;
}
function getCallingSheetNames_() {
var list = [];
list.push(sheets.pendingCallings.getName());
list.push(sheets.currentCallings.getName());
list.push(sheets.archivedCallings.getName());
return list;
}
function addConfigurationValidations() {
var sheet;
// Sort sheets first
if (sheets.units.exists()) {
sortUnits_();
}
if (sheets.leaders.exists()) {
sortLeaders_();
}
sortLifecycles_();
// Add lifecycles list to positions sheet
var lifecyclesRule = SpreadsheetApp.newDataValidation().requireValueInList(getLifecycleNames_()).setAllowInvalid(true).build();
sheet = sheets.positions;
sheet.getRef().getRange(sheet.getTopRow(), sheet.getColumn("Lifecycle"), sheet.getRef().getMaxRows() - sheet.getTopRow() + 1, 1).setDataValidation(lifecyclesRule);
// Add positions columns lists to lifecycle sheet
var positionsColumnsRule = SpreadsheetApp.newDataValidation().requireValueInList(Object.keys(sheets.pendingCallings.getColumns())).setAllowInvalid(true).build();
sheet = sheets.lifecycles;
sheet.getColumn('Column').forEach(function(c){
sheet.getRef().getRange(sheet.getTopRow(), c, sheet.getRef().getMaxRows() - sheet.getTopRow() + 1, 1).setDataValidation(positionsColumnsRule);
});
// Add action names lists to lifecycle sheet
var actionsRule = SpreadsheetApp.newDataValidation().requireValueInList(getActionNames_()).setAllowInvalid(true).build();
sheet = sheets.lifecycles;
sheet.getRef().getRange(sheet.getTopRow(), sheet.getColumn("Default action"), sheet.getRef().getMaxRows() - sheet.getTopRow() + 1, 1).setDataValidation(actionsRule);
sheet.getColumn('Action').forEach(function(c){
sheet.getRef().getRange(sheet.getTopRow(), c, sheet.getRef().getMaxRows() - sheet.getTopRow() + 1, 1).setDataValidation(actionsRule);
});
// Add sheet name lists to actions sheet
var callingSheetsRule = SpreadsheetApp.newDataValidation().requireValueInList(getCallingSheetNames_()).setAllowInvalid(true).build();
sheet = sheets.actions;
sheet.getRef().getRange(sheet.getTopRow(), sheet.getColumn("Sheet"), sheet.getRef().getMaxRows() - sheet.getTopRow() + 1, 1).setDataValidation(callingSheetsRule);
}
function addValidations() {
var sheet;
// Update member names and add validations
updatePendingMembers();
// Add units lists to pending callings sheet
if (sheets.units.exists()) {
var unitsRule = SpreadsheetApp.newDataValidation().requireValueInList(getUnits_()).setAllowInvalid(true).build();
sheet = sheets.pendingCallings;
sheet.getRef().getRange(sheet.getTopRow(), sheet.getColumn("Member/Unit"), sheet.getRef().getMaxRows() - sheet.getTopRow() + 1, 1).setDataValidation(unitsRule);
}
// Add positions lists to pending callings sheet
var positionsRule = SpreadsheetApp.newDataValidation().requireValueInList(getPositions_()).setAllowInvalid(true).build();
sheet = sheets.pendingCallings;
sheet.getRef().getRange(sheet.getTopRow(), sheet.getColumn("Position"), sheet.getRef().getMaxRows() - sheet.getTopRow() + 1, 1).setDataValidation(positionsRule);
// Add leaders lists to pending callings sheet
if (sheets.leaders.exists()) {
var leadersRule = SpreadsheetApp.newDataValidation().requireValueInList(getLeaders_()).setAllowInvalid(true).build();
sheet = sheets.pendingCallings;
sheet.getRef().getRange(sheet.getTopRow(), sheet.getColumn("Extend/Set apart by"), sheet.getRef().getMaxRows() - sheet.getTopRow() + 1, 1).setDataValidation(leadersRule);
}
}
function updateAllCallingStatus() {
// Update calling status
[sheets.pendingCallings, sheets.currentCallings].forEach(function(sheet){
updateCallingStatus(sheet);
});
}
function updateCallingStatus(sheet, startRow, numRows, parentLock) {
// Set defaults for startRow and numRows
startRow = startRow || sheet.getTopRow();
numRows = numRows || sheet.getRef().getLastRow() - sheet.getTopRow() + 1;
// Skip empty sheets
if (startRow < sheet.getTopRow() || numRows < 1) {
return;
}
// Get positions and lifecycles
var lifecycleActions = getLifecycleActions_();
var positionLifecycles = getPositionLifecycles_();
var positionNames = getPositions_();
var actionNames = getActionNames_();
// Get a lock to prevent parallel execution
var lock = parentLock || LockService.getDocumentLock();
lock.waitLock(LOCK_WAIT);
// Grab copy of all data
var allData = sheet.getRef().getRange(startRow, 1, numRows, sheet.getRef().getLastColumn()).getValues();
for (var r = 0; r < allData.length; r++) {
var row = allData[r];
var memberName = row[sheet.getColumn("Member/Name") - 1];
var positionName = row[sheet.getColumn("Position") - 1];
var status = row[sheet.getColumn("Status") - 1];
var newStatus = status;
var sid = row[sheet.getColumn("SID") - 1];
var newSid = sid;
var pid = row[sheet.getColumn("PID") - 1];
var newPid = pid;
if (positionName) {
// Find current action
var lifecycle = lifecycleActions[positionLifecycles[positionName]];
var newStatus = 'Unknown';
if (lifecycle) {
lifecycle.some(function(columnAction){
if (! columnAction.column) {
newStatus = columnAction.action;
} else {
var value = row[sheet.getColumn(columnAction.column) - 1];
if (value && value[0] != '>') {
newStatus = columnAction.action;
} else {
return true;
}
}
});
}
// Look up indexes
var newSid = actionNames.indexOf(newStatus);
var newPid = positionNames.indexOf(positionName);
} else if (memberName) {
newStatus = 'Nominate';
newSid = -1;
newPid = '';
} else {
newStatus = '';
newSid = '';
newPid = '';
}
// Change values only if we have to
if (status !== newStatus) {
row[sheet.getColumn("Status") - 1] = newStatus;
}
if (sid !== newSid) {
row[sheet.getColumn("SID") - 1] = newSid;
}
if (pid !== newPid) {
row[sheet.getColumn("PID") - 1] = newPid;
}
}
// Write columns back
var dataRows = allData.length;
sheet.getRef().getRange(startRow, sheet.getColumn("Status"), dataRows, 1).setValues(
sliceSingleColumn(allData, 0, dataRows, sheet.getColumn("Status") - 1)
);
sheet.getRef().getRange(startRow, sheet.getColumn("SID"), dataRows, 1).setValues(
sliceSingleColumn(allData, 0, dataRows, sheet.getColumn("SID") - 1)
);
sheet.getRef().getRange(startRow, sheet.getColumn("PID"), dataRows, 1).setValues(
sliceSingleColumn(allData, 0, dataRows, sheet.getColumn("PID") - 1)
);
// Flush spreadsheet changes and release the lock if it wasn't inherited
SpreadsheetApp.flush();
if (! parentLock) {
lock.releaseLock();
}
}
function organizeCallings() {
try {
// Sanity check the sheets
if (sheets.pendingCallings.getRef().getMaxColumns() != sheets.currentCallings.getRef().getMaxColumns() || sheets.pendingCallings.getRef().getMaxColumns() != sheets.archivedCallings.getRef().getMaxColumns()) {
throw "Mismatch in number of columns among the callings sheets. They must be the same.";
}
// Get action to sheet mapping
var actionSheets = getActionSheets_();
// Get a lock to prevent parallel execution
var lock = LockService.getDocumentLock();
lock.waitLock(LOCK_WAIT);
// Loop through calling sheets
var changedSheets = [];
[sheets.pendingCallings, sheets.currentCallings].forEach(function(sheet){
// Only continue if there's data
var numRows = sheet.getRef().getLastRow() - sheet.getTopRow() + 1;
if (numRows < 1) {
return;
}
// Sort callings so that we can move contiguous rows
updateCallingStatus(sheet, sheet.getTopRow(), sheet.getRef().getLastRow() - sheet.getTopRow() + 1, lock);
sortCallings(sheet);
// Iterate through all status values
var allData = sheet.getRef().getRange(sheet.getTopRow(), sheet.getColumn("Status"), numRows, 1).getValues();
var startRow = null;
var targetSheet = null;
var rowsMoved = 0;
for (var r = 0; r < allData.length; r++) {
var action = allData[r][0];
var callingsSheet = null;
if (action) {
callingsSheet = actionSheets[action];
}
// Get started
if (startRow == null) {
startRow = r;
targetSheet = callingsSheet;
}
// Handle changes in targetSheet
['previous', 'current'].forEach(function(step){
if ((step == 'previous' && callingsSheet != targetSheet) || (step == 'current' && r == allData.length - 1)) {
if (targetSheet != null && targetSheet.getName() != sheet.getName()) {
// Send rows to another sheet
var endRow = (step == 'previous' ? r - 1 : r);
var realStartRow = startRow + sheet.getTopRow() - rowsMoved;
var realEndRow = endRow + sheet.getTopRow() - rowsMoved;
// Move
Logger.log("Move row " + realStartRow + " through row " + realEndRow + " from sheet " + sheet.getName() + " to sheet " + targetSheet.getName());
var targetRange = moveRows(sheet, targetSheet, realStartRow, realEndRow - realStartRow + 1, targetSheet.getTopRow());
if (targetRange != sheets.PendingCallings) {
targetRange.clearDataValidations();
}
rowsMoved += endRow - startRow + 1;
changedSheets.push(targetSheet);
}
// Reset to current row
startRow = r;
targetSheet = callingsSheet;
}
});
}
});
changedSheets = changedSheets.filter(onlyUnique);
// Sort sheets
changedSheets.forEach(function(sheet){
sortCallings(sheet);
});
// Flush spreadsheet changes and release the lock
SpreadsheetApp.flush();
lock.releaseLock();
// Add validations to pending sheet if changed
if (sheets.pendingCallings in changedSheets) {
addValidations();
}
} catch (error) {
SpreadsheetApp.getUi().alert(error);
}
}
function sortAllCallings() {
sortCallings(sheets.pendingCallings);
sortCallings(sheets.currentCallings);
sortCallings(sheets.archivedCallings);
}
function sortCallings(sheet) {
sheet.getRef().sort(sheet.getColumn("Member/Name"));
sheet.getRef().sort(sheet.getColumn("Extend/Sustain"));
sheet.getRef().sort(sheet.getColumn("PID"));
sheet.getRef().sort(sheet.getColumn("SID"));
}
function formatMembers() {
var sheet = sheets.members;
var lock = LockService.getDocumentLock();
try {
// Get a lock to prevent parallel execution
lock.waitLock(LOCK_WAIT);
// Grab copy of all data
var startRow = sheet.getTopRow();
var allData = getAllData_(sheet);
// Determine lookup names
for (var r = 0; r < allData.length; r++) {
var row = allData[r];
var fullName = row[sheet.getColumn("Full name") - 1].trim();
var age = row[sheet.getColumn("Age") - 1];
var unit = sheet.hasColumn("Unit") ? row[sheet.getColumn("Unit") - 1] : null;
var forcedName = row[sheet.getColumn("Forced name") - 1];
var lookupName = forcedName || reformatNameLnfToShort(fullName);
var details = [];
if (age) {
details.push(age);
}
if (unit) {
details.push(unit);
}
if (details.length > 0) {
lookupName = lookupName + " (" + details.join(", ") + ")";
}
row[sheet.getColumn("Lookup name") - 1] = lookupName;
}
// Write columns back
var dataRows = allData.length;
sheet.getRef().getRange(startRow, sheet.getColumn("Lookup name"), dataRows, 1).setValues(
sliceSingleColumn(allData, 0, dataRows, sheet.getColumn("Lookup name") - 1)
);
} catch (error) {
SpreadsheetApp.getUi().alert(error);
}
// Flush spreadsheet changes and release the lock
SpreadsheetApp.flush();
lock.releaseLock();
// Refresh configuration
reloadConfiguration();
}
function updatePendingMembers(startRow, numRows, parentLock) {
var sheet = sheets.pendingCallings;
// Set defaults for startRow and numRows
startRow = startRow || sheet.getTopRow();
numRows = numRows || sheet.getRef().getMaxRows() - startRow + 1;
// Skip empty sheets
if (startRow < sheet.getTopRow() || numRows < 1) {
return;
}
// Get a lock to prevent parallel execution
var lock = parentLock || LockService.getDocumentLock();
lock.waitLock(LOCK_WAIT);
// Grab copy of all data
var allData = sheet.getRef().getRange(startRow, 1, numRows, sheet.getRef().getMaxColumns()).getValues();
// Build members validation rule
// FIXME: This can't handle more than 500 items now; gotta figure out a fix
//var membersRule = SpreadsheetApp.newDataValidation().requireValueInList(getMembers_()).setAllowInvalid(true).build();
// Clear validations from member name column
sheet.getRef().getRange(startRow, sheet.getColumn("Member/Name"), numRows, 1).clearDataValidations();
// Process rows
var nameChanged = false;
var unitChanged = false;
var rangeStartRow = null;
var rangeStopRow = null;
for (var r = 0; r < allData.length; r++) {
var row = allData[r];
var name = row[sheet.getColumn("Member/Name") - 1];
var result = NAME_PARSER_LOOKUP.exec(name);
if (result != null) {
// Reduce member name cell to just member name
row[sheet.getColumn("Member/Name") - 1] = result[1];
nameChanged = true;
if (sheet.hasColumn("Member/Unit")) {
var unit = row[sheet.getColumn("Member/Unit") - 1];
if (! unit) {
// Add unit only if not already defined
var ageAndUnit = result[2].split(/\s*,\s*/);
var unit = null;
if (ageAndUnit.length > 1) {
unit = ageAndUnit[1];
} else {
unit = ageAndUnit[0];
}
// TODO: Validate unit better
if (unit) {
row[sheet.getColumn("Member/Unit") - 1] = unit;
unitChanged = true;
}
}
}
}
// Update validation pointers
if (! name) {
if (rangeStartRow == null) {
rangeStartRow = r;
}
rangeStopRow = r;
}
// Add validation
if (rangeStopRow != null && (r > rangeStopRow || r == allData.length - 1)) {
// FIXME: Can't set this validation now
//sheet.getRef().getRange(startRow + rangeStartRow, sheet.getColumn("Member/Name"), rangeStopRow - rangeStartRow + 1, 1).setDataValidation(membersRule);
rangeStartRow = null;
rangeStopRow = null;
}
}
// Write columns back
var dataRows = allData.length;
if (nameChanged) {
sheet.getRef().getRange(startRow, sheet.getColumn("Member/Name"), dataRows, 1).setValues(
sliceSingleColumn(allData, 0, dataRows, sheet.getColumn("Member/Name") - 1)
);
}
if (unitChanged) {
sheet.getRef().getRange(startRow, sheet.getColumn("Member/Unit"), dataRows, 1).setValues(
sliceSingleColumn(allData, 0, dataRows, sheet.getColumn("Member/Unit") - 1)
);
}