-
Notifications
You must be signed in to change notification settings - Fork 2
/
Code.js
694 lines (621 loc) Β· 21.6 KB
/
Code.js
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
/**
* @OnlyCurrentDoc
*/
/*
-----------------------------
| SHEETS MIXPANEL |
| a google sheets add-on |
| by AK |
-----------------------------
*/
const APP_VERSION = "1.17";
/**
* some important things to know about google apps script
* - there are no modules; every function shares a global namespace
* - 'Types' are declared in Types.gs
* - all of the 'typeof module' stuff at the bottom is to enable IDE support
*/
// track(event, {props}) in GAS
let track;
try {
track = tracker();
} catch (e) {
track = () => {};
}
/*
----
IDEAS
----
*/
// $ overcome the 6 (or 30) minute limit for an execution
// ? https://developers.google.com/apps-script/guides/services/quotas#current_limitations
// ? https://inclu-cat.net/2021/12/14/an-easy-way-to-deal-with-google-apps-scripts-6-minute-limit/
// ? https://github.com/inclu-cat/LongRun
// $ in case this script ever needs to store secrets
// ? https://stackoverflow.com/a/75735362
/*
----
MENUS
----
*/
/**
* the main entry point to the application
* called when the sheet is opened by any user
* populates the menu the dropdown the end-user sees in the toolbar
* may runs with different levels of permission which is why we delineate between the two
*
* @param {GoogleAppsScript.Events.SheetsOnOpen} sheetOpenEv event for "sheet is opened"
* @returns {void}
*/
function onOpen(sheetOpenEv) {
const ui = SpreadsheetApp.getUi();
const menu = ui.createAddonMenu();
const authMode = sheetOpenEv.authMode;
if (sheetOpenEv && authMode == ScriptApp.AuthMode.NONE) {
// app does not have permissions to do things
// this occurs when a user is viewing the document who has not authorized/installed the extension
// clicking on menu buttons when the script is not authorized will show the OAuth consent screen
// OAuth consent screen is configured in GCP:
// ? https://developers.google.com/apps-script/add-ons/concepts/editor-auth-lifecycle
menu.addItem("Sheet β Mixpanel", "SheetToMixpanelView");
menu.addItem("Mixpanel β Sheet", "MixpanelToSheetView");
} else {
// user has given app permissions
menu.addItem("Sheet β Mixpanel", "SheetToMixpanelView");
menu.addItem("Mixpanel β Sheet", "MixpanelToSheetView");
// get rid of "feedback"
// menu.addItem("Feedback", "ShowFeedbackForm");
if (authMode == ScriptApp.AuthMode.FULL || authMode == ScriptApp.AuthMode.LIMITED) {
const activeSync = getConfig().active_sync || false;
if (activeSync) {
menu.addItem("Sync Now!", "syncNow");
}
}
}
menu.addToUi();
}
/**
* the "feedback" menu option
* opens a google form
*/
function ShowFeedbackForm() {
// ? https://dogmatix.medium.com/open-a-url-using-google-apps-script-b1f6b8bdaec4
track("feedback");
var htmlOutput = HtmlService.createHtmlOutputFromFile("ui/feedback.html").setHeight(100);
SpreadsheetApp.getUi().showModalDialog(htmlOutput, "Feedback Form");
}
/**
* the "sync now" menu option
* runs a sync using last known config
* these methods are self-sufficient
*/
function syncNow() {
/** @type {Config} */
const config = getConfig();
const runId = Math.random();
const t = tracker({
runId,
type: config.config_type,
project_id: config?.project_id,
view: config?.config_type === "sheet-to-mixpanel" ? "sheet β mixpanel" : "mixpanel β sheet",
manual: true
});
t("sync now: start");
const ui = SpreadsheetApp.getUi();
try {
if (config.config_type === "mixpanel-to-sheet") {
syncMpToSheets();
}
if (config.config_type === "sheet-to-mixpanel") {
syncSheetsToMp();
}
ui.alert("β
Sync Complete", `sync ran successfully`, ui.ButtonSet.OK);
t("sync now: end");
return { status: "success", error: null };
} catch (e) {
t("sync now: error", { error: e.toString() });
ui.alert("β Sync Error", `sync failed to run; got error\n${e.message}`, ui.ButtonSet.OK);
return { status: "fail", error: e.message };
}
}
/*
----------------
Sheet β Mixpanel
----------------
*/
/**
* called when the user clicks Sheet β Mixpanel
*
* @returns {void}
*/
function SheetToMixpanelView() {
try {
const htmlTemplate = HtmlService.createTemplateFromFile("ui/sheet-to-mixpanel.html");
// server-side data
htmlTemplate.columns = getSheetHeaders();
htmlTemplate.config = getConfig();
htmlTemplate.sheet = getSheetInfo();
htmlTemplate.syncs = getTriggers();
// apply data template
const htmlOutput = htmlTemplate.evaluate().setWidth(700).setHeight(700);
// render template
SpreadsheetApp.getUi().showModalDialog(htmlOutput, "Sheet β Mixpanel");
track("open", { view: "sheet β mixpanel" });
} catch (e) {
const ui = SpreadsheetApp.getUi();
ui.alert(
"π³ Empty Sheet",
`your current active sheet is empty...\n\nplease open Sheet β Mixpanel from a sheet that has data`,
ui.ButtonSet.OK
);
}
}
/**
* called when a user clicks the 'test' button in the Sheet β Mixpanel UI
*
* @param {SheetMpConfig} config if not supplied, last known will be used
* @param {SheetInfo} sheetInfo the source sheet which contains the data
* @returns {[ImportResponse[], ImportResults, string]}
*/
function testSyncSheetsToMp(config, sheetInfo = getSheetInfo(SpreadsheetApp.getActiveSheet())) {
config.config_type = "sheet-to-mixpanel";
const runId = Math.random();
const t = tracker({
runId,
record_type: config?.record_type,
project_id: config?.project_id,
view: "sheet β mixpanel"
});
t("test: start");
try {
// @ts-ignore
const auth = validateCreds(config);
config.auth = auth;
} catch (e) {
//bad credentials
t("test: error", { error: e.toString() });
throw e;
}
const sheet = getSheetById(sheetInfo.sheet_id);
const [responses, summary] = importData(config, sheet);
const { total, success, failed, seconds } = summary;
t("test: end", { total, success, failed, seconds });
//store config for future syncs
/** @type {SheetMpConfig} */
const storedConfig = { ...config, ...sheetInfo };
storedConfig.active_sync = false;
setConfig(storedConfig);
return [responses, summary, `https://mixpanel.com/project/${config.project_id}`];
}
/**
* called when a user clicks the 'sync' button in the Sheet β Mixpanel UI
* creates a scheduled sync and runs it
*
* @param {SheetMpConfig} config if not supplied, last known will be used
* @param {SheetInfo} sheetInfo the source sheet which contains the data
*/
function createSyncSheetsToMp(config, sheetInfo) {
//clear all triggers + stored data
clearConfig(getConfig());
config.config_type = "sheet-to-mixpanel";
const runId = Math.random();
const t = tracker({
runId,
record_type: config?.record_type,
project_id: config?.project_id,
view: "sheet β mixpanel",
manual: "first sync"
});
t("sync: create start");
//validate credentials
try {
// @ts-ignore
const auth = validateCreds(config);
config.auth = auth;
} catch (e) {
//bad credentials
t("sync: error", { error: e.toString() });
throw e;
}
const sheet = getSheetById(Number(sheetInfo.sheet_id));
//create the sheet for storing logs; add it to config
const receiptSheetName = `Sheet β Mixpanel (${config.record_type} logs)`;
const receiptSheet = createSheet(receiptSheetName);
config.receipt_sheet = getSheetInfo(receiptSheetName).sheet_id;
const columns = `Start Time,End Time,Duration,Total,Success,Failed,Errors`;
overwriteSheet(columns, receiptSheet);
receiptSheet.setFrozenRows(1);
//create the trigger
const trigger = ScriptApp.newTrigger("syncSheetsToMp").timeBased().everyHours(1).create();
//store config for future syncs
/** @type {SheetMpConfig} */
const storedConfig = { ...config, ...sheetInfo, trigger: trigger.getUniqueId() };
storedConfig.active_sync = true;
setConfig(storedConfig);
//run a sync now
t("sync: start");
const [responses, summary] = importData(config, sheet);
const { startTime, endTime, seconds, total, success, failed, errors } = summary;
t("sync: end", { total, success, failed, seconds });
//dump results to sync log
receiptSheet
.getRange(getEmptyRow(receiptSheet), 1, 1, 7)
.setValues([
[
new Date(startTime),
new Date(endTime),
`${seconds} seconds`,
total,
success,
failed,
JSON.stringify(errors, null, 2)
]
]);
t("sync: create end");
//notify the end user
return [responses, summary, `https://mixpanel.com/project/${config.project_id}`, storedConfig];
}
/**
* called automatically by the trigger: Sheet β Mixpanel
*/
function syncSheetsToMp() {
/** @type {SheetMpConfig & SheetInfo} */
const config = getConfig();
if (Object.keys(config).length === 0) {
//console.log("no operation: sync was scheduled, but config is empty (SH => MP)");
clearConfig(null, true);
track("sync: autodelete", { view: "sheet β mixpanel", reason: "empty config" });
return `SYNC DELETED`;
}
config.config_type = "sheet-to-mixpanel";
const runId = Math.random();
const t = tracker({
runId,
record_type: config?.record_type,
project_id: config?.project_id,
view: "sheet β mixpanel",
manual: false
});
t("sync: start");
const triggerId = config.trigger;
let sourceSheet;
let receiptSheet;
try {
sourceSheet = getSheet(Number(config.sheet_id));
} catch (e) {
//the source sheet is gone; kill the sync + config
t("sync: autodelete", { reason: "source sheet deleted" });
clearTriggers(triggerId);
clearConfig();
return `SYNC DELETED`;
}
try {
receiptSheet = getSheet(Number(config.receipt_sheet));
} catch (e) {
//receipt sheet MUST exist; make it again... UGH... this is terrible
const receiptSheetName = `Sheet β Mixpanel (${config.record_type} logs)`;
receiptSheet = createSheet(receiptSheetName);
config.receipt_sheet = getSheetInfo(receiptSheetName).sheet_id;
const columns = `Start Time,End Time,Duration,Total,Success,Failed,Errors`;
overwriteSheet(columns, receiptSheet);
receiptSheet.setFrozenRows(1);
}
// store any updated changes
setConfig(config);
//actually do the sync
try {
//validate credentials
if (!config.auth) {
// @ts-ignore
const auth = validateCreds(config);
config.auth = auth;
}
//run import
const [responses, summary] = importData(config, sourceSheet);
// track sync result
if (responses.length === 0) {
t("sync: skipped");
} else {
t("sync: end");
}
const { startTime, endTime, seconds, total, success, failed, errors } = summary;
//dump results to sync log
receiptSheet
.getRange(getEmptyRow(receiptSheet), 1, 1, 7)
.setValues([
[
new Date(startTime),
new Date(endTime),
`${seconds} seconds`,
total,
success,
failed,
JSON.stringify(errors, null, 2)
]
]);
return { status: "success", error: errors };
} catch (e) {
t("sync: error", { error: e.toString() });
receiptSheet
.getRange(getEmptyRow(receiptSheet), 1, 1, 7)
.setValues([[new Date(), new Date(), `-----`, `-----`, `-----`, `-----`, `ERROR:\n${e.message}`]]);
return { status: "fail", error: e.message || e };
}
}
/*
----------------
Mixpanel β Sheet
----------------
*/
/**
* called when the user clicks Mixpanel β Sheet
*
* @returns {void}
*/
function MixpanelToSheetView() {
const htmlTemplate = HtmlService.createTemplateFromFile("ui/mixpanel-to-sheet.html");
// server-side data
htmlTemplate.config = getConfig();
htmlTemplate.sheet = getSheetInfo();
htmlTemplate.syncs = getTriggers();
// apply data to template
const htmlOutput = htmlTemplate.evaluate().setWidth(600).setHeight(500);
//render template
SpreadsheetApp.getUi().showModalDialog(htmlOutput, "Mixpanel β Sheet");
track("open", { view: "mixpanel β sheet" });
}
/**
* called when a user clicks the 'test' button in the Mixpanel β Sheet UI
*
* @param {MpSheetConfig} config if not supplied, last known will be used
*/
function testSyncMpToSheets(config) {
config.config_type = "mixpanel-to-sheet";
const runId = Math.random();
const t = tracker({ runId, project_id: config.project_id, view: "mixpanel β sheet" });
t("test: start");
try {
const auth = validateCreds(config);
config.auth = auth;
} catch (e) {
//bad credentials
t("test: error", { error: e.toString() });
throw e;
}
try {
const [csvData, metadata] = exportData(config);
let sheetName;
if (config.entity_type === "cohort") {
//@ts-ignore
sheetName = `cohort: ${metadata.cohort_name}`;
} else if (config.entity_type === "report") {
//@ts-ignore
sheetName = `report: ${metadata.report_name}`;
}
//this should never be the case
else {
sheetName = `mixpanel export`;
}
const destSheet = createSheet(sheetName);
config.dest_sheet = getSheetInfo(destSheet).sheet_id;
config.active_sync = false;
setConfig(config);
const updatedSheet = overwriteSheet(csvData, destSheet);
t("test: end");
return [updatedSheet, metadata];
} catch (e) {
t("test: error", { error: e.toString() });
throw e;
}
}
/**
* called when a user clicks the 'sync' button in the Mixpanel β Sheet UI
* creates a scheduled sync and runs it
*
* @param {MpSheetConfig} config
*/
function createSyncMpToSheets(config) {
//clear all triggers + stored data
clearConfig(getConfig());
config.config_type = "mixpanel-to-sheet";
const startTime = new Date();
const runId = Math.random();
const t = tracker({
runId,
record_type: config?.entity_type,
project_id: config?.project_id,
view: "mixpanel β sheet",
manual: "first time"
});
t("sync: create start");
//validate credentials
try {
// @ts-ignore
const auth = validateCreds(config);
config.auth = auth;
} catch (e) {
//bad credentials
t("sync: error", { error: e.toString() });
throw e;
}
//create the sheet for storing logs; add it to config
const receiptSheetName = `Sheet β Mixpanel (${config.entity_type} logs)`;
const receiptSheet = createSheet(receiptSheetName);
config.receipt_sheet = getSheetInfo(receiptSheetName).sheet_id;
const columns = `Start Time,End Time,Duration,Entity,Errors`;
overwriteSheet(columns, receiptSheet);
receiptSheet.setFrozenRows(1);
//hit the report & get it's data
t("sync: start");
let csvData, metadata;
try {
[csvData, metadata] = exportData(config);
} catch (e) {
t("sync: error", { error: e.toString() });
throw e;
}
//create a sheet for the destination; add it to config
let sheetName;
if (config.entity_type === "cohort") {
//@ts-ignore
sheetName = `cohort: ${metadata.cohort_name}`;
} else if (config.entity_type === "report") {
//@ts-ignore
sheetName = `report: ${metadata.report_name}`;
}
//this should never be the case
else {
sheetName = `mixpanel export`;
}
const destSheet = createSheet(sheetName);
config.dest_sheet = getSheetInfo(destSheet).sheet_id;
// overwrite entire contents
const updatedSheet = overwriteSheet(csvData, destSheet);
t("sync: end");
//create the trigger
const trigger = ScriptApp.newTrigger("syncMpToSheets").timeBased().everyHours(1).create();
//store config for future syncs
config.active_sync = true;
config.trigger = trigger.getUniqueId();
setConfig(config);
//write receipt
const endTime = new Date();
const deltaSec = Math.abs(endTime.getTime() - startTime.getTime()) / 1000;
receiptSheet.getRange(getEmptyRow(receiptSheet), 1, 1, 5).setValues([
[
startTime,
endTime,
`${deltaSec} seconds`,
// @ts-ignore
metadata?.cohort_name || metadata?.report_name || "unknown",
"none"
]
]);
t("sync: create end");
return [updatedSheet, metadata, config];
}
/**
* called automatically by the trigger: Mixpanel β Sheet
*/
function syncMpToSheets() {
/** @type {MpSheetConfig} */
const config = getConfig();
if (Object.keys(config).length === 0) {
//console.log("no operation: sync was scheduled, but config is empty (MP => SH)");
clearConfig(null, true);
track("sync: autodelete", { view: "mixpanel β sheet", reason: "empty config" });
return `SYNC DELETED`;
}
config.config_type = "mixpanel-to-sheet";
const runId = Math.random();
const t = tracker({
runId,
record_type: config?.entity_type,
project_id: config?.project_id,
view: "mixpanel β sheet",
manual: false
});
t("sync: start");
const triggerId = config.trigger;
const startTime = new Date();
let destSheet;
let receiptSheet;
try {
destSheet = getSheet(Number(config.dest_sheet));
} catch (e) {
//dest sheet is gone; remake it
destSheet = createSheet(`mixpanel ${config.entity_type} export`);
config.dest_sheet = getSheetInfo(destSheet).sheet_id;
}
try {
receiptSheet = getSheet(Number(config.receipt_sheet));
} catch (e) {
// receipt sheet is gone; remake it
const receiptSheetName = `Sheet β Mixpanel (${config.entity_type} logs)`;
receiptSheet = createSheet(receiptSheetName);
config.receipt_sheet = getSheetInfo(receiptSheetName).sheet_id;
const columns = `Start Time,End Time,Duration,Entity,Errors`;
overwriteSheet(columns, receiptSheet);
receiptSheet.setFrozenRows(1);
}
// store any updated changes
setConfig(config);
//actually do the sync
try {
const [csvData, metadata] = exportData(config);
const updatedSheet = overwriteSheet(csvData, destSheet);
const endTime = new Date();
const deltaSec = Math.abs(endTime.getTime() - startTime.getTime()) / 1000;
receiptSheet.getRange(getEmptyRow(receiptSheet), 1, 1, 5).setValues([
[
startTime,
endTime,
`${deltaSec} seconds`,
// @ts-ignore
metadata?.cohort_name || metadata?.report_name || "unknown",
""
]
]);
t("sync: end");
return { status: "success", error: null };
} catch (e) {
t("sync: error", { error: e.toString() });
receiptSheet
.getRange(getEmptyRow(receiptSheet), 1, 1, 5)
.setValues([[new Date(), new Date(), `-----`, `-----`, `sync fail:\n${e}`]]);
return { status: "fail", error: e.message || e };
}
}
/*
----
NOT USED BY GAS
----
*/
if (typeof module !== "undefined") {
const { tracker } = require("./utilities/tracker.js");
const {
getSheetHeaders,
getSheetById,
getSheetInfo,
createSheet,
overwriteSheet,
getSheet,
getEmptyRow
} = require("./utilities/sheet");
const { getConfig, setConfig, clearConfig, getTriggers, clearTriggers } = require("./utilities/storage.js");
const { validateCreds } = require("./utilities/validate.js");
const { importData } = require("./components/dataImport.js");
const { exportData } = require("./components/dataExport.js");
module.exports = {
onOpen,
syncNow,
SheetToMixpanelView,
testSyncSheetsToMp,
createSyncSheetsToMp,
syncSheetsToMp,
MixpanelToSheetView,
testSyncMpToSheets,
createSyncMpToSheets,
syncMpToSheets,
ShowFeedbackForm
};
}
/*
----
REF DOCS
----
*/
// ? MODEL https://developers.google.com/apps-script/reference/spreadsheet
// ? UI https://developers.google.com/apps-script/guides/menus
// ? COMMUNICATION https://developers.google.com/apps-script/guides/html/communication
// ? STORAGE https://developers.google.com/apps-script/guides/properties
// ? PUBLISH https://developers.google.com/apps-script/add-ons/how-tos/publish-add-on-overview
// ? also pub: https://link.medium.com/qT0PlG3wiyb
// ? scheduling: https://developers.google.com/apps-script/add-ons/concepts/editor-triggers
// ? also scheduler: https://developers.google.com/apps-script/reference/script/clock-trigger-builder
// ? low level scheduler: https://developers.google.com/apps-script/reference/script/trigger
// ? delete triggers: https://stackoverflow.com/a/47217237
// ? tests: https://github.com/WildH0g/UnitTestingApp
// ? bundling npm modules: https://12ft.io/proxy?q=https%3A%2F%2Fmedium.com%2Fgeekculture%2Fthe-ultimate-guide-to-npm-modules-in-google-apps-script-a84545c3f57c
// ? overloads https://austingil.com/typescript-function-overloads-with-jsdoc/