-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode.gs
More file actions
2863 lines (2383 loc) · 100 KB
/
Code.gs
File metadata and controls
2863 lines (2383 loc) · 100 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
/**
* TransacFlow - Flow your transactions from Gmail to Sheets
*
* ⚠️ SETUP REQUIRED:
* 1. Update Config.gs with your Sheet ID
* 2. Customize BankPatterns.gs if needed
* 3. Run setupAutomation() to start
*
* ⚠️ DO NOT EDIT THIS FILE (unless you know what you're doing)
* → All configurations are in Config.gs
* → Bank patterns are in BankPatterns.gs
*
* 📋 MAIN FUNCTIONS (Run these):
* - setupAutomation() → Initial setup & create triggers
* - processTransactionEmails() → Manual run (also auto-runs every 10 min)
* - refreshAllNicknames() → Update all transactions with latest nicknames
* - updateDashboard() → Create/refresh analytics dashboard
* - addCategoriesToTransactions() → Add categories to existing transactions
*
* 🧪 TESTING FUNCTIONS:
* - test_SingleEmail() → Test parsing of one email
* - test_WriteToSheet() → Test parsing + writing to sheet
*
* 🔍 DIAGNOSTIC FUNCTIONS:
* - debug_SearchQuery() → Show current search query
* - debug_EmailSearch() → Diagnose email search issues
* - debug_ShowRawEmail() → Show raw email content for pattern debugging
* - debug_DashboardData() → Troubleshoot dashboard zero values
*
* ℹ️ ACCOUNT NICKNAMES:
* - Managed in "Account Nicknames" sheet (auto-created)
* - Edit "Custom Nickname" column to customize names
* - Changes automatically update all transactions!
*
* 📊 ANALYTICS DASHBOARD:
* - Run updateDashboard() to create comprehensive analytics
* - Includes: Monthly summaries, top merchants, category breakdown, trends, budget tracking
* - Categories are auto-assigned based on merchant names
*
* @version 1.2.0
* @author Aakash Goel
* @license MIT
* @repository https://github.com/alpha-gamma/transacflow
*/
// ==================== UTILITIES ====================
/**
* Logger class for centralized logging
*/
class Logger {
constructor(logLevel = 'INFO') {
this.logLevel = logLevel;
this.levels = { 'DEBUG': 0, 'INFO': 1, 'WARN': 2, 'ERROR': 3 };
}
shouldLog(level) {
return this.levels[level] >= this.levels[this.logLevel];
}
formatMessage(level, message) {
const timestamp = new Date().toISOString();
return `[${timestamp}] [${level}] ${message}`;
}
debug(message) {
if (this.shouldLog('DEBUG')) console.log(this.formatMessage('DEBUG', message));
}
info(message) {
if (this.shouldLog('INFO')) console.log(this.formatMessage('INFO', message));
}
warn(message) {
if (this.shouldLog('WARN')) console.warn(this.formatMessage('WARN', message));
}
error(message) {
if (this.shouldLog('ERROR')) console.error(this.formatMessage('ERROR', message));
}
success(message) {
console.log(this.formatMessage('SUCCESS', `✓ ${message}`));
}
section(title) {
if (this.shouldLog('INFO')) {
console.log('\n' + '='.repeat(50));
console.log(` ${title}`);
console.log('='.repeat(50) + '\n');
}
}
object(label, obj) {
if (this.shouldLog('DEBUG')) {
console.log(`${label}:`);
console.log(JSON.stringify(obj, null, 2));
}
}
}
/**
* TextUtils class for text processing
*/
class TextUtils {
static normalizeAmount(amountStr) {
if (!amountStr) return null;
try {
// Get currency format from config
const currencyFormat = getCurrencyFormat();
let cleaned = amountStr;
// Remove currency symbols based on configuration
currencyFormat.symbols.forEach(symbol => {
// Escape special regex characters
const escapedSymbol = symbol.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
cleaned = cleaned.replace(new RegExp(escapedSymbol, 'gi'), '');
});
// Remove thousands separator
cleaned = cleaned.replace(new RegExp('\\' + currencyFormat.thousandsSeparator, 'g'), '');
// Remove whitespace
cleaned = cleaned.replace(/\s+/g, '').trim();
const amount = parseFloat(cleaned);
return isNaN(amount) ? null : amount.toFixed(2);
} catch (error) {
console.error(`Error normalizing amount: ${error.message}`);
return null;
}
}
static cleanText(text) {
if (!text) return null;
return text
.replace(/[\r\n]+/g, ' ')
.replace(/\s{2,}/g, ' ')
.replace(/\t+/g, ' ')
.trim();
}
static truncate(text, maxLength = 100) {
if (!text || text.length <= maxLength) return text;
return text.substring(0, maxLength - 3) + '...';
}
}
/**
* DateUtils class for date processing
*/
class DateUtils {
static parseDate(dateStr, format = null) {
if (!dateStr) return null;
try {
let cleanDateStr = dateStr.replace(/\s*(IST|GMT|UTC|EST|PST)\s*$/i, '').trim();
// If format is specified, use format-specific parser
if (format) {
let date = null;
if (format === 'DD-MM-YYYY') {
// Try DD-MM-YYYY formats and also DD MMM, YYYY format
date = DateUtils.parseDDMMYYYYComma(cleanDateStr) ||
DateUtils.parseDDMMYYYY(cleanDateStr) ||
DateUtils.parseDDMMMYYYY(cleanDateStr);
} else if (format === 'DD-MM-YY') {
// Try DD-MM-YY format (2-digit year)
date = DateUtils.parseDDMMYY(cleanDateStr);
} else if (format === 'DD-MMM-YYYY' || format === 'DD MMM YYYY') {
date = DateUtils.parseDDMMMYYYY(cleanDateStr);
} else if (format === 'MMM DD, YYYY') {
// Try MMM DD, YYYY format (e.g., Nov 24, 2025)
date = DateUtils.parseMMMDDYYYY(cleanDateStr);
}
if (date && !isNaN(date.getTime())) return date;
}
// Fallback: Try standard Date() constructor
let date = new Date(cleanDateStr);
if (!isNaN(date.getTime())) return date;
// Fallback: Try all parsers
const parsers = [
DateUtils.parseDDMMYYYYComma,
DateUtils.parseDDMMYYYY,
DateUtils.parseDDMMMYYYY
];
for (const parser of parsers) {
date = parser(cleanDateStr);
if (date && !isNaN(date.getTime())) return date;
}
console.warn(`Could not parse date: ${dateStr}, using current time`);
return new Date();
} catch (error) {
console.error(`Date parsing error: ${error}`);
return new Date();
}
}
static parseDDMMYYYYComma(dateStr) {
// DD-MM-YYYY format (e.g., 09-11-2025 = 9 Nov 2025)
const match = dateStr.match(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4}),?\s*(\d{1,2}):(\d{2}):?(\d{2})?/);
if (match) {
const day = parseInt(match[1]);
const month = parseInt(match[2]);
const year = parseInt(match[3]);
const hour = parseInt(match[4]);
const minute = parseInt(match[5]);
const second = match[6] ? parseInt(match[6]) : 0;
// JavaScript Date constructor: new Date(year, monthIndex, day, ...)
// monthIndex is 0-based: 0=Jan, 1=Feb, ..., 11=Dec
return new Date(year, month - 1, day, hour, minute, second);
}
return null;
}
static parseDDMMYYYY(dateStr) {
// DD-MM-YYYY format with optional am/pm
// Handles: "22-11-2025 03:05:35 pm" or "22-11-2025 15:05:35"
const match = dateStr.match(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})\s+(\d{1,2}):(\d{2}):?(\d{2})?\s*([ap]m)?/i);
if (match) {
const day = parseInt(match[1]);
const month = parseInt(match[2]);
const year = parseInt(match[3]);
let hour = parseInt(match[4]);
const minute = parseInt(match[5]);
const second = match[6] ? parseInt(match[6]) : 0;
const meridiem = match[7] ? match[7].toLowerCase() : null;
// Convert to 24-hour format if am/pm is present
if (meridiem) {
if (meridiem === 'pm' && hour < 12) {
hour += 12;
} else if (meridiem === 'am' && hour === 12) {
hour = 0;
}
}
return new Date(year, month - 1, day, hour, minute, second);
}
return null;
}
static parseDDMMYY(dateStr) {
// DD-MM-YY format (2-digit year, e.g., 16-11-25 = 16 Nov 2025)
const match = dateStr.match(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})$/);
if (match) {
const day = parseInt(match[1]);
const month = parseInt(match[2]);
let year = parseInt(match[3]);
// Convert 2-digit year to 4-digit
// Assume 00-49 = 2000-2049, 50-99 = 1950-1999
year = year < 50 ? 2000 + year : 1900 + year;
return new Date(year, month - 1, day);
}
return null;
}
static parseDDMMMYYYY(dateStr) {
// Format 1: DD-MMM-YYYY (e.g., 01-Dec-2025 14:30:45)
let match = dateStr.match(/(\d{1,2})[\/\-]([A-Za-z]{3})[\/\-](\d{4})\s*(\d{1,2}):(\d{2}):?(\d{2})?/);
if (match) {
const [, day, monthName, year, hour, minute, second] = match;
const date = new Date(`${monthName} ${day}, ${year} ${hour}:${minute}:${second || '00'}`);
return !isNaN(date.getTime()) ? date : null;
}
// Format 2: DD MMM, YYYY at HH:MM:SS (e.g., 26 Nov, 2025 at 12:01:34)
match = dateStr.match(/(\d{1,2})\s+([A-Za-z]{3}),\s+(\d{4})\s+at\s+(\d{1,2}):(\d{2}):?(\d{2})?/);
if (match) {
const [, day, monthName, year, hour, minute, second] = match;
const date = new Date(`${monthName} ${day}, ${year} ${hour}:${minute}:${second || '00'}`);
return !isNaN(date.getTime()) ? date : null;
}
return null;
}
static parseMMMDDYYYY(dateStr) {
// Format: MMM DD, YYYY HH:MM:SS (e.g., Nov 24, 2025 07:05:19)
// Also handles: MMM DD, YYYY at HH:MM:SS
const match = dateStr.match(/([A-Za-z]{3})\s+(\d{1,2}),\s+(\d{4})(?:\s+at)?\s+(\d{1,2}):(\d{2}):?(\d{2})?/);
if (match) {
const [, monthName, day, year, hour, minute, second] = match;
const date = new Date(`${monthName} ${day}, ${year} ${hour}:${minute}:${second || '00'}`);
return !isNaN(date.getTime()) ? date : null;
}
return null;
}
}
// ==================== BUILT-IN BANK PATTERNS ====================
/**
* Manager for bank patterns (built-in + custom)
* Encapsulates pattern loading logic
*/
class BankPatternManager {
static getDefaultPatterns() {
return [
// ============================================
// HDFC BANK
// ============================================
{
name: 'HDFC Bank UPI - Debit Account',
senderPattern: 'alerts@hdfcbank\\.net',
subjectPattern: 'You have done a UPI txn',
bodyPattern: 'has been debited from account \\d{4} to',
amountPattern: 'Rs\\.\\s*([\\d,]+\\.?\\d*)\\s+has been debited from account',
accountPattern: 'from\\s+account\\s+(\\d{4})',
// Updated to handle hyphens in VPA (e.g., 9876543210-1@upibank)
merchantPattern: 'to\\s+(?:VPA\\s+)?[\\w.-]+@\\w+\\s+([A-Za-z0-9][A-Za-z0-9\\s&\\.\\-\\*]+?)\\s+on',
datePattern: 'on\\s+(\\d{2}[/-]\\d{2}[/-]\\d{2})',
dateFormat: 'DD-MM-YY',
},
{
name: 'HDFC Bank UPI - RuPay Credit Card',
senderPattern: 'alerts@hdfcbank\\.net',
subjectPattern: 'You have done a UPI txn',
bodyPattern: 'has been debited from your HDFC Bank RuPay Credit Card',
amountPattern: 'Rs\\.\\s*([\\d,]+\\.?\\d*)\\s+has been debited from your HDFC Bank RuPay Credit Card',
accountPattern: 'from\\s+your\\s+HDFC\\s+Bank\\s+RuPay\\s+Credit\\s+Card\\s+(XX\\d{4})',
merchantPattern: 'to\\s+[\\w.]+@\\w+\\s+([A-Za-z0-9][A-Za-z0-9\\s&\\.\\-\\*]+?)\\s+on',
datePattern: 'on\\s+(\\d{2}[/-]\\d{2}[/-]\\d{2})',
dateFormat: 'DD-MM-YY',
},
{
name: 'HDFC Bank Credit Card',
senderPattern: 'alerts@hdfcbank\\.net',
subjectPattern: 'debited via Credit Card|Update on your HDFC Bank Credit Card',
bodyPattern: 'Credit Card ending \\d{4}',
amountPattern: '(?:for\\s+)?Rs\\.?\\s*([\\d,]+\\.?\\d*)',
accountPattern: '[Cc](?:redit\\s+)?[Cc]ard\\s+ending\\s+(\\d{4})',
merchantPattern: '(?:at\\s+|towards\\s+)([A-Za-z0-9][A-Za-z0-9\\s&\\.\\-\\*]+?)\\s+on',
datePattern: 'on\\s+(\\d{2}[/-]\\d{2}[/-]\\d{4}\\s+\\d{2}:\\d{2}:\\d{2}|\\d{2}\\s+\\w{3},\\s+\\d{4}\\s+at\\s+\\d{2}:\\d{2}:\\d{2})',
dateFormat: 'DD-MM-YYYY',
},
// ============================================
// AXIS BANK - Credit Card
// ============================================
{
name: 'Axis Bank Credit Card',
senderPattern: 'alerts@axisbank\\.com',
subjectPattern: 'spent on credit card|Transaction alert on Axis Bank Credit Card',
bodyPattern: 'summary of your Axis Bank Credit Card Transaction|Thank you for using your Card|Thank you for using your credit card',
amountPattern: '(?:Transaction\\s+Amount:\\s*|for\\s+)?(?:INR|Rs\\.?|₹)\\s*([\\d,]+\\.?\\d*)',
accountPattern: '(?:(?:Axis\\s+Bank\\s+)?[Cc]redit\\s+)?[Cc]ard\\s+(?:[Nn]o\\.?|ending)\\s*(XX\\d{4})',
merchantPattern: '(?:Merchant\\s+Name:\\s*|at\\s+)([A-Za-z0-9][A-Za-z0-9\\s&\\.\\-]+?)(?:[\\r\\n]|\\s{2,}|\\s+on)',
datePattern: '(?:Date\\s+&\\s+Time:\\s*|on\\s+)(\\d{2}[/-]\\d{2}[/-]\\d{4})[,\\s]+(\\d{2}:\\d{2}(?::\\d{2})?)(?:\\s+IST)?',
dateFormat: 'DD-MM-YYYY',
},
// ============================================
// INDUSIND BANK - Credit Card
// ============================================
{
name: 'IndusInd Bank Credit Card',
senderPattern: 'transactionalert@indusind\\.com',
subjectPattern: 'Transaction Alert - IndusInd Bank Credit Card',
bodyPattern: 'The transaction on your IndusInd Bank Credit Card',
// "for INR 3,275.00 on" - handle commas and optional decimals
amountPattern: 'for\\s+INR\\s+([\\d,]+(?:\\.\\d{2})?)\\s+on',
// "ending 1234" - will be auto-prefixed with XX
accountPattern: 'ending\\s+(\\d{4})',
// "at Merchant Name is Approved" - match until " is "
merchantPattern: 'at\\s+([A-Za-z0-9][^\\r\\n]+?)\\s+is\\s+Approved',
// "on 22-11-2025 03:05:35 pm at"
// Captures both date and time with am/pm
datePattern: 'on\\s+(\\d{2}-\\d{2}-\\d{4})\\s+(\\d{2}:\\d{2}:\\d{2}\\s+[ap]m)',
dateFormat: 'DD-MM-YYYY',
},
// ============================================
// ICICI BANK - Credit Card
// ============================================
{
name: 'ICICI Bank Credit Card',
senderPattern: 'credit_cards@icicibank\\.com',
subjectPattern: 'Transaction alert for your ICICI Bank Credit Card',
bodyPattern: 'Your ICICI Bank Credit Card',
// "INR 2,460.00" or "INR 2.00" - handle commas and decimals
amountPattern: 'INR\\s+([\\d,]+\\.\\d{2})',
// "XX1234" or "XX5678" - already includes XX prefix
accountPattern: '(XX\\d{4})',
// "Info: AMAZON PAY IN UTILITY" or "Info: UPI-123456789012-MERCHANT NAME"
// Match everything after "Info: " until period or end of line
merchantPattern: 'Info:\\s+([A-Za-z0-9\\s\\-*]+?)(?:\\.|$)',
// "on Nov 24, 2025 at 07:05:19" or "on Sep 19, 2025 at 08:14:10"
// Captures month abbr, day, year and time (24-hour format)
datePattern: 'on\\s+([A-Z][a-z]{2}\\s+\\d{2},\\s+\\d{4})\\s+at\\s+(\\d{2}:\\d{2}:\\d{2})',
dateFormat: 'MMM DD, YYYY',
},
// ============================================
// OneCard - Credit Card
// ============================================
{
name: 'OneCard Credit Card',
senderPattern: 'no-reply@getonecard\\.app',
subjectPattern: 'Payment update on your Federal One credit card',
bodyPattern: 'Your Federal One Credit Card ending',
// "*Amount:* INR 230.46" or "Amount: INR 2,071.00"
// Handles with/without asterisks, commas, and decimals
amountPattern: '\\*?Amount[:\\s*]+INR[\\s]+([\\d,]+(?:\\.\\d{2})?)',
// "ending in 1234" - will be auto-prefixed with XX
accountPattern: 'ending in\\s+(\\d{4})',
// "*Merchant:* MERCHANT.COM" or "Merchant: STORE* TRANSACTION123"
// Handles asterisks, alphanumeric, special chars, dots
merchantPattern: '\\*?Merchant[:\\s*]+([A-Za-z0-9*.][A-Za-z0-9*.\\s-]*?)\\s*(?:\\r?\\n|-{5,}|$)',
// "*Date:* 31/07/2025" and "*Time:* 11:30:18"
// Handles asterisks and dash separators between fields
datePattern: '\\*?Date[:\\s*]+(\\d{2}/\\d{2}/\\d{4})\\s*(?:\\r?\\n|-+\\s*\\r?\\n)*\\s*\\*?Time[:\\s*]+(\\d{2}:\\d{2}:\\d{2})',
dateFormat: 'DD-MM-YYYY', // Parser will handle / separator
},
];
}
static getAllPatterns() {
const defaultPatterns = BankPatternManager.getDefaultPatterns();
// Check if user has custom patterns defined
if (typeof getBankPatterns === 'function') {
try {
const customPatterns = getBankPatterns();
return [...defaultPatterns, ...customPatterns];
} catch (error) {
console.log('No custom bank patterns found, using defaults only');
return defaultPatterns;
}
}
return defaultPatterns;
}
}
// ==================== SERVICES ====================
/**
* EmailService for Gmail operations
*/
class EmailService {
constructor(logger) {
this.logger = logger;
}
searchEmails(searchQuery, maxResults = 50) {
try {
this.logger.info(`Searching emails with query: ${searchQuery}`);
const threads = GmailApp.search(searchQuery, 0, maxResults);
this.logger.info(`Found ${threads.length} email threads`);
return threads;
} catch (error) {
this.logger.error(`Error searching emails: ${error.message}`);
throw new Error(`Failed to search emails: ${error.message}`);
}
}
getMessagesFromThread(thread) {
try {
return thread.getMessages();
} catch (error) {
this.logger.error(`Error getting messages from thread: ${error.message}`);
throw new Error(`Failed to get messages: ${error.message}`);
}
}
extractEmailData(message) {
try {
let body = message.getPlainBody();
// Check if plain body is empty, null, or the literal string "null"
const isPlainBodyEmpty = !body || body.trim() === '' || body.trim().toLowerCase() === 'null';
if (isPlainBodyEmpty) {
this.logger.debug('Plain body empty/null, extracting from HTML...');
const htmlBody = message.getBody();
if (htmlBody && htmlBody.trim() !== '') {
// Strip HTML tags
body = this.stripHtmlTags(htmlBody);
this.logger.debug(`Extracted ${body.length} chars from HTML`);
} else {
body = '';
}
}
return {
id: message.getId(),
from: message.getFrom(),
subject: message.getSubject(),
body: body || '',
date: message.getDate()
};
} catch (error) {
this.logger.error(`Error extracting email data: ${error.message}`);
throw new Error(`Failed to extract email data: ${error.message}`);
}
}
stripHtmlTags(html) {
if (!html) return '';
try {
return html
.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '') // Remove style blocks
.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '') // Remove script blocks
.replace(/<br\s*\/?>/gi, '\n') // Convert <br> to newlines
.replace(/<\/p>/gi, '\n') // Convert </p> to newlines
.replace(/<\/div>/gi, '\n') // Convert </div> to newlines
.replace(/<[^>]+>/g, ' ') // Remove all other HTML tags
.replace(/ /gi, ' ') // Replace
.replace(/&/gi, '&') // Replace &
.replace(/</gi, '<') // Replace <
.replace(/>/gi, '>') // Replace >
.replace(/"/gi, '"') // Replace "
.replace(/'/gi, "'") // Replace '
.replace(/₹/gi, '₹') // Replace ₹ (rupee symbol)
.replace(/\s*\n\s*/g, '\n') // Clean up newlines
.replace(/\n{3,}/g, '\n\n') // Max 2 consecutive newlines
.replace(/ {2,}/g, ' ') // Normalize spaces
.trim();
} catch (error) {
this.logger.error(`Error stripping HTML: ${error.message}`);
return html;
}
}
markAsRead(message) {
try {
message.markRead();
return true;
} catch (error) {
this.logger.error(`Error marking email as read: ${error.message}`);
return false;
}
}
}
/**
* SheetService for Google Sheets operations
*/
class SheetService {
constructor(sheetId, sheetName, logger, nicknameManager) {
this.sheetId = sheetId;
this.sheetName = sheetName;
this.logger = logger;
this.nicknameManager = nicknameManager;
this.spreadsheet = null;
this.sheet = null;
}
initialize() {
try {
this.spreadsheet = SpreadsheetApp.openById(this.sheetId);
this.sheet = this.spreadsheet.getSheetByName(this.sheetName);
if (!this.sheet) {
this.logger.info(`Sheet "${this.sheetName}" not found, creating...`);
this.sheet = this.createSheet();
}
return this.sheet;
} catch (error) {
this.logger.error(`Error initializing sheet: ${error.message}`);
throw new Error(`Failed to initialize sheet: ${error.message}`);
}
}
createSheet() {
try {
const sheet = this.spreadsheet.insertSheet(this.sheetName);
this.setupHeaders(sheet);
return sheet;
} catch (error) {
this.logger.error(`Error creating sheet: ${error.message}`);
throw new Error(`Failed to create sheet: ${error.message}`);
}
}
setupHeaders(sheet) {
const headers = SHEET_HEADERS;
sheet.getRange(1, 1, 1, headers.length).setValues([headers]);
const headerRange = sheet.getRange(1, 1, 1, headers.length);
headerRange.setFontWeight(HEADER_STYLE.fontWeight);
headerRange.setBackground(HEADER_STYLE.backgroundColor);
headerRange.setFontColor(HEADER_STYLE.fontColor);
sheet.setFrozenRows(1);
this.setColumnWidths(sheet);
this.logger.info('Sheet headers created and formatted');
}
setColumnWidths(sheet) {
const widths = [100, 80, 100, 150, 180, 300, 150, 150, 250];
widths.forEach((width, index) => {
sheet.setColumnWidth(index + 1, width);
});
}
getProcessedEmailIds() {
try {
if (!this.sheet) this.initialize();
const lastRow = this.sheet.getLastRow();
if (lastRow <= 1) return new Set();
const emailIds = this.sheet.getRange(2, 9, lastRow - 1, 1).getValues();
return new Set(emailIds.map(row => row[0]).filter(id => id));
} catch (error) {
this.logger.error(`Error getting processed email IDs: ${error.message}`);
return new Set();
}
}
appendTransaction(transaction, emailId) {
try {
if (!this.sheet) this.initialize();
const row = this.formatTransactionRow(transaction, emailId);
// Append at bottom for chronological order (oldest first, newest last)
this.sheet.appendRow(row);
// Format the amount column
const lastRow = this.sheet.getLastRow();
this.sheet.getRange(lastRow, 3).setNumberFormat(AMOUNT_FORMAT);
this.logger.info(`Transaction appended: ${transaction.merchant} - ${transaction.amount}`);
return true;
} catch (error) {
this.logger.error(`Error appending transaction: ${error.message}`);
return false;
}
}
formatTransactionRow(transaction, emailId) {
const date = transaction.datetime || new Date();
const timezone = getTimezone();
const accountNickname = this.nicknameManager
? this.nicknameManager.getAccountNickname(transaction.account || '', transaction.source || '')
: '';
const category = CategoryMapper.categorize(transaction.merchant || '');
return [
Utilities.formatDate(date, timezone, 'dd-MMM-yyyy'),
Utilities.formatDate(date, timezone, 'HH:mm:ss'),
transaction.amount,
transaction.account || 'N/A',
accountNickname || '',
transaction.merchant || 'N/A',
category,
transaction.source || 'Unknown',
emailId
];
}
getSheet() {
if (!this.sheet) this.initialize();
return this.sheet;
}
}
/**
* TransactionParser for parsing transaction emails
*/
class TransactionParser {
constructor(logger) {
this.logger = logger;
this.patterns = BankPatternManager.getAllPatterns();
}
parseEmail(emailData) {
this.logger.debug(`Parsing email from: ${emailData.from}`);
this.logger.debug(`Subject: ${emailData.subject}`);
const pattern = this.findMatchingPattern(emailData);
if (!pattern) {
this.logger.warn('No matching pattern found for email');
return null;
}
this.logger.info(`Matched pattern: ${pattern.name}`);
const transaction = this.extractTransaction(emailData, pattern);
if (!transaction) {
this.logger.warn('Failed to extract transaction data');
return null;
}
return transaction;
}
findMatchingPattern(emailData) {
for (const pattern of this.patterns) {
if (this.isPatternMatch(emailData, pattern)) {
return pattern;
}
}
return null;
}
isPatternMatch(emailData, pattern) {
const senderMatch = pattern.senderPattern
? new RegExp(pattern.senderPattern, 'i').test(emailData.from)
: false;
const subjectMatch = pattern.subjectPattern
? new RegExp(pattern.subjectPattern, 'i').test(emailData.subject)
: false;
this.logger.debug(`Testing pattern: ${pattern.name}`);
this.logger.debug(` Sender match: ${senderMatch} (pattern: ${pattern.senderPattern})`);
this.logger.debug(` Subject match: ${subjectMatch} (pattern: ${pattern.subjectPattern})`);
// Basic match: sender OR subject
const basicMatch = senderMatch || subjectMatch;
// If bodyPattern is specified, it MUST also match (additional validation)
if (basicMatch && pattern.bodyPattern) {
const bodyMatch = new RegExp(pattern.bodyPattern, 'i').test(emailData.body);
this.logger.debug(` Body match: ${bodyMatch} (pattern: ${pattern.bodyPattern})`);
return bodyMatch;
}
return basicMatch;
}
extractTransaction(emailData, pattern) {
const transaction = {
datetime: null,
amount: null,
account: null,
merchant: null,
source: pattern.name
};
if (pattern.amountPattern) {
transaction.amount = this.extractField(emailData.body, pattern.amountPattern, TextUtils.normalizeAmount);
}
if (pattern.accountPattern) {
let account = this.extractField(emailData.body, pattern.accountPattern, TextUtils.cleanText);
// Add XX prefix if it's just 4 digits (and doesn't already have XX)
if (account && /^\d{4}$/.test(account)) {
account = 'XX' + account;
}
transaction.account = account;
}
if (pattern.merchantPattern) {
transaction.merchant = this.extractField(emailData.body, pattern.merchantPattern, TextUtils.cleanText);
}
if (pattern.datePattern) {
// Pass date format to parser
transaction.datetime = this.extractField(
emailData.body,
pattern.datePattern,
(dateStr) => DateUtils.parseDate(dateStr, pattern.dateFormat)
);
}
if (!transaction.datetime) {
transaction.datetime = emailData.date;
}
if (!transaction.amount) {
this.logger.warn('Transaction missing amount');
return null;
}
return transaction;
}
extractField(text, pattern, formatter) {
try {
const match = text.match(new RegExp(pattern, 'i'));
if (match) {
let value;
// Check if we have multiple capture groups
if (match.length > 2) {
// Find the first non-null captured group (skip match[0] which is full match)
for (let i = 1; i < match.length; i++) {
if (match[i]) {
value = match[i];
// For date patterns, check if next group is time
if (i + 1 < match.length && match[i + 1] && /^\d{2}:\d{2}/.test(match[i + 1])) {
value = match[i] + ' ' + match[i + 1];
}
break;
}
}
} else {
// Single capture group
value = match[1] || match[0];
}
this.logger.debug(`Extracted value: "${value}" using pattern: ${pattern}`);
return formatter ? formatter(value) : value;
}
// Enhanced debug: show portion of text around where we expected to find match
const patternKey = pattern.substring(0, 20);
const textSample = text.substring(0, 200);
this.logger.debug(`No match found for pattern: ${pattern}`);
this.logger.debug(`Text sample (first 200 chars): ${textSample}`);
return null;
} catch (error) {
this.logger.error(`Error extracting field with pattern "${pattern}": ${error.message}`);
return null;
}
}
}
/**
* QueryBuilder for building Gmail search queries
*/
class QueryBuilder {
constructor(logger) {
this.logger = logger;
}
buildFromPatterns(patterns, searchDays) {
const senders = this.extractSenders(patterns);
const subjectPhrases = this.extractSubjectPhrases(patterns);
const queryParts = [];
if (senders.length > 0) queryParts.push(`from:(${senders.join(' OR ')})`);
if (subjectPhrases.length > 0) queryParts.push(`subject:(${subjectPhrases.join(' OR ')})`);
queryParts.push(`newer_than:${searchDays}d`);
const query = queryParts.join(' ');
this.logger.debug(`Built search query: ${query}`);
return query;
}
extractSenders(patterns) {
const senders = [];
patterns.forEach(pattern => {
if (pattern.senderPattern) {
// Split by | to get multiple sender patterns
const senderEmails = pattern.senderPattern.split('|');
senderEmails.forEach(email => {
// Clean up the regex syntax to get the actual email
const cleanEmail = email
.replace(/\\/g, '') // Remove backslashes
.trim();
if (cleanEmail.includes('@')) {
senders.push(cleanEmail);
}
});
}
});
return [...new Set(senders)];
}
extractSubjectPhrases(patterns) {
const phrases = [];
patterns.forEach(pattern => {
if (pattern.subjectPattern) {
// Split by | to get individual phrase patterns
const individualPatterns = pattern.subjectPattern.split('|');
individualPatterns.forEach(subPattern => {
// Clean up regex syntax and get the actual phrase
let phrase = subPattern
.replace(/\\/g, '') // Remove backslashes
.replace(/\.\*\?/g, '') // Remove .*?
.replace(/\\s\+/g, ' ') // Replace \s+ with space
.replace(/\\s/g, ' ') // Replace \s with space
.replace(/[\(\)\[\]\{\}]/g, '') // Remove grouping brackets
.trim();
// Only add if it's a meaningful phrase (not just regex)
if (phrase.length > 0 && phrase.split(' ').length >= 2) {
// Wrap in quotes for exact phrase matching in Gmail
phrases.push(`"${phrase}"`);
}
});
}
});
return phrases;
}
}
// ==================== SERVICE INITIALIZATION ====================
/**
* Factory for initializing all services
*/
class ServiceFactory {
static initialize() {
const logger = new Logger(LOG_LEVEL);
const spreadsheet = SpreadsheetApp.openById(SHEET_ID);
const emailService = new EmailService(logger);
const nicknameManager = new NicknameManager(spreadsheet, logger);
const sheetService = new SheetService(SHEET_ID, SHEET_NAME, logger, nicknameManager);
const transactionParser = new TransactionParser(logger);
const queryBuilder = new QueryBuilder(logger);
// Initialize nickname manager
nicknameManager.initialize();
return { logger, emailService, sheetService, transactionParser, queryBuilder, nicknameManager };
}
}
// ==================== MAIN FUNCTIONS ====================
// These are the primary functions users will run
/**
* Main automation function - processes transaction emails and adds to sheet
* This function is called automatically every 10 minutes by the trigger
* You can also run it manually anytime
*
* @returns {Object} Result with success status, totalEmails, and newTransactions
*/
function processTransactionEmails() {
const services = ServiceFactory.initialize();
const { logger, emailService, sheetService, transactionParser, queryBuilder } = services;
try {
logger.section('TransacFlow - Processing Transaction Emails');
sheetService.initialize();
const processedEmailIds = sheetService.getProcessedEmailIds();
logger.info(`Already processed: ${processedEmailIds.size} transactions`);
const searchQuery = SEARCH_QUERY_MODE === 'DYNAMIC'
? queryBuilder.buildFromPatterns(BankPatternManager.getAllPatterns(), EMAIL_SEARCH_DAYS)
: getSearchQuery();
const threads = emailService.searchEmails(searchQuery, MAX_EMAILS_PER_RUN);
if (threads.length === 0) {
logger.info('No new emails found matching the query');
return { success: true, totalEmails: 0, newTransactions: 0 };
}
let emailsProcessed = 0;
const newTransactionsList = []; // Collect all new transactions
const messagesToMarkRead = []; // Track messages to mark as read
threads.forEach(thread => {
const messages = emailService.getMessagesFromThread(thread);
messages.forEach(message => {
const emailData = emailService.extractEmailData(message);
if (processedEmailIds.has(emailData.id)) {
logger.debug(`Skipping already processed email: ${emailData.id}`);
return;
}
emailsProcessed++;
const transaction = transactionParser.parseEmail(emailData);
if (transaction) {
newTransactionsList.push({
transaction: transaction,
emailId: emailData.id,
message: message
});
}
});
});
// Sort transactions by datetime (oldest first)
// Append in chronological order: oldest at top, newest at bottom