-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode.gs
More file actions
293 lines (253 loc) · 10.5 KB
/
Copy pathCode.gs
File metadata and controls
293 lines (253 loc) · 10.5 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
/**
* Creates the custom menu.
*/
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('✉️ Envelope Maker')
.addItem('Generate Envelopes', 'showSheetPicker')
.addToUi();
}
/**
* Progress helpers
*/
function setProgress_(current, total) {
PropertiesService.getUserProperties().setProperty(
"MERGE_PROGRESS",
JSON.stringify({ current, total })
);
}
function pollProgress() {
const val = PropertiesService.getUserProperties().getProperty("MERGE_PROGRESS");
return val ? JSON.parse(val) : { current: 0, total: 0 };
}
function resetCancelFlag_() {
PropertiesService.getUserProperties().deleteProperty("CANCEL_MERGE");
}
function setCancelFlag_() {
PropertiesService.getUserProperties().setProperty("CANCEL_MERGE", "true");
}
/**
* Picker Dialog: Sheet + Template + Progress
*/
function showSheetPicker() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheets = ss.getSheets();
const sheetOptions = sheets.map(s => `<option value="${s.getName()}">${s.getName()}</option>`).join('');
// Get parent folder of spreadsheet
const ssFile = DriveApp.getFileById(ss.getId());
const folders = ssFile.getParents();
const parentFolder = folders.hasNext() ? folders.next() : DriveApp.getRootFolder();
// Scan entire Drive for likely templates (WORKING VERSION)
const templateFiles = [];
const files = DriveApp.searchFiles(
'mimeType="application/vnd.google-apps.document" and ' +
'(title contains "template" or title contains "Template" or ' +
' title contains "envelope" or title contains "Envelope")'
);
while (files.hasNext()) {
templateFiles.push(files.next());
}
const templateOptions = templateFiles.map(f => `<option value="${f.getId()}">${f.getName()}</option>`).join('');
const oauthToken = ScriptApp.getOAuthToken(); // Pass OAuth token to HTML
const htmlContent = `
<html>
<head>
<script src="https://apis.google.com/js/api.js"></script>
<script src="https://accounts.google.com/gsi/client"></script>
<script src="https://apis.google.com/js/api.js"></script>
<script src="https://www.gstatic.com/picker/1/picker.js"></script>
</head>
<body style="font-family: 'Roboto', Arial, sans-serif; padding:20px; color:#333;">
<div id="setup">
<label style="font-weight:500;">1. Select Sheet With Addresses</label>
<p style="font-size:12px; color:#5f6368;margin-top:6px;">
Column headers in the sheet should exactly match the placeholder names in your template document.
</p>
<select id="sheetSelect" style="width:100%; padding:8px; margin:8px 0 14px; border:1px solid #dadce0; border-radius:4px;">
${sheetOptions}
</select>
<label style="font-weight:500;">2. Select Template Doc</label>
<p style="font-size:12px; color:#5f6368;margin-top:6px;">
The template should have placeholders like *|Column Name|*.
</p>
<!-- Inline drop-down + picker button -->
<div style="display:flex; align-items:center; gap:6px; margin-bottom:20px;">
<select id="templateSelect" style="flex:1; padding:8px; border:1px solid #dadce0; border-radius:4px;">
<option value="">-- choose a template --</option>
${templateOptions}
</select>
</div>
<button id="mainBtn" onclick="runMerge(false)" style="background:#1a73e8;color:#fff;border:none;padding:12px;border-radius:4px;cursor:pointer;width:100%;font-weight:500;margin-bottom:8px;">Generate All</button>
<button id="testBtn" onclick="runMerge(true)" style="background:#fff;color:#1a73e8;border:1px solid #dadce0;padding:10px;border-radius:4px;cursor:pointer;width:100%;">Test (First Row)</button>
<div id="progressWrap" style="margin-top:16px; display:none;">
<div style="height:6px; background:#e8f0fe; border-radius:3px;">
<div id="bar" style="height:6px; width:0%; background:#1a73e8; border-radius:3px;"></div>
</div>
<div style="display:flex;justify-content: center;gap: 10px;align-items: baseline;">
<p id="progressText" style="font-size:12px; color:#5f6368;text-align:center;margin-top:6px;"></p>
<button id="cancelBtn" onclick="cancelMerge()" style="display:none;font-size:10px;background:#f44336;color:#fff;border:none;padding:4px 6px;border-radius:3px;cursor:pointer;margin-top:8px;">Cancel</button>
</div>
</div>
</div>
<script>
let selectedTemplateId = null;
const oauthToken = '${oauthToken}';
document.getElementById('browseBtn').addEventListener('click', () => {
const view = new google.picker.DocsView(google.picker.ViewId.DOCS)
.setIncludeFolders(true);
const picker = new google.picker.PickerBuilder()
.setAppId('${ScriptApp.getScriptId()}')
.setOAuthToken(oauthToken)
.addView(view)
.setCallback(pickCallback)
.build();
picker.setVisible(true);
});
function pickCallback(data) {
if (data.action === google.picker.Action.PICKED) {
const doc = data.docs[0];
selectedTemplateId = doc.id;
const sel = document.getElementById('templateSelect');
let found = false;
for (let i = 0; i < sel.options.length; i++) {
if (sel.options[i].value === doc.id) {
sel.selectedIndex = i;
found = true;
break;
}
}
if (!found) {
const opt = document.createElement('option');
opt.value = doc.id;
opt.text = doc.name;
opt.selected = true;
sel.add(opt);
}
}
}
function runMerge(isTest) {
const sheetName = document.getElementById('sheetSelect').value;
const templateSelect = document.getElementById('templateSelect');
const templateId = templateSelect.value || selectedTemplateId;
if (!templateId) { alert('Please select a template'); return; }
document.getElementById('mainBtn').disabled = true;
document.getElementById('testBtn').disabled = true;
document.getElementById('progressWrap').style.display = 'block';
document.getElementById('cancelBtn').style.display = 'inline-block';
document.getElementById('progressText').innerText = isTest ? 'Preparing test envelope…' : 'Initializing merge…';
startPolling();
google.script.run
.withFailureHandler(err => {
alert(err.message);
document.getElementById('mainBtn').disabled = false;
document.getElementById('testBtn').disabled = false;
document.getElementById('cancelBtn').style.display = 'none';
})
.withSuccessHandler(() => google.script.host.close())
.startSimpleMerge(sheetName, templateId, isTest);
}
function cancelMerge() {
google.script.run.setCancelFlag_();
document.getElementById('progressText').innerText = 'Cancelling…';
document.getElementById('cancelBtn').disabled = true;
}
function startPolling() {
const poller = setInterval(() => {
google.script.run.withSuccessHandler(p => {
if (!p.total) return;
const pct = Math.round((p.current / p.total) * 100);
document.getElementById('bar').style.width = pct + '%';
document.getElementById('progressText').innerText = 'Processed ' + p.current + ' of ' + p.total;
if (p.current >= p.total) clearInterval(poller);
}).pollProgress();
}, 400);
}
</script>
</body>
</html>
`;
SpreadsheetApp.getUi().showModalDialog(
HtmlService.createHtmlOutput(htmlContent).setWidth(520).setHeight(500),
'✉️ Envelope Maker'
);
}
// Server-side: get parent folder of spreadsheet
function getSpreadsheetFolderId() {
const ssFile = DriveApp.getFileById(SpreadsheetApp.getActiveSpreadsheet().getId());
const folders = ssFile.getParents();
return folders.hasNext() ? folders.next().getId() : DriveApp.getRootFolder().getId();
}
/**
* Extract all *|Tag|* fields from template
*/
function extractTemplateTags_(body) {
const regex = /\*\|([^|]+)\|\*/g;
const tags = new Set();
let match;
while ((match = regex.exec(body.getText())) !== null) {
tags.add(match[1].trim());
}
return [...tags];
}
/**
* Main merge logic with progress and cancellation support
*/
function startSimpleMerge(sheetName, templateId, isTest) {
resetCancelFlag_();
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName(sheetName);
const values = sheet.getDataRange().getValues();
const headers = values.shift();
const limit = isTest ? 1 : values.length;
setProgress_(0, limit);
const outFile = DriveApp.getFileById(templateId).makeCopy((isTest ? "TEST_" : "") + "Envelopes_" + sheetName);
const doc = DocumentApp.openById(outFile.getId());
const body = doc.getBody();
const templateDoc = DocumentApp.openById(templateId);
const templateBody = templateDoc.getBody();
const templateTags = extractTemplateTags_(templateBody);
for (let i = 0; i < limit; i++) {
if (PropertiesService.getUserProperties().getProperty("CANCEL_MERGE") === "true") {
outFile.setTrashed(true);
setProgress_(i, limit);
return;
}
const row = values[i];
setProgress_(i + 1, limit);
if (i > 0) {
body.appendPageBreak();
for (let j = 0; j < templateBody.getNumChildren(); j++) {
const el = templateBody.getChild(j).copy();
if (el.getType() === DocumentApp.ElementType.PARAGRAPH) body.appendParagraph(el);
else if (el.getType() === DocumentApp.ElementType.TABLE) body.appendTable(el);
}
}
const replacements = {};
templateTags.forEach(tag => {
const idx = headers.indexOf(tag);
const val = idx === -1 ? "" : row[idx];
replacements[`\\*\\|${tag}\\|\\*`] = val === null || val === undefined ? "" : String(val);
});
body.getParagraphs().forEach(p => {
let text = p.getText();
let hadTag = false;
let allEmpty = true;
for (const key in replacements) {
const re = new RegExp(key);
if (re.test(text)) {
hadTag = true;
const v = replacements[key];
text = text.replace(re, v);
if (v.trim()) allEmpty = false;
}
}
if (hadTag) {
if (allEmpty && p.getParent().getNumChildren() > 1) p.removeFromParent();
else p.setText(text);
}
});
}
doc.saveAndClose();
PropertiesService.getUserProperties().deleteProperty("MERGE_PROGRESS");
resetCancelFlag_();
}