-
Notifications
You must be signed in to change notification settings - Fork 22
/
autoCrat.gs
2059 lines (1870 loc) · 86.5 KB
/
autoCrat.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
var scriptTitle = "autoCrat Script V4.4.0 (10/20/13)";
var scriptName = "autoCrat"
var analyticsId = 'UA-30983014-1'
// Written by Andrew Stillman for New Visions for Public Schools
// Published under GNU General Public License, version 3 (GPL-3.0)
// See restrictions at http://www.opensource.org/licenses/gpl-3.0.html
// Support and contact at http://www.youpd.org/autocrat
//Want to run autoCrat on a time-based trigger?
//Set time triggers on the autoCrat_onFormSubmit function.
var AUTOCRATIMAGEURL = 'https://c04a7a5e-a-3ab37ab8-s-sites.googlegroups.com/a/newvisions.org/data-dashboard/searchable-docs-collection/autoCrat_icon.gif?attachauth=ANoY7crV8whTTm4tyWEhFrNIM8Yt6RdYthydKlFA4gpIovpihpZdsviIZ0_D42FJXHSxpZnRFyJdSj7iCS5KMTjv9VYHGfctNojT3Tckh2zJHB5AlEwZIqj2uYdKPz8Zl6JtsUTWIYzLCoCxM-NvPWlji1fL9LGjIx1e-AKmz6qnxq2K_rC9zCiENHHaap9Lyq9W4umEoeYWtqWykApce9wtLXhFYEJ7uLN65vLGDKl5Ao5OHwyTG3COIIij-qsufuMjFr2WtHAK&attredirects=0';
function onInstall() {
onOpen();
}
//onOpen is part of the Google Apps Script library. It runs whenever the spreadsheet is opened.
//Adds script menu to the spreadsheet
//Sometimes this seems not to run by itself when the script is installed
//and needs to be run manually the first time to prompt script authorization.
function onOpen() {
var ss = SpreadsheetApp.getActive();
var menuEntries = [];
menuEntries.push({name: "What is autoCrat?", functionName: "autoCrat_whatIs"});
menuEntries.push({name: "Run initial configuration", functionName: "autoCrat_preconfig"});
ss.addMenu("autoCrat", menuEntries);
autoCrat_initialize();
}
//This function is responsible for configuring the script upon first install.
//Subsequently, adds the menu of dropdown items based on previous actions by the user, as stored in script properties.
function autoCrat_initialize() {
var ss = SpreadsheetApp.getActive();
var menuEntries = [];
menuEntries.push({name: "What is autoCrat?", functionName: "autoCrat_whatIs"});
var preconfigStatus = ScriptProperties.getProperty('preconfigStatus');
if (preconfigStatus) {
menuEntries.push({name: "Step 1: Choose Template Doc", functionName: "autoCrat_defineTemplate"});
} else {
menuEntries.push({name: "Run initial configuration", functionName: "autoCrat_preconfig"});
}
var fileId = ScriptProperties.getProperty('fileId');
if ((fileId)&&(!fileId=="")) {
menuEntries.push({name: "Step 2: Select Source Data", functionName: "autoCrat_defineSettings"});
var sheetName = ScriptProperties.getProperty('sheetName');
var mappingString = ScriptProperties.getProperty('mappingString');
var fileSetting = ScriptProperties.getProperty('fileSetting');
var emailSetting = ScriptProperties.getProperty('emailSetting');
if ((sheetName)&&(!sheetName=="")) {
menuEntries.push({name: "Step 3: Set Merge Conditions", functionName: "autoCrat_setMergeConditions"});
}
menuEntries.push({name: "Step 4: Set Field Mappings", functionName: "autoCrat_mapFields"});
}
if ((mappingString)&&(!mappingString=="")) {
menuEntries.push({name: "Step 5: Set Merge Type", functionName: "autoCrat_runMergeConsole"});
}
if (((fileSetting)||(emailSetting))&&(mappingString)&&(!mappingString=="")) {
menuEntries.push({name: "Step 6: Preview/Run Merge", functionName: "autoCrat_runMergePrompt"});
}
if (((fileSetting)||(emailSetting))&&(mappingString)&&(!mappingString=="")) {
menuEntries.push({name: "Advanced options", functionName: "autoCrat_advanced"});
}
ss.addMenu("autoCrat", menuEntries);
if ((preconfigStatus)&&(!(fileId))) {
autoCrat_defineTemplate();
}
}
function autoCrat_advanced() {
var ss = SpreadsheetApp.getActive();
var app = UiApp.createApplication().setTitle("Advanced options").setHeight(130).setWidth(290);
var quitHandler = app.createServerHandler('autoCrat_quitUi');
var handler1 = app.createServerHandler('detectFormSheet');
var button1 = app.createButton('Copy down formulas on form submit').addClickHandler(quitHandler).addClickHandler(handler1);
var handler2 = app.createServerHandler('autoCrat_extractorWindow');
var button2 = app.createButton('Package this system for others to copy').addClickHandler(quitHandler).addClickHandler(handler2);
var handler3 = app.createServerHandler('autoCrat_institutionalTrackingUi');
var button3 = app.createButton('Manage your usage tracker settings').addClickHandler(quitHandler).addClickHandler(handler3);
var panel = app.createVerticalPanel();
panel.add(button1);
panel.add(button2);
panel.add(button3);
app.add(panel);
ss.show(app);
return app;
}
function autoCrat_quitUi(e) {
var app = UiApp.getActiveApplication();
app.close();
return app;
}
function autoCrat_setFormTrigger() {
var ssKey = SpreadsheetApp.getActiveSpreadsheet().getId();
ScriptApp.newTrigger('autoCrat_onFormSubmit').forSpreadsheet(ssKey).onFormSubmit().create();
}
//onSubmit is part of the Google Apps Script library. It runs whenever a Google Form is submitted.
//Checks to see if a merge method has been set and the "trigger on form submit" option has been saved in the
//and fires off the merge.
//Note that the merge will only execute for a record if there is no value in the "Merge Status."
//Code for handling this condition is in the runMerge function
function autoCrat_onFormSubmit() {
var lock = LockService.getPublicLock();
lock.waitLock(120000);
var ssKey = ScriptProperties.getProperty('ssKey');
var ss = SpreadsheetApp.openById(ssKey);
var formTrigger = ScriptProperties.getProperty('formTrigger');
var fileSetting = ScriptProperties.getProperty('fileSetting');
var emailSetting = ScriptProperties.getProperty('emailSetting');
if ((formTrigger == "true")&&(fileSetting == "true") || (formTrigger == "true")&&(emailSetting == "true")) {
autoCrat_waitForFormulaCaddy(ss)
autoCrat_runMerge();
}
lock.releaseLock();
}
//Function to handle the creation of the "Test/Run Merge" GUI panel.
function autoCrat_runMergeConsole() {
var ss = SpreadsheetApp.getActive();
var app = UiApp.createApplication();
app.setTitle("Step 5: Set Merge Type");
app.setHeight("500");
var fileId = ScriptProperties.getProperty('fileId');
if (!fileId) {
Browser.msgBox("You must select a template file before you can run a merge.");
autoCrat_defineTemplate();
return;
}
var mappingString = ScriptProperties.getProperty('mappingString');
if (!mappingString) {
Browser.msgBox("You must map document fields before you can run a merge.");
autoCrat_mapFields();
return;
}
var sheetName = ScriptProperties.getProperty('sheetName');
if (!sheetName) {
Browser.msgBox("You must select a source data sheet before you can run a merge.");
autoCrat_defineSettings();
return;
}
//create spinner graphic to show upon button click awaiting merge completion
var refreshPanel = app.createFlowPanel();
refreshPanel.setId('refreshPanel');
refreshPanel.setStyleAttribute("width", "100%");
refreshPanel.setStyleAttribute("height", "500px");
refreshPanel.setVisible(false);
//Adds the graphic for the waiting period before merge completion. Set invisible until client handler
//is called by button click
var spinner = app.createImage(AUTOCRATIMAGEURL);
spinner.setVisible(false);
spinner.setStyleAttribute("position", "absolute");
spinner.setStyleAttribute("top", "220px");
spinner.setStyleAttribute("left", "220px");
spinner.setId("dialogspinner");
// Build the panel
var panel = app.createVerticalPanel().setId("fieldMappingPanel");
var varScrollPanel = app.createScrollPanel().setHeight("150px").setStyleAttribute('backgroundColor', 'whiteSmoke');
var scrollPanel = app.createScrollPanel().setHeight("350px");
panel.setStyleAttribute("width", "100%");
var folderLabel = app.createLabel().setId("folderLabel").setWidth("100%");
folderLabel.setText("Select the destination folder(s) for your merged documents. Primary folder must be in the same folder as this spreadsheet. Assign secondary folder(s) using valid folder key(s). Separate multiple with commas. Can be a variable that provides folder key.").setStyleAttribute("clear","right");
var folderListBox = app.createListBox().setName("destinationFolderId").setId("destFolderListBox").setWidth("210px");
folderListBox.addItem('Select primary destination folder').setStyleAttribute("clear","right");
var secondaryFolder = app.createTextBox().setName('secondaryFolderId').setWidth("260px").setValue("Optional: Additional folder key(s) here").setStyleAttribute('color', 'grey');
var secondaryClickHandler = app.createClientHandler().forTargets(secondaryFolder).setStyleAttribute('color', 'black');
secondaryFolder.addMouseDownHandler(secondaryClickHandler);
// Build listbox for folder destination options. Limit to first 20 folders to avoid
// Google server errors.
var parent = DocsList.getFileById(ss.getId()).getParents()[0];
if (!(parent)) {
parent = DocsList.getRootFolder();
}
var folders = parent.getFolders();
if (folders.length>0) {
for (var i = 0; i<folders.length; i++) {
var name = folders[i].getName();
var id = folders[i].getId();
folderListBox.addItem(name, id);
}
} else {
var newFolderId = parent.createFolder("New Merged Document Folder");
folderListBox.addItem("New Merged Document Folder", newFolderId);
folderListBox.setSelectedIndex(1);
}
var fileToFolderCheckBox = app.createCheckBox().setId("fileToFolderCheckBox").setName("fileToFolderCheckValue");
fileToFolderCheckBox.setText("Save merged files to Docs").setStyleAttribute("clear","right");;
var fileToFolderCheckBoxFalse = app.createCheckBox().setId("fileToFolderCheckBoxFalse").setName("fileToFolderCheckValueFalse").setVisible(false);
fileToFolderCheckBoxFalse.setText("Save merged files to Docs").setVisible(false).setStyleAttribute("clear","right");
//Preset to previously used folder value if it exists
var destinationFolderId = ScriptProperties.getProperty('destinationFolderId');
if ((destinationFolderId)&&(destinationFolderId!='')) {
//autoCrat_getFolderIndex is a custom built function that looks up where the saved folder is in the list
var index = autoCrat_getFolderIndex(destinationFolderId)+1;
folderListBox.setItemSelected(index, true);
}
var secondaryFolderId = ScriptProperties.getProperty('secondaryFolderId');
if ((secondaryFolderId)&&(secondaryFolderId!='')) {
secondaryFolder.setValue(secondaryFolderId).setStyleAttribute('color','black');
}
//build the rest of the panel field and checkboxes.
//Checks for pre-set values in Script Properties and pre-populates fields
var fileNameLabel = app.createLabel().setId("fileNameLabel");
var fileNameStringBox = app.createTextBox().setId("fileNameString").setName('fileNameString');
fileNameStringBox.setWidth("100%");
var fileNameStringValue = ScriptProperties.getProperty('fileNameString');
if (fileNameStringValue) {
fileNameStringBox.setValue(fileNameStringValue);
}
var fileNameHelpLabel = app.createLabel().setId("fileNameHelpLabel");
var sheetName = ScriptProperties.getProperty('sheetName');
var sheetFieldNames = autoCrat_fetchSheetHeaders(sheetName);
var normalizedSheetFieldNames = autoCrat_normalizeHeaders(sheetFieldNames);
var fileNameHelpText = "This setting determines the file name for each merged document.";
fileNameLabel.setText("File naming convention to use:");
fileNameHelpLabel.setText(fileNameHelpText);
fileNameHelpLabel.setStyleAttribute("color","grey");
var fileTypeLabel = app.createLabel().setText("Select the file type you want to create");
var fileTypeSelectBox = app.createListBox().setId("fileTypeSelectBox").setName("fileType");
fileTypeSelectBox.addItem("Google Doc")
.addItem("PDF");
var fileType = ScriptProperties.getProperty('fileType');
if (fileType=='Google Doc') {
fileTypeSelectBox.setSelectedIndex(0);
}
if (fileType=='PDF') {
fileTypeSelectBox.setSelectedIndex(1);
}
var linkCheckBox = app.createCheckBox('Save links to merged Docs in spreadsheet').setId('linkToDoc').setName('linkToDoc');
var linkToDoc = ScriptProperties.getProperty('linkToDoc');
if (linkToDoc=="true") {
linkCheckBox.setValue(true);
}
var fileId = ScriptProperties.getProperty("fileId");
var sheetName = ScriptProperties.getProperty("sheetName");
var mappingString = ScriptProperties.getProperty("mappingString");
//add server and client handlers and callbacks to button
var saveRunSettingsHandler = app.createServerHandler('autoCrat_saveRunSettings').addCallbackElement(panel);
var spinnerHandler = app.createClientHandler().forTargets(spinner).setVisible(true).forTargets(panel).setStyleAttribute('opacity', '0.5');
var button = app.createButton().setId("runMergeButton").addClickHandler(saveRunSettingsHandler);
button.addClickHandler(spinnerHandler);
button.setText("Save Settings");
/*check for pre-existing values and preset checkbox and visibilities accordingly
checkboxes fire off client handlers to make sub-panels visible when checked
Below is a bit of ridiculous javascript trickery to work around the dire limitations
of checkbox handlers, which don't allow for checked-unchecked
state to be recognized by the handler...hint, hint Googlers.
The solution is to create two checkboxes, one for the "checked" state and one for the "unchecked"
and fire a different handler, alternately hiding one of the two checkboxes and using
server handlers to reset their checked status.
The user only ever sees one checkbox
*/
var fileSetting = ScriptProperties.getProperty('fileSetting');
var fileInfoPanel = app.createVerticalPanel().setId("fileInfoPanel");
if (fileSetting=="true") {
fileToFolderCheckBox.setVisible(true).setValue(true);
fileToFolderCheckBoxFalse.setVisible(false).setValue(true);
fileInfoPanel.setVisible(true);
} else {
fileToFolderCheckBox.setVisible(false).setValue(false);
fileToFolderCheckBoxFalse.setVisible(true).setValue(false);
fileInfoPanel.setVisible(false);
}
var fileToEmailCheckBox = app.createCheckBox().setId("fileToEmailCheckBox").setName("fileToEmailCheckValue");
fileToEmailCheckBox.setText("Send merged files via Email").setEnabled(false);
var fileToEmailCheckBoxFalse = app.createCheckBox().setId("fileToEmailCheckBoxFalse").setName("fileToEmailCheckValueFalse").setVisible(false);
fileToEmailCheckBoxFalse.setText("Email and/or share merged documents").setVisible(false);
var emailLabel = app.createLabel().setId("emailRecipientsLabel");
emailLabel.setText("Recepient email addresses:");
var emailStringBox = app.createTextBox().setId("emailStringBox").setName('emailString');
emailStringBox.setWidth("100%");
var emailStringValue = ScriptProperties.getProperty('emailString');
if (emailStringValue) {
emailStringBox.setValue(emailStringValue);
}
var emailHelpLabel = app.createLabel().setId("emailHelpLabel");
var emailHelpText = "Emails must be separated by commas.";
emailHelpLabel.setText(emailHelpText);
emailHelpLabel.setStyleAttribute("color","grey");
var emailSubjectLabel = app.createLabel().setText('Email subject:');
var emailSubjectBox = app.createTextBox().setId("emailSubjectBox").setName("emailSubject");
emailSubjectBox.setWidth("100%");
var emailSubjectPreset =ScriptProperties.getProperty('emailSubject');
if (emailSubjectPreset) {
emailSubjectBox.setValue(emailSubjectPreset);
}
var bodyPrefixHelpLabel = app.createLabel().setId("bodyPrefixLabel").setText('Short note to recipients:');
var bodyPrefixTextArea = app.createTextArea().setId("bodyPrefixTextArea").setName("bodyPrefix");
bodyPrefixTextArea.setHeight("75px").setWidth("100%");
var bodyPrefix = ScriptProperties.getProperty('bodyPrefix');
if (bodyPrefix != null) {
bodyPrefixTextArea.setValue(bodyPrefix);
}
var emailAttachmentLabel = app.createLabel().setText("Attachment type:");
var emailAttachmentListBox = app.createListBox().setId("emailAttachmentListBox").setName("emailAttachment");
emailAttachmentListBox.addItem("PDF")
.addItem("Recipient-view-only Google Doc")
.addItem("Recipient-editable Google Doc");
var emailInfoPanel = app.createVerticalPanel().setId("emailInfoPanel");
var attachmentPreset = ScriptProperties.getProperty('emailAttachment');
if(attachmentPreset) {
switch (attachmentPreset) {
case "PDF":
emailAttachmentListBox.setSelectedIndex(0);
break;
case "Recipient-view-only Google Doc":
emailAttachmentListBox.setSelectedIndex(1);
break;
case "Recipient-editable Google Doc":
emailAttachmentListBox.setSelectedIndex(2);
break;
default:
emailAttachmentListBox.setSelectedIndex(0);
}
}
//check for pre-existing value and preset checkbox and visibilities accordingly
var emailSetting = ScriptProperties.getProperty('emailSetting');
var emailInfoPanel = app.createVerticalPanel().setId("emailInfoPanel");
if (emailSetting=="true") {
fileToEmailCheckBox.setVisible(true).setValue(true);
fileToEmailCheckBoxFalse.setVisible(false).setValue(true);
emailInfoPanel.setVisible(true);
} else {
fileToEmailCheckBox.setVisible(false).setValue(false);
fileToEmailCheckBoxFalse.setVisible(true).setValue(false);
emailInfoPanel.setVisible(false);
}
// more crazy trickery for checkboxes
var fileUnCheckHandler = app.createClientHandler().forTargets(fileToFolderCheckBox, fileInfoPanel).setVisible(false)
.forTargets(fileToFolderCheckBoxFalse).setVisible(true)
.forTargets(fileToEmailCheckBox).setEnabled(false)
.forTargets(fileToEmailCheckBoxFalse).setEnabled(false)
var unSetCheck = app.createServerHandler('autoCrat_unsetFileCheck').addCallbackElement(fileToFolderCheckBox);
var fileCheckHandler = app.createClientHandler().forTargets(fileToFolderCheckBox, fileInfoPanel).setVisible(true)
.forTargets(fileToFolderCheckBoxFalse).setVisible(false)
.forTargets(fileToEmailCheckBoxFalse).setEnabled(true)
.forTargets(fileToEmailCheckBox).setEnabled(true);
var setCheck = app.createServerHandler('autoCrat_setFileCheck').addCallbackElement(fileToFolderCheckBox);
fileToFolderCheckBox.addClickHandler(unSetCheck).addClickHandler(fileUnCheckHandler);
fileToFolderCheckBoxFalse.addClickHandler(fileCheckHandler).addClickHandler(setCheck);
fileInfoPanel.setStyleAttribute("width","100%");
fileInfoPanel.setStyleAttribute("backgroundColor","#F5F5F5");
fileInfoPanel.setStyleAttribute("padding","5px");
fileInfoPanel.add(folderLabel);
var folderPanel = app.createHorizontalPanel();
folderPanel.add(folderListBox).add(secondaryFolder);
fileInfoPanel.add(folderPanel);
fileInfoPanel.add(fileNameLabel);
fileInfoPanel.add(fileNameStringBox);
fileInfoPanel.add(fileNameHelpLabel);
fileInfoPanel.add(fileTypeLabel);
fileInfoPanel.add(fileTypeSelectBox);
fileInfoPanel.add(linkCheckBox);
app.add(refreshPanel);
panel.add(fileToFolderCheckBox);
panel.add(fileToFolderCheckBoxFalse);
panel.add(fileInfoPanel);
var emailUnCheckHandler = app.createClientHandler().forTargets(fileToEmailCheckBox, emailInfoPanel).setVisible(false)
.forTargets(fileToEmailCheckBoxFalse).setVisible(true);
var emailUnSetCheck = app.createServerHandler('autoCrat_unSetEmailCheck').addCallbackElement(fileToEmailCheckBox);
var emailCheckHandler = app.createClientHandler().forTargets(fileToEmailCheckBox, emailInfoPanel).setVisible(true)
.forTargets(fileToEmailCheckBoxFalse).setVisible(false);
var emailSetCheck = app.createServerHandler('autoCrat_setEmailCheck').addCallbackElement(fileToEmailCheckBox);
fileToEmailCheckBox.addClickHandler(emailUnSetCheck).addClickHandler(emailUnCheckHandler);
fileToEmailCheckBoxFalse.addClickHandler(emailCheckHandler).addClickHandler(emailSetCheck);
if ((fileSetting == "false")||(!fileSetting)) {
fileToEmailCheckBox.setEnabled(false).setValue(false);
fileToEmailCheckBoxFalse.setEnabled(false).setValue(false);
}
if (fileSetting == "true") {
fileToEmailCheckBox.setEnabled(true);
fileToEmailCheckBoxFalse.setEnabled(true);
}
emailInfoPanel.setStyleAttribute("width","100%");
emailInfoPanel.setStyleAttribute("backgroundColor","#F5F5F5");
emailInfoPanel.setStyleAttribute("padding","5px");
emailInfoPanel.add(emailLabel);
emailInfoPanel.add(emailStringBox);
emailInfoPanel.add(emailHelpLabel);
emailInfoPanel.add(emailSubjectLabel);
emailInfoPanel.add(emailSubjectBox);
emailInfoPanel.add(bodyPrefixHelpLabel);
emailInfoPanel.add(bodyPrefixTextArea);
emailInfoPanel.add(emailAttachmentLabel);
emailInfoPanel.add(emailAttachmentListBox);
panel.add(fileToEmailCheckBox);
panel.add(fileToEmailCheckBoxFalse);
panel.add(emailInfoPanel);
var formTrigger = ScriptProperties.getProperty('formTrigger');
var mergeTriggerCheckBox = app.createCheckBox().setText("Trigger merge on form submit").setName("formTrigger");
if (formTrigger=="true") {
mergeTriggerCheckBox.setValue(true);
}
panel.add(mergeTriggerCheckBox);
panel.add(button);
//Help text below dynamically loads all field names from the sheet using normalized (camelCase) sheet headers
var fieldHelpText = "Use these variables to include values from the spreadsheet in any of the fields below.";
var fieldHelpLabel = app.createLabel().setText(fieldHelpText);
var fieldHelpTable = app.createFlexTable();
fieldHelpTable.setWidget(0, 0, app.createLabel("$currDate (adds the current date in mm.dd.yy format)")).setStyleAttribute('color', 'blue');
for (var i = 0; i<normalizedSheetFieldNames.length; i++) {
var variable = app.createLabel("$"+normalizedSheetFieldNames[i]).setStyleAttribute('color', 'blue');
fieldHelpTable.setWidget(i+1, 0, variable)
}
var instructions = app.createLabel().setText("Note: Merge will only execute for rows with no entry in the \"Merge Status\" column, and that meet any \"Merge conditions\" you may have set.");
instructions.setStyleAttribute("font-weight", "bold");
panel.add(instructions);
app.add(fieldHelpLabel);
varScrollPanel.add(fieldHelpTable);
scrollPanel.add(panel);
app.add(varScrollPanel);
app.add(refreshPanel);
app.add(scrollPanel);
app.add(spinner);
ss.show(app);
}
// Nutty server handler to always uncheck the ghost checkbox that shows only when true checkbox is clicked
function autoCrat_unSetEmailCheck () {
var app = UiApp.getActiveApplication();
var fileToEmailCheckBox = app.getElementById('fileToEmailCheckBox');
fileToEmailCheckBox.setValue(false);
var fileToEmailCheckBoxFalse = app.getElementById('fileToEmailCheckBoxFalse');
fileToEmailCheckBoxFalse.setValue(false);
return app;
}
// Nutty server handler to always uncheck the ghost checkbox that shows only when false checkbox is clicked
function autoCrat_setEmailCheck () {
var app = UiApp.getActiveApplication();
var fileToEmailCheckBox = app.getElementById('fileToEmailCheckBox');
fileToEmailCheckBox.setValue(true);
var fileToEmailCheckBoxFalse = app.getElementById('fileToEmailCheckBoxFalse');
fileToEmailCheckBoxFalse.setValue(false);
return app;
}
// More of the same craziness
function autoCrat_unsetFileCheck () {
var app = UiApp.getActiveApplication();
var fileToFolderCheckBox = app.getElementById('fileToFolderCheckBox');
fileToFolderCheckBox.setValue(false);
var fileToFolderCheckBoxFalse = app.getElementById('fileToFolderCheckBoxFalse');
fileToFolderCheckBoxFalse.setValue(false);
return app;
}
function autoCrat_setFileCheck () {
var app = UiApp.getActiveApplication();
var fileToFolderCheckBox = app.getElementById('fileToFolderCheckBox');
fileToFolderCheckBox.setValue(true);
var fileToFolderCheckBoxFalse = app.getElementById('fileToFolderCheckBoxFalse');
fileToFolderCheckBoxFalse.setValue(false);
return app;
}
//This function loads all Test/Run Merge settings into script properties
// and does some handling for different user error scenarios
function autoCrat_saveRunSettings(e) {
var ss = SpreadsheetApp.getActive();
var app = UiApp.getActiveApplication();
var destinationFolderId = e.parameter.destinationFolderId;
var secondaryFolderId = e.parameter.secondaryFolderId;
if (secondaryFolderId=="Optional: Additional folder key(s) here") {
secondaryFolderId = "";
}
var fileSetting = e.parameter.fileToFolderCheckValue;
var emailSetting = e.parameter.fileToEmailCheckValue;
var fileNameString = e.parameter.fileNameString;
var linkToDoc = e.parameter.linkToDoc;
var emailString = e.parameter.emailString;
var fileType = e.parameter.fileType;
var emailSubject = e.parameter.emailSubject;
var bodyPrefix = e.parameter.bodyPrefix;
var emailAttachment = e.parameter.emailAttachment;
var formTrigger = e.parameter.formTrigger;
if (linkToDoc=="true") {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheetName = ScriptProperties.getProperty('sheetName');
var headers = autoCrat_fetchSheetHeaders(sourceSheetName);
var sheet = ss.getSheetByName(sourceSheetName);
var lastCol = sheet.getLastColumn();
var statusCol = headers.indexOf("Document Merge Status");
var linkCol = headers.indexOf("Link to merged Doc");
if (linkCol == -1) {
sheet.insertColumnBefore(statusCol+1);
sheet.getRange(1, statusCol+1).setValue("Link to merged Doc").setBackgroundColor("black").setFontColor("white").setComment("Required by autoCrat script. Do not change the text of this header");
sheet.insertColumnBefore(statusCol+1);
sheet.getRange(1, statusCol+1).setValue("Merged Doc URL").setBackgroundColor("black").setFontColor("white").setComment("Required by autoCrat script. Do not change the text of this header");
sheet.insertColumnBefore(statusCol+1);
sheet.getRange(1, statusCol+1).setValue("Merged Doc ID").setBackgroundColor("black").setFontColor("white").setComment("Required by autoCrat script. Do not change the text of this header");
}
}
if (formTrigger=="true") {
var triggers = ScriptApp.getScriptTriggers();
var triggerSetFlag = false;
for (var i = 0; i<triggers.length; i++) {
var eventType = triggers[i].getEventType();
var triggerSource = triggers[i].getTriggerSource();
var handlerFunction = triggers[i].getHandlerFunction();
if ((handlerFunction=='autoCrat_onFormSubmit')&&(eventType=="ON_FORM_SUBMIT")&&(triggerSource=="SPREADSHEETS")) {
triggerSetFlag = true;
break;
}
}
if (triggerSetFlag==false) {
autoCrat_setFormTrigger();
}
}
//Do a bunch of error handling stuff for all permutations of settings values that don't make sense
if ((fileSetting=="false")&&(emailSetting=="false")) {
Browser.msgBox("You must select a merge type before you can run a merge job.");
autoCrat_runMergeConsole();
return;
}
if ((fileSetting=="true")&&(!fileNameString)) {
Browser.msgBox("If you are saving your merge job to Docs, you must set a file naming convention.");
autoCrat_runMergeConsole();
return;
}
if ((emailSetting=="true")&&(!emailString)) {
Browser.msgBox("If you want to email this merge job, you must set at least one recipient email address.");
autoCrat_runMergeConsole();
return;
}
ScriptProperties.setProperty('fileSetting',fileSetting);
ScriptProperties.setProperty('fileNameString', fileNameString);
ScriptProperties.setProperty('fileType', fileType);
ScriptProperties.setProperty('linkToDoc', linkToDoc);
ScriptProperties.setProperty('emailSetting',emailSetting);
ScriptProperties.setProperty('emailString', emailString);
ScriptProperties.setProperty('emailSubject', emailSubject);
ScriptProperties.setProperty('bodyPrefix', bodyPrefix);
ScriptProperties.setProperty('emailAttachment', emailAttachment);
ScriptProperties.setProperty('formTrigger', formTrigger);
if (destinationFolderId=="Select destination folder") {
Browser.msgBox("You forgot to choose a destination folder for your merged Docs.");
autoCrat_runMergeConsole();
}
var parent = DocsList.getFileById(ss.getId()).getParents()[0];
if (!(parent)) {
parent = DocsList.getRootFolder();
}
var folders = parent.getFolders();
var indexFlag = 1;
ScriptProperties.setProperty('destinationFolderId', destinationFolderId);
ScriptProperties.setProperty('secondaryFolderId', secondaryFolderId);
var destinationFolderName = DocsList.getFolderById(destinationFolderId).getName();
ScriptProperties.setProperty('destinationFolderName', destinationFolderName);
if (secondaryFolderId.indexOf("$")!=-1) {
ScriptProperties.setProperty('secondaryFolderToken', secondaryFolderId);
}
autoCrat_initialize();
autoCrat_runMergePrompt();
app.close();
return app;
}
function autoCrat_runMergePrompt() {
var app = UiApp.createApplication().setTitle('Step 6: Preview/Run Merge');
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetName = ScriptProperties.getProperty("sheetName");
var sheet = ss.getSheetByName(sheetName);
var headers = autoCrat_fetchSheetHeaders(sheetName);
if (headers.indexOf("")!=-1) {
Browser.msgBox("It appears one of your merge sheet headers is blank, which the autoCrat does not allow!");
app.close();
return app;
}
var panel = app.createVerticalPanel();
var label = app.createLabel("Note that the Google Docs service can cause this script to execute slowly, and there are quotas for the total number of script-generated Docs you can create in a day. Visit https://docs.google.com/macros/dashboard to learn about your quotas. For large merge jobs, the autoCrat will pause and then automatically restart to avoid a service timeout.");
panel.add(label);
//create spinner graphic to show upon button click awaiting merge completion
var refreshPanel = app.createFlowPanel();
refreshPanel.setId('refreshPanel');
refreshPanel.setStyleAttribute("width", "100%");
refreshPanel.setVisible(false);
//Adds the graphic for the waiting period before merge completion. Set invisible until client handler
//is called by button click
var spinner = app.createImage(this.AUTOCRATIMAGEURL).setHeight("220px");
spinner.setStyleAttribute("opacity", "1");
spinner.setStyleAttribute("position", "absolute");
spinner.setStyleAttribute("top", "50px");
spinner.setStyleAttribute("left", "100px");
spinner.setId("dialogspinner");
var waitingLabel1 = app.createLabel("Performing full merge...this sometimes takes a while;)").setStyleAttribute('textAlign', 'center').setVisible(false);
var waitingLabel2 = app.createLabel("Previewing merge on first row...").setStyleAttribute('textAlign', 'center').setVisible(false);
refreshPanel.add(spinner);
refreshPanel.add(waitingLabel1);
refreshPanel.add(waitingLabel2);
app.add(refreshPanel);
var horiz = app.createHorizontalPanel();
var handler1 = app.createServerHandler('autoCrat_runMerge').addCallbackElement(panel);
var spinnerHandler1 = app.createClientHandler().forTargets(refreshPanel).setVisible(true).forTargets(panel).setVisible(false).forTargets(waitingLabel1).setVisible(true);
var spinnerHandler2 = app.createClientHandler().forTargets(refreshPanel).setVisible(true).forTargets(panel).setVisible(false).forTargets(waitingLabel2).setVisible(true);
var button1 = app.createButton('Run merge now').addClickHandler(handler1).addClickHandler(spinnerHandler1);
var handler2 = app.createServerHandler('autoCrat_previewMerge').addCallbackElement(panel);
var button2 = app.createButton('Preview on first row only').addClickHandler(handler2).addClickHandler(spinnerHandler2);
var handler3 = app.createServerHandler('autoCrat_exit').addCallbackElement(panel);
var button3 = app.createButton('Not now, just keep my settings').addClickHandler(handler3);
horiz.add(button2);
horiz.add(button1);
horiz.add(button3);
panel.add(horiz);
app.add(panel);
ss.show(app);
return app;
}
function autoCrat_previewMerge() {
autoCrat_runMerge("true");
}
function autoCrat_exit(e) {
var app = UiApp.getActiveApplication();
app.close();
return app;
}
// This function is where the actual merge is executed, entirely from values stored in
// Script Properties. This is the function that the Google Form submit trigger calls
function autoCrat_runMerge(preview) {
var ssKey = ScriptProperties.getProperty('ssKey');
var ss = SpreadsheetApp.openById(ssKey);
autoCrat_removeTimeoutTrigger();
//Do some more error handling just in case
var fileId = ScriptProperties.getProperty('fileId');
if (!fileId) {
Browser.msgBox("You must select a template file before you can run a merge.");
autoCrat_defineTemplate();
return;
}
var mappingString = ScriptProperties.getProperty('mappingString');
if (!mappingString) {
Browser.msgBox("You must map document fields before you can run a merge.");
autoCrat_defineSettings();
return;
}
var sheetName = ScriptProperties.getProperty('sheetName');
if (!sheetName) {
Browser.msgBox("You must select a source data sheet before you can run a merge.");
autoCrat_defineSettings();
return;
}
var sheet = ss.getSheetByName(sheetName);
var now = new Date();
var headers = autoCrat_fetchSheetHeaders(sheetName);
for (var h=0; h<headers.length; h++) {
if (autoCrat_normalizeHeader(headers[h])=="") {
Browser.msgBox("Ooops! You must have an illegal header value in column " + (h+1) + ". Headers cannot be blank or purely numeric. Please fix.");
return;
}
}
var statusCol = headers.indexOf("Document Merge Status");
var lastCol = sheet.getLastColumn();
var linkCol = headers.indexOf("Link to merged Doc");
var urlCol = headers.indexOf("Merged Doc URL");
var docIdCol = headers.indexOf("Merged Doc ID");
//status message will get concatenated as the logic tree progresses through the merge
var mergeStatusMessage = "";
var fileSetting = ScriptProperties.getProperty('fileSetting');
var fileNameString = ScriptProperties.getProperty('fileNameString');
var linkToDoc = ScriptProperties.getProperty('linkToDoc');
// error handling
if ((!fileNameString)&&(fileSetting==true)) {
Browser.msgBox("You must set a file naming convention before you can run a merge.");
autoCrat_runMergeConsole();
return;
}
var testOnly = preview;
// avoids loading any stale settings from old file or email merges
if (fileSetting == "true") {
var fileTypeSetting = ScriptProperties.getProperty('fileType');
var destFolderId = ScriptProperties.getProperty('destinationFolderId');
var secondaryFolderIdString = ScriptProperties.getProperty('secondaryFolderId');
var secondaryFolderIdArray = [];
secondaryFolderIdString = secondaryFolderIdString.replace(/\s+/g, '');
if ((secondaryFolderIdString)&&(secondaryFolderIdString!='')) {
secondaryFolderIdArray = secondaryFolderIdString.split(",");
}
}
var emailSetting = ScriptProperties.getProperty('emailSetting');
if (emailSetting == "true") {
var emailString = ScriptProperties.getProperty('emailString');
var emailSubject = ScriptProperties.getProperty('emailSubject');
var emailAttachment = ScriptProperties.getProperty('emailAttachment');
}
var row2values = sheet.getRange(2,1,1,sheet.getLastColumn()).getValues()[0];
if (row2values.indexOf("N/A: This is the formula row.")!=-1) {
sheet.getRange(2,statusCol+1).setValue("N/A: This is the formula row.").setFontColor('white').setBackground('black');
Utilities.sleep(5000);
}
var normalizedHeaders = autoCrat_normalizeHeaders(headers);
var mergeTags = "$"+normalizedHeaders.join(",$");
//this array will be used to do replacements in all file name, subject, and email body settings
mergeTags = mergeTags.split(",");
var fullRange = sheet.getDataRange();
var lastCol = fullRange.getLastColumn();
var lastRow = fullRange.getLastRow();
// copyId will be used to pass the Doc Id of the merged copy through different branches of the merge logic
var copyId = "0";
// Load the merge fields from the template
var mergeFields = autoCrat_fetchDocFields(fileId);
//Create a temporary folder in the case that the user doesn't have
//the "Save merged files to Docs" option checked.
//This folder will be kept if they select the shared Google Docs method
if ((emailSetting == "true") && (fileSetting == "false")) {
var tempFolderId = DocsList.createFolder('Merged Docs from' + now).getId();
}
var count = 0;
//Load conditions and mapping object
var conditionString = ScriptProperties.getProperty('mergeConditions');
var mappingString = ScriptProperties.getProperty('mappingString');
var mappingObject = Utilities.jsonParse(mappingString);
//Load in the range
var range = sheet.getDataRange();
var rowValueArray = range.getValues();
var rowFormatArray = range.getNumberFormats();
var templateFileType = DocsList.getFileById(fileId).getFileType().toString();
templateFileType = templateFileType.charAt(0).toUpperCase() + templateFileType.slice(1);
//Commence the merge loop, run through sheet
for (var i=1; i<lastRow; i++) {
var loopTime = new Date();
var timeElapsed = parseInt(loopTime - now);
if (timeElapsed > 295000) {
autoCrat_preemptTimeout();
return;
}
var rowValues = rowValueArray[i];
var rowFormats = rowFormatArray[i];
//reload sheet to ensure status messages update
var sheet = ss.getSheetByName(sheetName);
// Test conditions on this row
var conditionTest = autoCrat_evaluateConditions(conditionString, 0, rowValues, normalizedHeaders);
//Only run a merge for records that have no existing value in the last column ("Document Merge Status"), and that passes condition test
if ((rowValues[statusCol]=="")&&(conditionTest==true)) {
var sheet = ss.getSheetByName(sheetName);
//First big branch in the merge logic: If file setting is true, do all necessary things
if (fileSetting == "true") {
// custom function replaces "$variables" with values in a string
var fileName = autoCrat_replaceStringFields(fileNameString, rowValues, rowFormats, headers, mergeTags);
var secondaryFolderIds = [];
if (secondaryFolderIdArray.length>0) {
for (var z=0; z<secondaryFolderIdArray.length; z++) {
if (secondaryFolderIdArray[z].indexOf("$")!=-1) {
secondaryFolderIds.push(autoCrat_replaceStringFields(secondaryFolderIdArray[z], rowValues, rowFormats, headers, mergeTags));
} else {
secondaryFolderIds.push(secondaryFolderIdArray[z]);
}
}
}
//Google Doc created by default. Custom function to replace all <<merge tags>> with mapped fields
var copyId = DocsList.getFileById(fileId).makeCopy(fileName).getId();
if (docIdCol!=-1) {
sheet.getRange(i+1, docIdCol+1, 1, 1).setValue(copyId);
SpreadsheetApp.flush();
rowValues = sheet.getRange(i+1, 1, 1, sheet.getLastColumn()).getValues()[0];
}
copyId = autoCrat_makeMergeDoc(copyId, rowValues, rowFormats, destFolderId, secondaryFolderIds, mergeFields, mappingObject);
try {
autoCrat_logDocCreation();
} catch(err) {
}
//PDF created only if set
if (fileTypeSetting == "PDF") {
var pdfId = autoCrat_converToPdf(copyId, destFolderId, secondaryFolderIds);
mergeStatusMessage += "PDF successfully created,";
autoCrat_trashDoc(copyId);
copyId = '';
} else {
mergeStatusMessage += 'Google ' + templateFileType + ' successfully created,';
}
}
//handle the case where the email option is chosen without the save in docs option
//set temporary file name and create the merged file in the temporary folder
if ((emailSetting == "true") && (fileSetting == "false")) {
var tempFileName = "Merged File #" + (i-1);
var copyId = DocsList.getFileById(fileId).makeCopy(tempFileName).getId();
var copyId = autoCrat_makeMergeDoc(copyId, rowValues, rowFormats, tempFolderId, secondaryFolderIds, mergeFields, mappingObject);
}
// 2nd major logic branch in merge
if (emailSetting == "true") {
try {
// replace $variables in strings
var recipients = autoCrat_replaceStringFields(emailString, rowValues, rowFormats, headers, mergeTags);
//remove whitespaces from email strings
recipients = recipients.replace(/\s+/g, '');
//remove trailing commas from email strings
recipients = recipients.replace(/,$/,'');
var subject = autoCrat_replaceStringFields(emailSubject, rowValues, rowFormats, headers, mergeTags);
var bodyPrefix = ScriptProperties.getProperty('bodyPrefix');
var user = Session.getActiveUser().getUserLoginId();
bodyPrefix = autoCrat_replaceStringFields(bodyPrefix, rowValues, rowFormats, headers, mergeTags);
//Time to use a switch case. Woot!
switch (emailAttachment){
case "PDF":
//Hard to grasp, but look to see if PDF already exists from file merge and use it if so
//attach the file and set email properties
if (pdfId) {
var attachment = DocsList.getFileById(pdfId);
var body = '<table style="border:1px; padding:15px; background-color:#DDDDDD"><tr><td>' + user + ' has attached a PDF file to this email.</td><tr></table><br /><br />';
body += bodyPrefix;
MailApp.sendEmail(recipients, subject, body, {htmlBody: body, attachments: attachment});
mergeStatusMessage += "PDF attached in email to " + recipients;
}
// copyId should only exist if PDF option isn't selected in the file method
//attach the file and set email properties
if (copyId) {
var attachment = DocsList.getFileById(copyId).getAs("application/pdf");
attachment.setName(DocsList.getFileById(copyId).getName() + ".pdf");
var body = '<table style="border:1px; padding:15px; background-color:#DDDDDD"><tr><td>' + user + ' has attached a PDF file to this email.</td><tr></table><br /><br />';
body += bodyPrefix;
MailApp.sendEmail(recipients, subject, body, {htmlBody: body, attachments: attachment});
mergeStatusMessage += "PDF attached in email to " + recipients;
}
break;
case "Recipient-view-only Google Doc":
var file = DocsList.getFileById(copyId);
//add email recipients as doc viewers
file.addViewers(recipients.split(","));
var docUrl = file.getUrl();
var docTitle = file.getName();
// Add a little note on sharing as caring
var body = '<table style="border:1px; padding:15px; background-color:#DDDDDD"><tr><td>' + user + ' has just shared this view-only Google ' + templateFileType + ' with you:</td><td><a href = "' + docUrl + '">' + docTitle + '</a></td></tr></table><br /><br />';
body += bodyPrefix;
MailApp.sendEmail(recipients, subject, body, {htmlBody: body});
mergeStatusMessage += " View-only " + templateFileType + " shared with " + recipients + " ";
break;
case "Recipient-editable Google Doc":
var file = DocsList.getFileById(copyId);
//add email recipients as doc editors
file.addEditors(recipients.split(","));
var docUrl = file.getUrl();
var docTitle = file.getName();
var user = Session.getActiveUser().getUserLoginId();
var body = '<table style="border:1px; padding:15px; background-color:#DDDDDD"><tr><td>' + user + ' has just shared this editable Google ' + templateFileType + ' with you:</td><td><a href = "' + docUrl + '">' + docTitle + '</a></td></tr></table><br /><br />';
body += bodyPrefix;
MailApp.sendEmail(recipients, subject, body, {htmlBody: body});
mergeStatusMessage += " Editable " + templateFileType + " shared with " + recipients + " ";
break;
}
} catch(err) {
mergeStatusMessage += err;
}
}
//Purge the file if user doesn't want it saved.
//Leaves files that have been shared as docs in the temporary folder, unless
//the user has specified the folder
if ((emailSetting == "true") && (fileSetting == "false") && (emailAttachment=="PDF")){
mergeStatusMessage += ", file not saved in Docs."
autoCrat_trashDoc(copyId);
}
mergeStatusMessage += now;
if ((linkToDoc=="true")&&((copyId)||(pdfId))) {
var range1 = sheet.getRange(i+1, linkCol+1, 1, 1);
var range2 = sheet.getRange(i+1, urlCol+1, 1, 1);
var range3 = sheet.getRange(i+1, docIdCol+1, 1, 1);
var range4 = sheet.getRange(i+1, statusCol+1, 1, 1);
if (pdfId!='') {
var mergeFileId = pdfId;
}
if (copyId!='') {
var mergeFileId = copyId;
}
var mergeFile = DocsList.getFileById(mergeFileId)
var url = mergeFile.getUrl();
var urlValue = [[url]];
var copyIdValue = [[mergeFileId]];
var mergeTitle = mergeFile.getName();
var link = [['=hyperlink("' + url + '", "' + mergeTitle + '")']];
var mergeStatusMessage = [[mergeStatusMessage]];
range1.setValues(link);
range2.setValues(urlValue);
range3.setValues(copyIdValue);
range4.setValues(mergeStatusMessage);
} else {
var range = sheet.getRange(i+1, statusCol+1);
range.setValue(mergeStatusMessage);
}
mergeStatusMessage = "";
count = count+1;
}
if ((emailSetting == "true") && (fileSetting == "false") && (emailAttachment=="PDF")){
var folder = DocsList.getFolderById(tempFolderId);
folder.setTrashed(true);
}
if ((testOnly=="true")&&(count>0)) { break; }
}
//Extra fancy merge completion confirmation
//Even fancier: What would it take to have a progress bar embedded in the loop?
if (count!=0) {
Browser.msgBox("Merge successfully completed for " + count + " record(s).");
} else {
Browser.msgBox("For some reason, no record(s) were successfully merged. If you haven't cleared the merge-status messages, that could be the issue.");
}
}
// This function subs in row values for $variables
function autoCrat_replaceStringFields(string, rowValues, rowFormats, headers, mergeTags) {