-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCode.js
More file actions
1180 lines (1001 loc) · 36.4 KB
/
Code.js
File metadata and controls
1180 lines (1001 loc) · 36.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Simplify Budget - Google Sheets Budget Management App
* Built on a modular architecture for improved performance
*/
/**
* Returns the HTML content for the web app
* Handles ?authorizeDrive=1 parameter to force Drive scope authorization
*/
function doGet() {
return HtmlService.createTemplateFromFile("Index")
.evaluate()
.setTitle("Simplify Budget")
.addMetaTag("viewport", "width=device-width, initial-scale=1")
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
/**
* Includes an HTML file in another HTML file
* @param {string} filename - The name of the file to include
* @return {string} The contents of the file
*/
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
/**
* Sets the budget sheet URL for the current session
* @param {string} url - The Google Sheet URL
* @return {Object} Success response or error
*/
function setBudgetSheetUrl(url) {
try {
Logger.log("Setting budget sheet URL: " + url);
if (!url) {
return {
success: false,
error: "No URL provided"
};
}
// Store in user properties
PropertiesService.getUserProperties().setProperty('BUDGET_SHEET_URL', url);
// Verify it was stored correctly
const storedUrl = PropertiesService.getUserProperties().getProperty('BUDGET_SHEET_URL');
Logger.log("Successfully stored URL: " + storedUrl);
// TRIAL INITIATION: Start trial when user connects via manual URL
try {
const userEmail = Session.getActiveUser().getEmail();
if (userEmail) recordFirstUse(userEmail);
} catch (e) {
// Completely silent - don't break anything
}
return {
success: true,
message: "URL set successfully"
};
} catch (error) {
Logger.log("Error setting sheet URL: " + error);
return {
success: false,
error: error.toString()
};
}
}
/**
* Parse a Google Sheet URL to extract spreadsheet ID and sheet GID
* @param {string} url - Full Google Sheet URL
* @return {Object} Object with spreadsheetId and sheetId
*/
function parseSheetUrl(url) {
try {
// Extract spreadsheet ID
const spreadsheetIdMatch = url.match(/\/d\/([a-zA-Z0-9-_]+)/);
const spreadsheetId = spreadsheetIdMatch ? spreadsheetIdMatch[1] : null;
// Extract GID
const gidMatch = url.match(/[#&]gid=([0-9]+)/);
const sheetId = gidMatch ? gidMatch[1] : null;
return {
success: true,
spreadsheetId: spreadsheetId,
sheetId: sheetId
};
} catch (error) {
return {
success: false,
error: "Could not parse Sheet URL: " + error.toString()
};
}
}
function verifySheetUrl(url) {
try {
if (!url) return { success: false, error: "No URL provided" };
const parsedUrl = parseSheetUrl(url);
if (!parsedUrl.success) return parsedUrl;
const { spreadsheetId, sheetId } = parsedUrl;
if (!spreadsheetId) return { success: false, error: "Could not extract spreadsheet ID from URL" };
try {
// Just verify we can open the spreadsheet
const ss = SpreadsheetApp.openById(spreadsheetId);
// ALWAYS save the IDs if we got this far - don't waste time looking for specific sheets
const userProps = PropertiesService.getUserProperties();
userProps.setProperty("BUDGET_SPREADSHEET_ID", spreadsheetId);
if (sheetId) userProps.setProperty("BUDGET_SHEET_ID", sheetId);
userProps.setProperty('BUDGET_SHEET_URL', url);
return { success: true, message: "Sheet URL verified and accessible" };
} catch (e) {
return { success: false, error: "Cannot access this sheet. Make sure it's shared with you." };
}
} catch (error) {
return { success: false, error: error.toString() };
}
}
/**
* Get a sheet from spreadsheet using cached URL (failsafe approach)
* @return {SpreadsheetApp.Sheet} Sheet object or null
*/
function getBudgetSheet(sheetName) {
try {
// Get the cached URL - this is fastest and most reliable
const props = PropertiesService.getUserProperties();
const sheetUrl = props.getProperty('BUDGET_SHEET_URL');
if (!sheetUrl) {
Logger.log("Missing cached sheet URL");
// This error message is specifically checked by frontend to show welcome screen
throw new Error("No spreadsheet ID found");
}
// Open the spreadsheet by URL directly
const ss = SpreadsheetApp.openByUrl(sheetUrl);
if (!ss) throw new Error("Cannot access spreadsheet");
// If sheet name provided, return that sheet
if (sheetName) {
const sheet = ss.getSheetByName(sheetName);
if (!sheet) throw new Error(`Sheet "${sheetName}" not found`);
return sheet;
}
// Otherwise return the first sheet by default
return ss.getSheets()[0];
} catch (error) {
Logger.log("Error in getBudgetSheet: " + error.toString());
throw error; // Re-throw to propagate to calling functions
}
}
/**
* Get user credentials
* @return {Object} User credentials
*/
function getUserCredentials() {
try {
const props = PropertiesService.getUserProperties();
return {
success: true,
email: Session.getActiveUser().getEmail(),
sheetUrl: props.getProperty('BUDGET_SHEET_URL') || ''
};
} catch (error) {
return {
success: false,
error: error.toString()
};
}
}
/**
* Sets a user property
* @param {string} key - The property key
* @param {string} value - The property value
* @return {Object} Result with success flag
*/
function setUserProperty(key, value) {
try {
PropertiesService.getUserProperties().setProperty(key, value);
return { success: true };
} catch (error) {
return { success: false, error: error.toString() };
}
}
/**
* Save sheet ID from picker - uses drive.file scope only!
* Also records first use for trial tracking
*/
function saveSheetFromPicker(fileId, fileName) {
try {
console.log("Attempting to access file:", fileId);
const spreadsheet = SpreadsheetApp.openById(fileId);
const actualFileName = spreadsheet.getName();
const userProps = PropertiesService.getUserProperties();
userProps.setProperty("BUDGET_SPREADSHEET_ID", fileId);
userProps.setProperty('BUDGET_SHEET_URL', `https://docs.google.com/spreadsheets/d/${fileId}/edit`);
// TRIAL INITIATION: Start trial when user first connects (FAIL-SAFE)
try {
const userEmail = Session.getActiveUser().getEmail();
if (userEmail) recordFirstUse(userEmail);
} catch (e) {
// Completely silent - don't break anything
}
return { success: true, fileName: actualFileName };
} catch (e) {
console.error("Error details:", e.toString());
return { success: false, error: "Cannot access file: " + e.message || e.toString() };
}
}
/**
* Test server connection
* @param {string} sheetUrl - Optional sheet URL to set
* @return {Object} Simple response to verify connection
*/
function testServerConnection(sheetUrl) {
try {
// If URL provided, store it
if (sheetUrl) {
const result = setBudgetSheetUrl(sheetUrl);
if (!result.success) {
return { success: false, error: result.error };
}
}
return {
success: true,
timestamp: new Date().toString(),
message: "Server connection successful",
userEmail: Session.getActiveUser().getEmail()
};
} catch (error) {
Logger.log("Error in testServerConnection: " + error.toString());
return { success: false, error: error.toString() };
}
}
function setCurrencyInSheet(currencySymbol) {
try {
// Get user settings for decimal places
const userProps = PropertiesService.getUserProperties();
const showDecimals = userProps.getProperty("showDecimals") === "true";
// Generate the currency format once
const numberFormat = getCurrencyFormat(currencySymbol, showDecimals);
// 1. Format Income:F5:F sheet
const incomeSheet = getBudgetSheet("Income");
if (incomeSheet) {
incomeSheet.getRange("F5:F").setNumberFormat(numberFormat);
Logger.log("Applied format to Income sheet range F5:F");
}
// 2. Format Expenses:F5:F sheet
const expensesSheet = getBudgetSheet("Expenses");
if (expensesSheet) {
expensesSheet.getRange("F5:F").setNumberFormat(numberFormat);
Logger.log("Applied format to Expenses sheet range F5:F");
}
// 3. Format recurring:I6:I sheet
const recurringSheet = getBudgetSheet("recurring");
if (recurringSheet) {
recurringSheet.getRange("I6:I").setNumberFormat(numberFormat);
Logger.log("Applied format to recurring sheet range I6:I");
}
// 4. Format Net Worth ranges
const netWorthSheet = getBudgetSheet("Net Worth");
if (netWorthSheet) {
netWorthSheet.getRange("H37:H").setNumberFormat(numberFormat);
netWorthSheet.getRange("D5:P18").setNumberFormat(numberFormat);
netWorthSheet.getRange("J37:J").setNumberFormat(numberFormat);
}
// 10. Format Setup sheet with specific currency ranges
const setupSheet = getBudgetSheet("Reports");
if (setupSheet) {
// Format specific ranges that contain monetary values
setupSheet.getRange("E6:L7").setNumberFormat(numberFormat);
setupSheet.getRange("I61:K71").setNumberFormat(numberFormat);
setupSheet.getRange("B78:D109").setNumberFormat(numberFormat);
setupSheet.getRange("F78:F109").setNumberFormat(numberFormat);
setupSheet.getRange("I78:K109").setNumberFormat(numberFormat);
setupSheet.getRange("M78:M109").setNumberFormat(numberFormat);
setupSheet.getRange("C26:D55").setNumberFormat(numberFormat);
setupSheet.getRange("J26:J55").setNumberFormat(numberFormat);
setupSheet.getRange("M26:N55").setNumberFormat(numberFormat);
Logger.log("Applied format to Setup sheet specific currency ranges");
}
return { success: true };
} catch (e) {
Logger.log("Error in setCurrencyInSheet: " + e.toString());
return { success: false, error: e.toString() };
}
}
/**
* Get the proper Google Sheets number format for a given currency symbol
* @param {string} symbol - Currency symbol
* @param {boolean} showDecimals - Whether to show decimal places (defaults to false)
* @return {string} Google Sheets number format pattern
*/
function getCurrencyFormat(symbol, showDecimals = false) {
// Base formats with or without decimals
const decimalSuffix = showDecimals ? ".00" : "";
// Common currency formats
const formats = {
'$': `"$"#,##0${decimalSuffix};("$"#,##0${decimalSuffix})`,
'€': `[$€]#,##0${decimalSuffix};([$€]#,##0${decimalSuffix})`,
'£': `"£"#,##0${decimalSuffix};("£"#,##0${decimalSuffix})`,
'¥': `"¥"#,##0${decimalSuffix};("¥"#,##0${decimalSuffix})`,
'₹': `"₹"#,##0${decimalSuffix};("₹"#,##0${decimalSuffix})`,
'₽': `"₽"#,##0${decimalSuffix};("₽"#,##0${decimalSuffix})`,
'₺': `"₺"#,##0${decimalSuffix};("₺"#,##0${decimalSuffix})`,
'C$': `"C$"#,##0${decimalSuffix};("C$"#,##0${decimalSuffix})`,
'A$': `"A$"#,##0${decimalSuffix};("A$"#,##0${decimalSuffix})`,
'CHF': `CHF#,##0${decimalSuffix};(CHF#,##0${decimalSuffix})`,
'R$': `"R$"#,##0${decimalSuffix};("R$"#,##0${decimalSuffix})`,
'₩': `"₩"#,##0${decimalSuffix};("₩"#,##0${decimalSuffix})`,
'RM': `"RM"#,##0${decimalSuffix};("RM"#,##0${decimalSuffix})`,
'฿': `"฿"#,##0${decimalSuffix};("฿"#,##0${decimalSuffix})`,
'₦': `"₦"#,##0${decimalSuffix};("₦"#,##0${decimalSuffix})`,
// New currencies added:
'S$': `"S$"#,##0${decimalSuffix};("S$"#,##0${decimalSuffix})`,
'HK$': `"HK$"#,##0${decimalSuffix};("HK$"#,##0${decimalSuffix})`,
'R': `"R"#,##0${decimalSuffix};("R"#,##0${decimalSuffix})`,
'kr': `"kr"#,##0${decimalSuffix};("kr"#,##0${decimalSuffix})`,
'NZ$': `"NZ$"#,##0${decimalSuffix};("NZ$"#,##0${decimalSuffix})`,
'zł': `"zł"#,##0${decimalSuffix};("zł"#,##0${decimalSuffix})`,
'﷼': `"﷼"#,##0${decimalSuffix};("﷼"#,##0${decimalSuffix})`,
'Rp': `"Rp"#,##0${decimalSuffix};("Rp"#,##0${decimalSuffix})`,
'₱': `"₱"#,##0${decimalSuffix};("₱"#,##0${decimalSuffix})`,
'NT$': `"NT$"#,##0${decimalSuffix};("NT$"#,##0${decimalSuffix})`,
'د.إ': `"د.إ"#,##0${decimalSuffix};("د.إ"#,##0${decimalSuffix})`,
'د.ا': `"د.ا"#,##0${decimalSuffix};("د.ا"#,##0${decimalSuffix})`,
'₫': `"₫"#,##0${decimalSuffix};("₫"#,##0${decimalSuffix})`,
'₴': `"₴"#,##0${decimalSuffix};("₴"#,##0${decimalSuffix})`
};
// Return the specific format or default to a generic one with the given symbol
return formats[symbol] || `"${symbol}"#,##0${decimalSuffix};("${symbol}"#,##0${decimalSuffix})`;
}
/**
* Enhanced setUserSettings with separate timestamp storage
* Saves timestamp to Dontedit J8, data to Dontedit K8
* @param {Object} settings - The settings object to save
* @return {Object} Result with success status and timestamp
*/
function setUserSettings(settings) {
try {
const sheet = getBudgetSheet("Dontedit");
if (!sheet) {
return { success: false, error: "Dontedit sheet not found" };
}
// Create timestamp
const timestamp = new Date().toISOString();
// Prepare data without timestamp (clean JSON)
const cleanSettingsData = {
settings: settings,
version: 1
};
// Save timestamp to J8, data to K8
sheet.getRange("J8").setValue(timestamp);
sheet.getRange("K8").setValue(JSON.stringify(cleanSettingsData));
// Cache handled by CacheManager on frontend
// Server-side doesn't cache in properties
return {
success: true,
timestamp: timestamp
};
} catch (error) {
Logger.log("Error in setUserSettings: " + error.toString());
return { success: false, error: error.toString() };
}
}
/**
* Update last active timestamp in Dontedit D8
* @return {Object} Success response or error
*/
function updateLastActiveTimestamp() {
try {
const sheet = getBudgetSheet("Dontedit");
if (!sheet) {
return { success: false, error: "Dontedit sheet not found" };
}
// Create timestamp
const timestamp = new Date().toISOString();
// Save timestamp to D8
sheet.getRange("D8").setValue(timestamp);
Logger.log("Updated last active timestamp to: " + timestamp);
return {
success: true,
timestamp: timestamp
};
} catch (error) {
Logger.log("Error in updateLastActiveTimestamp: " + error.toString());
return { success: false, error: error.toString() };
}
}
/**
* Get user settings from Dontedit K8
* @param {boolean} useCache - Whether to use cached data
* @return {Object} Settings data
*/
function getUserSettings(useCache = true) {
try {
// Check cache first using CacheManager
if (useCache) {
// This would be handled by CacheManager on the frontend
// Server-side always fetches fresh from sheet
}
const sheet = getBudgetSheet("Dontedit");
if (!sheet) {
return { success: false, error: "Dontedit sheet not found" };
}
// Get data from K8 only (no timestamp)
const dataCell = sheet.getRange("K8").getValue();
// Handle empty data case
if (!dataCell) {
const emptySettings = {
settings: {},
version: 1
};
// Initialize data cell
sheet.getRange("K8").setValue(JSON.stringify(emptySettings));
return {
success: true,
settings: emptySettings.settings
};
}
// Parse data
let settingsData;
try {
settingsData = JSON.parse(dataCell);
} catch (e) {
return { success: false, error: "Invalid JSON in settings data cell K8: " + e.toString() };
}
// Add version if missing
if (!settingsData.version) {
settingsData.version = 1;
}
// Cache data handled by CacheManager on frontend
// Server-side doesn't cache in properties
return {
success: true,
settings: settingsData.settings || settingsData
};
} catch (error) {
Logger.log("Error in getUserSettings: " + error.toString());
return { success: false, error: error.toString() };
}
}
/**
* Fix missing transaction IDs - user-triggered from settings
*/
function fixMissingTransactionIds() {
try {
let totalFixed = 0;
const results = [];
const sheetsModified = []; // Track which sheets were actually modified
// Define sheets to check with correct ranges and prefixes
const sheetsToFix = [
{
name: 'Expenses',
dataRange: { start: 5, end: 11 },
idCol: 4, // D column
startRow: 6, // D6:D
prefix: 'ex-'
},
{
name: 'Income',
dataRange: { start: 5, end: 10 },
idCol: 4, // D column
startRow: 5, // D5:D
prefix: 'inc-'
},
{
name: 'Recurring',
dataRange: { start: 6, end: 12 },
idCol: 3, // C column
startRow: 6, // C6:C
prefix: 'rec-'
},
{
name: 'Net Worth',
dataRange: { start: 6, end: 12 },
idCol: 3, // C column
startRow: 37, // C37:C
prefix: 'net-'
}
];
sheetsToFix.forEach(sheetConfig => {
const sheet = getBudgetSheet(sheetConfig.name);
if (!sheet) {
results.push(`${sheetConfig.name}: Sheet not found`);
return;
}
const lastRow = sheet.getLastRow();
if (lastRow < sheetConfig.startRow) {
results.push(`${sheetConfig.name}: No data to check`);
return;
}
let fixedInSheet = 0;
// Calculate the range from startRow to lastRow
const rowsToCheck = lastRow - sheetConfig.startRow + 1;
// Read transaction IDs and data
const idRange = sheet.getRange(sheetConfig.startRow, sheetConfig.idCol, rowsToCheck, 1);
const ids = idRange.getValues().flat();
const dataRange = sheet.getRange(sheetConfig.startRow, sheetConfig.dataRange.start, rowsToCheck, sheetConfig.dataRange.end - sheetConfig.dataRange.start + 1);
const dataRows = dataRange.getValues();
// Process each row
const idsToSet = [];
for (let i = 0; i < ids.length; i++) {
const rowNum = i + sheetConfig.startRow;
const transactionId = ids[i];
const rowData = dataRows[i];
// Check if row has data - SAME LOGIC as checkDataHealth
const hasData = rowData.some(cell =>
cell !== null && cell !== undefined && cell !== ''
);
if (hasData) {
// Check for missing IDs OR purely numeric IDs (both need fixing)
const needsNewId = !transactionId || transactionId === '' || /^\d+$/.test(transactionId.toString());
if (needsNewId) {
const randomNumber = Math.random().toString(36).substr(2, 9);
const newId = `${sheetConfig.prefix}${Date.now()}-${randomNumber}`;
idsToSet.push({ row: rowNum, id: newId });
fixedInSheet++;
}
}
}
// Batch update the missing/numeric IDs
if (idsToSet.length > 0) {
idsToSet.forEach(item => {
sheet.getRange(item.row, sheetConfig.idCol).setValue(item.id);
});
// Track that this sheet was modified
sheetsModified.push(sheetConfig.name);
}
totalFixed += fixedInSheet;
results.push(`${sheetConfig.name}: Fixed ${fixedInSheet} rows`);
});
// Only update timestamps for sheets that were actually modified
if (totalFixed > 0) {
// Always update masterData since core data integrity was affected
updateDataTimestamp('masterData');
// Update specific timestamps based on which sheets were modified
sheetsModified.forEach(sheetName => {
if (sheetName === 'Expenses') {
updateDataTimestamp('budget'); // Expenses affect budget calculations
}
if (sheetName === 'Income') {
updateDataTimestamp('income');
updateDataTimestamp('budget'); // Income also affects budget
}
if (sheetName === 'Recurring') {
updateDataTimestamp('recurring');
}
if (sheetName === 'Net Worth') {
updateDataTimestamp('netWorth');
}
});
}
return {
success: true,
totalFixed: totalFixed,
results: results,
sheetsModified: sheetsModified
};
} catch (error) {
Logger.log("Error in fixMissingTransactionIds: " + error.toString());
return {
success: false,
error: error.toString()
};
}
}
/**
* Check data health - provides statistics about data integrity
*/
function checkDataHealth() {
try {
let totalRows = 0;
let missingIds = 0;
let duplicateIds = 0;
let numericIds = 0; // NEW: Track purely numeric IDs that need fixing
const results = [];
const allIds = new Set();
const duplicatedIds = new Set();
// Define sheets to check - ALIGNED with fixMissingTransactionIds
const sheetsToCheck = [
{
name: 'Expenses',
dataRange: { start: 5, end: 11 },
idCol: 4, // D column
startRow: 6, // D6:D
prefix: 'ex-'
},
{
name: 'Income',
dataRange: { start: 5, end: 10 },
idCol: 4, // D column
startRow: 5, // D5:D
prefix: 'inc-'
},
{
name: 'Recurring',
dataRange: { start: 6, end: 12 },
idCol: 3, // C column
startRow: 6, // C6:C
prefix: 'rec-'
},
{
name: 'Net Worth',
dataRange: { start: 6, end: 12 },
idCol: 3, // C column
startRow: 37, // C37:C
prefix: 'net-'
}
];
sheetsToCheck.forEach(sheetConfig => {
const sheet = getBudgetSheet(sheetConfig.name);
if (!sheet) {
results.push(`${sheetConfig.name}: Sheet not found`);
return;
}
const lastRow = sheet.getLastRow();
if (lastRow < sheetConfig.startRow) {
results.push(`${sheetConfig.name}: No data to check`);
return;
}
// Calculate the range from startRow to lastRow
const rowsToCheck = lastRow - sheetConfig.startRow + 1;
totalRows += rowsToCheck;
// Read transaction IDs and data - SAME LOGIC as fixMissingTransactionIds
const idRange = sheet.getRange(sheetConfig.startRow, sheetConfig.idCol, rowsToCheck, 1);
const ids = idRange.getValues().flat();
const dataRange = sheet.getRange(sheetConfig.startRow, sheetConfig.dataRange.start, rowsToCheck, sheetConfig.dataRange.end - sheetConfig.dataRange.start + 1);
const dataRows = dataRange.getValues();
let sheetMissingIds = 0;
let sheetDuplicates = 0;
let sheetDataRows = 0;
let sheetNumericIds = 0; // NEW: Track numeric IDs in this sheet
// Process each row - SAME LOGIC as fixMissingTransactionIds
for (let i = 0; i < ids.length; i++) {
const transactionId = ids[i];
const rowData = dataRows[i];
// Check if row has data - EXACT SAME CHECK
const hasData = rowData.some(cell =>
cell !== null && cell !== undefined && cell !== ''
);
if (hasData) {
sheetDataRows++;
// Check for missing IDs - SAME LOGIC
if (!transactionId || transactionId === '') {
sheetMissingIds++;
} else {
// NEW: Check if ID is purely numeric (needs fixing)
const idString = transactionId.toString();
const isPurelyNumeric = /^\d+$/.test(idString);
if (isPurelyNumeric) {
sheetNumericIds++;
}
// Check for duplicates
if (allIds.has(transactionId)) {
duplicatedIds.add(transactionId);
sheetDuplicates++;
} else {
allIds.add(transactionId);
}
}
}
}
missingIds += sheetMissingIds;
duplicateIds += sheetDuplicates;
numericIds += sheetNumericIds; // NEW: Add to total
// NEW: Updated result message to include numeric IDs
results.push(`${sheetConfig.name}: ${sheetDataRows} data rows, ${sheetMissingIds} missing IDs, ${sheetNumericIds} numeric IDs, ${sheetDuplicates} duplicates`);
});
return {
success: true,
totalRows: totalRows,
missingIds: missingIds,
numericIds: numericIds, // NEW: Return numeric ID count
duplicateIds: duplicateIds,
results: results,
duplicatedIdsList: Array.from(duplicatedIds)
};
} catch (error) {
Logger.log("Error in checkDataHealth: " + error.toString());
return {
success: false,
error: error.toString()
};
}
}
// Add this to your server-side code
function getPickerConfig() {
try {
const token = ScriptApp.getOAuthToken();
return {
success: true,
token: token
};
} catch (error) {
return { success: false, error: error.toString() };
}
}
/**
* Create a new budget sheet from template for first-time users
* @return {Object} Result with sheet ID and URL
*/
function createBudgetSheetFromTemplate() {
try {
// Template sheet ID from the provided URL
const TEMPLATE_SHEET_ID = '1fA8lHlDC8bZKVHSWSGEGkXHNmVylqF0Ef2imI_2jkZ8';
// Get the template spreadsheet
const templateSpreadsheet = SpreadsheetApp.openById(TEMPLATE_SHEET_ID);
// Create a copy with timestamp only
const timestamp = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy-MM-dd_HH-mm-ss');
const newSheetName = `SimplifyBudget_${timestamp}`;
// Make a copy to user's Drive
const newSpreadsheet = templateSpreadsheet.copy(newSheetName);
const newSpreadsheetId = newSpreadsheet.getId();
// Save the new sheet ID to user properties
const userProps = PropertiesService.getUserProperties();
userProps.setProperty("BUDGET_SPREADSHEET_ID", newSpreadsheetId);
userProps.setProperty('BUDGET_SHEET_URL', newSpreadsheet.getUrl());
// TRIAL INITIATION: Start trial when user creates new sheet from template
try {
const userEmail = Session.getActiveUser().getEmail();
if (userEmail) recordFirstUse(userEmail);
} catch (e) {
// Completely silent - don't break anything
}
return {
success: true,
spreadsheetId: newSpreadsheetId,
url: newSpreadsheet.getUrl(),
name: newSheetName
};
} catch (error) {
Logger.log("Error creating sheet from template: " + error.toString());
return {
success: false,
error: error.toString()
};
}
}
/**
* Force spreadsheet authorization flow (for web app consent dialog)
* @return {Object} Result with success status
*/
function requireSpreadsheetAuthorization() {
const TEMPLATE_SHEET_ID = '1fA8lHlDC8bZKVHSWSGEGkXHNmVylqF0Ef2imI_2jkZ8';
SpreadsheetApp.openById(TEMPLATE_SHEET_ID);
return { success: true };
}
/**
* Get the re-authorization URL to prompt user for all scopes again
* This is needed when users unchecked drive.file during initial setup
* @return {Object} Result with the authorization URL
*/
function getDriveAuthorizationUrl() {
try {
// Get the authorization URL - this will prompt for ALL scopes again
// including drive.file that they may have unchecked
const authInfo = ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL);
const authUrl = authInfo.getAuthorizationUrl();
// authUrl will be null if user has all scopes - but they might have
// unchecked drive.file, so we can't rely on this. Always return a URL.
if (authUrl) {
return { success: true, url: authUrl };
}
// If no auth URL returned, user may have all scopes OR
// may have unchecked optional ones. We can't tell the difference.
// Return the web app URL which will re-trigger auth if needed.
let webAppUrl = ScriptApp.getService().getUrl().replace('/dev', '/exec');
return { success: true, url: webAppUrl, note: 'full_auth' };
} catch (error) {
return { success: false, error: error.toString() };
}
}
/**
* Force Drive authorization flow (needed for Picker file listing)
* @return {Object} Result with success status
*/
function requireDriveAuthorization() {
const userProps = PropertiesService.getUserProperties();
const flag = userProps.getProperty('DRIVE_FILE_AUTH_OK');
if (!flag) {
// Create + trash a tiny temp file to trigger drive.file consent
const blob = Utilities.newBlob('auth-check', 'text/plain', 'SimplifyBudgetAuthCheck.txt');
const file = DriveApp.createFile(blob);
file.setTrashed(true);
userProps.setProperty('DRIVE_FILE_AUTH_OK', '1');
}
return { success: true };
}
/**
* Check if spreadsheet scope is already authorized.
* Attempts to get an OAuth token scoped to spreadsheets.
* @return {Object} { success: true, hasPermission: boolean }
*/
function checkSheetsPermission() {
try {
const authInfo = ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL);
const status = authInfo.getAuthorizationStatus();
return {
success: true,
hasPermission: status !== ScriptApp.AuthorizationStatus.REQUIRED
};
} catch (error) {
return { success: true, hasPermission: false };
}
}
/**
* Get authorization URL for required scopes, if needed.
* @return {Object} Result with optional authorization URL
*/
function getAuthorizationUrl() {
try {
const authInfo = ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL);
if (authInfo.getAuthorizationStatus() === ScriptApp.AuthorizationStatus.REQUIRED) {
return { success: true, url: authInfo.getAuthorizationUrl() };
}
return { success: true, url: null };
} catch (error) {
return { success: false, error: error.toString() };
}
}
/**
* Disconnect budget sheet (remove from user properties)
* @return {Object} Result with success status
*/
function disconnectBudgetSheet() {
try {
const userProps = PropertiesService.getUserProperties();
userProps.deleteProperty("BUDGET_SPREADSHEET_ID");
userProps.deleteProperty("BUDGET_SHEET_URL");
userProps.deleteProperty("BUDGET_SHEET_ID");
return {
success: true,
message: "Budget sheet disconnected successfully"
};
} catch (error) {
Logger.log("Error disconnecting sheet: " + error.toString());
return {
success: false,
error: error.toString()
};
}
}
/**
* TRIAL SYSTEM - Record first use when user connects template
*/
// Secret tracking sheet ID - users cannot see this
const TRIAL_TRACKING_SHEET = PropertiesService.getScriptProperties().getProperty('TRIAL_TRACKING_SHEET');
// Secret encryption key
const ENCRYPTION_KEY = PropertiesService.getScriptProperties().getProperty('ENCRYPTION_KEY');
/**
* Simple XOR encryption/decryption
* @param {string} text - Text to encrypt/decrypt
* @param {string} key - Encryption key
* @return {string} Encrypted/decrypted text
*/
function xorEncrypt(text, key) {
let result = '';
for (let i = 0; i < text.length; i++) {
result += String.fromCharCode(text.charCodeAt(i) ^ key.charCodeAt(i % key.length));
}
return result;
}