File size: 55,060 Bytes
149698e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
# ICC Interac Manager β€” Complete Build Prompt & Specification

---

## System Prompt / Role

You are an expert Senior Full-Stack Developer specializing in modern web applications, desktop apps, email integration (IMAP/Gmail API), and AI-powered data extraction. Your task is to build the **"ICC Interac Manager"** β€” a dual-platform application (Vite.js Web + Electron Desktop) that automatically scans email accounts for Interac e-Transfer notifications, extracts structured transaction data using AI, categorizes each transaction by city/branch, displays results in a live dashboard table, and generates PDF receipts.

---

## 1. Project Overview

**App Name:** ICC Interac Manager  
**Platforms:**
- **Web App (Primary):** Vite.js + React + TypeScript β€” deployed as a live SaaS-style web application
- **Desktop App (Secondary):** Electron wrapping the same React codebase for offline/local use

**Purpose:** Automate the scanning, parsing, categorization, and reporting of Interac e-Transfer emails received across multiple ICC branch email accounts.

### Key Features

1. **Gmail OAuth Login** β€” User authenticates with their Gmail account (Google OAuth 2.0). No passwords stored.
2. **Email Scanning** β€” Fetch emails ONLY from `notify@payments.interac.ca` via Gmail API or IMAP, with flexible date range controls: scan today only, last 7 days, or any custom date range.
3. **AI-Powered Parsing** β€” Extract structured transaction data from each email body using an LLM.
4. **City/Branch Routing** β€” Map the `recipient_email` field to a known ICC branch based on a configuration table.
5. **Live Dashboard** β€” Display all parsed transactions in a sortable, filterable table with columns: `Date | ExpΓ©diteur | Montant | RΓ©fΓ©rence | Succursale/Ville | Statut`.
6. **PDF Receipt Generation** β€” Generate a branded PDF receipt per transaction or in batch.
7. **Export** β€” Export data to CSV/Excel.
8. **Real-time Sync** β€” Live updates via WebSockets or Server-Sent Events in the web version.

---

## 2. Architecture β€” Monorepo with Shared Core

### Project Structure (Monorepo)

```
icc-interac-manager/
β”œβ”€β”€ packages/
β”‚   β”œβ”€β”€ shared/                    # Shared types, constants, utilities
β”‚   β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”‚   β”œβ”€β”€ types/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ transaction.ts  # InteracTransaction, BranchConfig, etc.
β”‚   β”‚   β”‚   β”‚   └── scan.ts         # ScanPreset, ScanDateRange, ScanRequest, ScanJob
β”‚   β”‚   β”‚   β”œβ”€β”€ constants/
β”‚   β”‚   β”‚   β”‚   └── branches.ts     # Complete emailβ†’branch mapping
β”‚   β”‚   β”‚   β”œβ”€β”€ utils/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ parser.ts       # AI prompt templates
β”‚   β”‚   β”‚   β”‚   └── formatter.ts    # Currency, date formatting
β”‚   β”‚   β”‚   └── index.ts
β”‚   β”‚   β”œβ”€β”€ package.json
β”‚   β”‚   └── tsconfig.json
β”‚   β”‚
β”‚   β”œβ”€β”€ web/                       # β˜… Vite.js Web Application
β”‚   β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”‚   β”œβ”€β”€ main.tsx
β”‚   β”‚   β”‚   β”œβ”€β”€ App.tsx
β”‚   β”‚   β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ layout/
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ Sidebar.tsx
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ Header.tsx
β”‚   β”‚   β”‚   β”‚   β”‚   └── MainLayout.tsx
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ dashboard/
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ TransactionTable.tsx
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ TransactionRow.tsx
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ TransactionDetail.tsx
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ SummaryBar.tsx
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ FilterPanel.tsx
β”‚   β”‚   β”‚   β”‚   β”‚   └── StatusBadge.tsx
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ auth/
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ GoogleLoginButton.tsx
β”‚   β”‚   β”‚   β”‚   β”‚   └── ProtectedRoute.tsx
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ settings/
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ BranchManager.tsx
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ AIProviderConfig.tsx
β”‚   β”‚   β”‚   β”‚   β”‚   └── EmailAccountConfig.tsx
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ scan/
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ ScanControls.tsx      # Preset toggle + custom date pickers
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ ScanProgress.tsx      # WebSocket-powered progress bar
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ ScanHistory.tsx       # Past scans table
β”‚   β”‚   β”‚   β”‚   β”‚   └── QuickScanButtons.tsx  # Dashboard header quick actions
β”‚   β”‚   β”‚   β”‚   └── receipts/
β”‚   β”‚   β”‚   β”‚       β”œβ”€β”€ ReceiptPreview.tsx
β”‚   β”‚   β”‚   β”‚       └── BatchExport.tsx
β”‚   β”‚   β”‚   β”œβ”€β”€ pages/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ DashboardPage.tsx
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ LoginPage.tsx
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ SettingsPage.tsx
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ ReportsPage.tsx
β”‚   β”‚   β”‚   β”‚   └── ScanPage.tsx
β”‚   β”‚   β”‚   β”œβ”€β”€ hooks/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ useTransactions.ts
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ useEmailScan.ts
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ useScanDateRange.ts  # Manages preset selection + custom date state
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ useAuth.ts
β”‚   β”‚   β”‚   β”‚   └── useRealtime.ts
β”‚   β”‚   β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ api.ts            # Axios/fetch wrapper to backend
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ gmail.ts          # Gmail API client-side helpers
β”‚   β”‚   β”‚   β”‚   └── websocket.ts      # Real-time connection
β”‚   β”‚   β”‚   β”œβ”€β”€ stores/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ authStore.ts      # Zustand auth state
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ transactionStore.ts
β”‚   β”‚   β”‚   β”‚   └── settingsStore.ts
β”‚   β”‚   β”‚   └── lib/
β”‚   β”‚   β”‚       β”œβ”€β”€ pdf.ts            # Client-side PDF generation
β”‚   β”‚   β”‚       └── export.ts         # CSV/Excel export
β”‚   β”‚   β”œβ”€β”€ index.html
β”‚   β”‚   β”œβ”€β”€ vite.config.ts
β”‚   β”‚   β”œβ”€β”€ tailwind.config.ts
β”‚   β”‚   β”œβ”€β”€ postcss.config.js
β”‚   β”‚   β”œβ”€β”€ tsconfig.json
β”‚   β”‚   └── package.json
β”‚   β”‚
β”‚   β”œβ”€β”€ server/                    # Express.js / Fastify Backend API
β”‚   β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”‚   β”œβ”€β”€ index.ts            # Server entry point
β”‚   β”‚   β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ auth.ts          # Google OAuth callback, token mgmt
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ emails.ts        # Scan trigger, fetch status
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ transactions.ts  # CRUD, list, filter, export
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ settings.ts      # Branch config, AI provider config
β”‚   β”‚   β”‚   β”‚   └── receipts.ts      # PDF generation endpoint
β”‚   β”‚   β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ gmailService.ts  # Gmail API integration
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ imapService.ts   # IMAP fallback
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ aiService.ts     # Unified AI provider abstraction
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ parserService.ts # Email body β†’ AI β†’ JSON
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ routingService.ts# Branch routing logic
β”‚   β”‚   β”‚   β”‚   └── pdfService.ts    # Server-side PDF generation
β”‚   β”‚   β”‚   β”œβ”€β”€ providers/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ anthropic.ts     # Claude adapter
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ openai.ts        # GPT adapter
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ google.ts        # Gemini adapter
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ openrouter.ts    # OpenRouter adapter
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ ollama.ts        # Local Ollama adapter
β”‚   β”‚   β”‚   β”‚   └── index.ts         # Provider factory
β”‚   β”‚   β”‚   β”œβ”€β”€ middleware/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ auth.ts          # JWT verification
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ rateLimit.ts     # API rate limiting
β”‚   β”‚   β”‚   β”‚   └── errorHandler.ts
β”‚   β”‚   β”‚   β”œβ”€β”€ db/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ schema.ts        # Drizzle ORM / Prisma schema
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ migrations/
β”‚   β”‚   β”‚   β”‚   └── seed.ts          # Seed branch config
β”‚   β”‚   β”‚   β”œβ”€β”€ websocket/
β”‚   β”‚   β”‚   β”‚   └── scanEvents.ts    # Real-time scan progress
β”‚   β”‚   β”‚   └── config/
β”‚   β”‚   β”‚       └── env.ts           # Environment config validation
β”‚   β”‚   β”œβ”€β”€ tsconfig.json
β”‚   β”‚   └── package.json
β”‚   β”‚
β”‚   └── desktop/                   # Electron wrapper (optional)
β”‚       β”œβ”€β”€ src/
β”‚       β”‚   β”œβ”€β”€ main.ts             # Electron main process
β”‚       β”‚   β”œβ”€β”€ preload.ts
β”‚       β”‚   └── ipc/                # IPC handlers for native features
β”‚       β”œβ”€β”€ electron-builder.yml
β”‚       └── package.json
β”‚
β”œβ”€β”€ package.json                   # Root workspace config
β”œβ”€β”€ pnpm-workspace.yaml            # or npm workspaces
β”œβ”€β”€ turbo.json                     # Turborepo config (optional)
β”œβ”€β”€ .env.example
β”œβ”€β”€ docker-compose.yml             # For local dev (PostgreSQL, Redis)
└── README.md
```

---

## 3. Tech Stack β€” Vite.js Web Version (Primary)

### Frontend (Vite + React)

```
Framework:       Vite 6 + React 19 + TypeScript 5
Styling:         Tailwind CSS 4 + shadcn/ui
Routing:         React Router v7 (or TanStack Router)
State:           Zustand (global) + TanStack Query v5 (server state / caching)
Tables:          TanStack Table v8 (sorting, filtering, pagination)
Forms:           React Hook Form + Zod validation
Charts:          Recharts (summary statistics)
PDF:             @react-pdf/renderer (client-side) + server-side fallback
Export:          SheetJS (xlsx) + native CSV generation
Date handling:   date-fns (with fr-CA locale)
Icons:           Lucide React
Notifications:   Sonner (toast notifications)
Real-time:       Socket.io client or native EventSource (SSE)
```

### Backend (Node.js API)

```
Runtime:         Node.js 20+ LTS
Framework:       Express.js 5 or Fastify 5
Language:        TypeScript 5
ORM:             Drizzle ORM (lightweight, SQL-first) or Prisma
Database:        PostgreSQL 16 (production) / SQLite (dev/desktop)
Cache:           Redis (optional, for scan job queue)
Job Queue:       BullMQ (for background email scanning) or simple cron
Auth:            Google OAuth 2.0 + JWT sessions
Email:           googleapis npm package (Gmail API)
IMAP:            imapflow (for non-Gmail accounts)
AI SDKs:         @anthropic-ai/sdk, openai, @google/generative-ai
PDF:             PDFKit or Puppeteer (server-side generation)
Validation:      Zod (shared schemas with frontend)
WebSocket:       Socket.io or ws (for real-time scan updates)
Logging:         Pino
```

### Vite Configuration

```typescript
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';
import path from 'path';

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
      '@shared': path.resolve(__dirname, '../shared/src'),
    },
  },
  server: {
    port: 5173,
    proxy: {
      '/api': {
        target: 'http://localhost:3001',
        changeOrigin: true,
      },
      '/ws': {
        target: 'ws://localhost:3001',
        ws: true,
      },
    },
  },
  build: {
    outDir: 'dist',
    sourcemap: true,
  },
});
```

### Environment Variables

```env
# .env.example (Web version)
# Google OAuth
VITE_GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your-google-client-secret

# Backend
PORT=3001
DATABASE_URL=postgresql://user:pass@localhost:5432/icc_interac
REDIS_URL=redis://localhost:6379
JWT_SECRET=your-jwt-secret

# AI Provider (pick one or configure multiple in settings)
AI_PROVIDER=anthropic
ANTHROPIC_API_KEY=sk-ant-...
OPENAI_API_KEY=sk-...
GOOGLE_AI_API_KEY=AIza...
OPENROUTER_API_KEY=sk-or-...
OLLAMA_BASE_URL=http://localhost:11434

# App
SCAN_INTERVAL_MINUTES=5
APP_URL=http://localhost:5173
```

---

## 4. Authentication & Email Access

### Gmail OAuth 2.0 Flow (Web Version)

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Browser  │────▢│ Google OAuth  │────▢│ Backend      │────▢│ Database β”‚
β”‚  (Vite)   β”‚     β”‚ Consent      β”‚     β”‚ /api/auth/   β”‚     β”‚ (tokens) β”‚
β”‚           │◀────│ Screen       │◀────│ callback     │◀────│          β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Flow:
1. User clicks "Se connecter avec Google" button
2. Frontend redirects to Google OAuth consent URL
3. Scopes requested:
   - https://www.googleapis.com/auth/gmail.readonly
   - https://www.googleapis.com/auth/userinfo.email
   - https://www.googleapis.com/auth/userinfo.profile
4. Google redirects back to /api/auth/google/callback with auth code
5. Backend exchanges code for access_token + refresh_token
6. Backend stores encrypted tokens in DB, issues JWT to frontend
7. Frontend stores JWT in httpOnly cookie or secure localStorage
8. All subsequent API calls include JWT in Authorization header
```

**Google Cloud Console Setup:**
- Create project β†’ Enable Gmail API
- OAuth consent screen β†’ External β†’ Add scopes
- Credentials β†’ OAuth 2.0 Client ID β†’ Web application
- Authorized redirect URIs: `http://localhost:3001/api/auth/google/callback` (dev) + production URL
- Authorized JavaScript origins: `http://localhost:5173` (dev) + production URL

### IMAP Fallback (For cPanel / Outlook / non-Gmail)

```typescript
// Server-side only β€” never expose IMAP credentials to frontend
interface IMAPConfig {
  host: string;        // e.g., "mail.iccameriques.org" or "imap.gmail.com"
  port: number;        // 993 (SSL)
  secure: true;
  auth: {
    user: string;      // e.g., "finances@iccameriques.org"
    pass: string;      // App password or OAuth2 token
  };
}
// Search filter: FROM "notify@payments.interac.ca"
```

---

## 5. Email Scanning β€” Date Range System

### Scan Mode Presets

The scan interface MUST provide three modes for selecting which emails to scan. These control the Gmail API `after:` / `before:` search operators (or IMAP `SINCE` / `BEFORE` filters).

| Mode | Label (FR) | Behavior |
|------|-----------|----------|
| **Today** | `Aujourd'hui` | From midnight (00:00:00) of the current day in the user's timezone β†’ now. Default mode. |
| **Last 7 Days** | `7 derniers jours` | From midnight 7 days ago β†’ now. |
| **Custom Range** | `PΓ©riode personnalisΓ©e` | User selects a start date and end date via a date picker. Supports ranges spanning months or years (e.g., 2024-01-10 to 2025-03-12). |

### Shared Types

```typescript
// packages/shared/src/types/scan.ts

export type ScanPreset = 'today' | 'last7days' | 'custom';

export interface ScanDateRange {
  preset: ScanPreset;
  startDate: string;   // ISO 8601 date: "2024-01-10T00:00:00Z"
  endDate: string;     // ISO 8601 date: "2025-03-12T23:59:59Z"
}

export interface ScanRequest {
  dateRange: ScanDateRange;
  forceRescan?: boolean;  // re-process emails already in DB (default: false)
}

export interface ScanJob {
  jobId: string;
  status: 'queued' | 'scanning' | 'parsing' | 'completed' | 'failed';
  dateRange: ScanDateRange;
  progress: {
    emailsFound: number;
    emailsProcessed: number;
    emailsSkipped: number;   // already in DB (deduplication)
    emailsErrored: number;
    currentEmail?: string;   // subject or sender being processed now
  };
  startedAt: string;
  completedAt?: string;
}

// Helper to resolve preset β†’ concrete dates
export function resolveScanDates(preset: ScanPreset, customStart?: string, customEnd?: string): ScanDateRange {
  const now = new Date();
  switch (preset) {
    case 'today': {
      const midnight = new Date(now);
      midnight.setHours(0, 0, 0, 0);
      return { preset, startDate: midnight.toISOString(), endDate: now.toISOString() };
    }
    case 'last7days': {
      const sevenDaysAgo = new Date(now);
      sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
      sevenDaysAgo.setHours(0, 0, 0, 0);
      return { preset, startDate: sevenDaysAgo.toISOString(), endDate: now.toISOString() };
    }
    case 'custom': {
      if (!customStart || !customEnd) throw new Error('Custom range requires startDate and endDate');
      return {
        preset,
        startDate: new Date(customStart + 'T00:00:00').toISOString(),
        endDate: new Date(customEnd + 'T23:59:59').toISOString(),
      };
    }
  }
}
```

### Gmail API Query Construction

```typescript
// packages/server/src/services/gmailService.ts

function buildGmailQuery(dateRange: ScanDateRange): string {
  // Gmail search uses YYYY/MM/DD format for after: and before:
  const start = new Date(dateRange.startDate);
  const end = new Date(dateRange.endDate);

  // Gmail after:/before: are DATE-only (not datetime), and after: is exclusive
  // So subtract 1 day from start to make it inclusive
  const afterDate = new Date(start);
  afterDate.setDate(afterDate.getDate() - 1);

  // Add 1 day to end to make before: inclusive of the end date
  const beforeDate = new Date(end);
  beforeDate.setDate(beforeDate.getDate() + 1);

  const fmt = (d: Date) => `${d.getFullYear()}/${d.getMonth() + 1}/${d.getDate()}`;

  return `from:notify@payments.interac.ca after:${fmt(afterDate)} before:${fmt(beforeDate)}`;
}

// Examples:
// Today (Feb 23, 2026):
//   "from:notify@payments.interac.ca after:2026/2/22 before:2026/2/24"
//
// Last 7 days (Feb 17-23, 2026):
//   "from:notify@payments.interac.ca after:2026/2/16 before:2026/2/24"
//
// Custom (Jan 10, 2024 β†’ Mar 12, 2025):
//   "from:notify@payments.interac.ca after:2024/1/9 before:2025/3/13"
```

### IMAP Date Filter Construction

```typescript
// packages/server/src/services/imapService.ts

function buildIMAPSearch(dateRange: ScanDateRange): any[] {
  const start = new Date(dateRange.startDate);
  const end = new Date(dateRange.endDate);

  return [
    { from: 'notify@payments.interac.ca' },
    { since: start },    // IMAP SINCE is inclusive (on or after)
    { before: end },     // IMAP BEFORE is exclusive (before this date)
  ];
}
```

### Scan UI Component (Frontend)

```typescript
// packages/web/src/components/scan/ScanControls.tsx
//
// Layout:
// β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
// β”‚  Scanner les courriels Interac                                     β”‚
// β”‚                                                                    β”‚
// β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
// β”‚  β”‚ Aujourd'hui β”‚ β”‚ 7 derniers jours β”‚ β”‚ PΓ©riode personnalisΓ©e  β”‚ β”‚
// β”‚  β”‚   (active)  β”‚ β”‚                  β”‚ β”‚                         β”‚ β”‚
// β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
// β”‚                                                                    β”‚
// β”‚  [Only visible when "PΓ©riode personnalisΓ©e" is selected:]          β”‚
// β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                     β”‚
// β”‚  β”‚ Date de dΓ©but     β”‚    β”‚ Date de fin       β”‚                    β”‚
// β”‚  β”‚ πŸ“… 2024-01-10    β”‚    β”‚ πŸ“… 2025-03-12    β”‚                     β”‚
// β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                     β”‚
// β”‚                                                                    β”‚
// β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                    β”‚
// β”‚  β”‚  πŸ” Scanner maintenant                    β”‚                    β”‚
// β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                    β”‚
// β”‚                                                                    β”‚
// β”‚  ☐ Forcer le re-scan (re-traiter les courriels dΓ©jΓ  importΓ©s)     β”‚
// β”‚                                                                    β”‚
// β”‚  [During scan β€” progress bar:]                                     β”‚
// β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                    β”‚
// β”‚  β”‚ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘  47/120 courriels  β”‚                    β”‚
// β”‚  β”‚ PΓ©riode: 10 janv. 2024 β†’ 12 mars 2025    β”‚                    β”‚
// β”‚  β”‚ Dernier traitΓ©: John Doe β€” 150,00 $       β”‚                    β”‚
// β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                    β”‚
// β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
//
// Implementation notes:
// - Use shadcn/ui ToggleGroup for the 3 preset buttons
// - Use shadcn/ui DatePicker (Popover + Calendar) for custom range
// - Custom date pickers only visible when "PΓ©riode personnalisΓ©e" is active
// - Date validation: startDate must be before endDate, endDate cannot be in the future
// - "Scanner maintenant" button disabled during an active scan
// - Progress bar powered by WebSocket scan:progress events
// - Show scan summary toast on completion: "47 nouveaux virements importΓ©s"
```

### Scan Quick Actions in Dashboard Header

```typescript
// The dashboard header should include quick-scan buttons for common operations:
//
// β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
// β”‚  πŸ“Š Tableau de bord                                         β”‚
// β”‚                                                             β”‚
// β”‚  [Scanner aujourd'hui]  [Scanner 7 jours]  [Scan avancΓ© β†’] β”‚
// β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
//
// "Scanner aujourd'hui" β†’ immediate scan with preset='today'
// "Scanner 7 jours" β†’ immediate scan with preset='last7days'
// "Scan avancΓ© β†’" β†’ navigates to full ScanPage with custom date picker
```

### Large Date Range Handling

For custom scans spanning months or years (e.g., Jan 2024 β†’ Mar 2025 = ~14 months), the system must handle potentially thousands of emails:

```typescript
// packages/server/src/services/scanService.ts

const BATCH_SIZE = 50;           // Process emails in batches
const RATE_LIMIT_DELAY = 100;    // ms between Gmail API calls (respect quota)

async function executeScan(scanRequest: ScanRequest, userId: string): Promise<void> {
  const { dateRange } = scanRequest;

  // 1. Build query and fetch all matching message IDs
  const query = buildGmailQuery(dateRange);
  const messageIds = await gmail.fetchAllMessageIds(query);
  // For large ranges, this could return 1000+ IDs

  // 2. Filter out already-processed emails (deduplication)
  const existingIds = await db.getExistingEmailIds(messageIds);
  const newIds = scanRequest.forceRescan
    ? messageIds
    : messageIds.filter(id => !existingIds.has(id));

  // 3. Emit initial progress
  websocket.emit('scan:started', {
    jobId, totalEmails: messageIds.length,
    newEmails: newIds.length,
    skipped: messageIds.length - newIds.length,
    dateRange,
  });

  // 4. Process in batches
  for (let i = 0; i < newIds.length; i += BATCH_SIZE) {
    const batch = newIds.slice(i, i + BATCH_SIZE);
    const results = await Promise.allSettled(
      batch.map(id => processEmail(id, userId))
    );

    // 5. Emit progress after each batch
    websocket.emit('scan:progress', {
      jobId,
      processed: Math.min(i + BATCH_SIZE, newIds.length),
      total: newIds.length,
      batchResults: results.map(r => r.status),
    });

    await sleep(RATE_LIMIT_DELAY);
  }

  // 6. Emit completion
  websocket.emit('scan:completed', { jobId, summary: { ... } });
}
```

---

## 6. Email Parsing with AI

### What to Extract

From each Interac e-Transfer notification email, the AI must extract:

```typescript
interface InteracTransaction {
  sender: string;              // "John Doe"
  amount: number;              // 150.00
  currency: string;            // "CAD"
  reference: string;           // "CA1b2c3d4e5f"
  message: string | null;      // "Dime pour mars 2025"
  recipient_email: string;     // "montreal.finances@iccameriques.org"
  date: string;                // "2025-02-15T14:30:00Z" (ISO 8601)
  status: 'deposited' | 'pending' | 'expired' | 'cancelled';
}
```

### AI Prompt Template

```
You are a financial data extraction assistant. Given the raw text/HTML of an Interac e-Transfer notification email from notify@payments.interac.ca, extract the following fields into a JSON object:

- sender: The name of the person who sent the money
- amount: The dollar amount (numeric, no $ sign)
- currency: Always "CAD"
- reference: The Interac reference number
- message: The personal message or memo (sometimes called "dime")
- recipient_email: The email address the transfer was sent TO (the ICC branch email)
- date: The date/time of the transfer in ISO 8601 format
- status: One of "deposited", "pending", "expired", "cancelled"

Rules:
- If a field is not found, set it to null.
- The amount must be a number (e.g., 150.00 not "$150.00").
- Return ONLY valid JSON, no markdown, no explanation.

Email content:
"""
{EMAIL_BODY}
"""
```

### Unified AI Provider Interface

```typescript
// packages/server/src/services/aiService.ts
interface AIProvider {
  name: string;
  parse(emailBody: string): Promise<InteracTransaction>;
}

class AIService {
  private provider: AIProvider;

  constructor(providerName: string) {
    this.provider = AIProviderFactory.create(providerName);
  }

  async parseEmail(emailBody: string): Promise<InteracTransaction> {
    const result = await this.provider.parse(emailBody);
    // Validate with Zod schema before returning
    return InteracTransactionSchema.parse(result);
  }
}
```

---

## 7. AI Model Options

### Tier 1: Cloud API β€” Best Accuracy

| Provider | Model | API Endpoint | Best For | Approx Cost |
|----------|-------|-------------|----------|-------------|
| **Anthropic** | `claude-sonnet-4-20250514` | `api.anthropic.com/v1/messages` | Best structured extraction | ~$3/$15 per 1M tokens |
| **Anthropic** | `claude-haiku-4-5-20251001` | `api.anthropic.com/v1/messages` | Fast + cheap extraction | ~$0.80/$4 per 1M tokens |
| **OpenAI** | `gpt-4o` | `api.openai.com/v1/chat/completions` | Great all-rounder | ~$2.50/$10 per 1M tokens |
| **OpenAI** | `gpt-4o-mini` | `api.openai.com/v1/chat/completions` | Cheapest OpenAI option | ~$0.15/$0.60 per 1M tokens |
| **Google** | `gemini-2.0-flash` | `generativelanguage.googleapis.com` | Very fast, good accuracy | ~$0.10/$0.40 per 1M tokens |
| **Google** | `gemini-2.5-pro` | `generativelanguage.googleapis.com` | Top-tier Google model | ~$1.25/$10 per 1M tokens |
| **Mistral** | `mistral-large-latest` | `api.mistral.ai/v1/chat/completions` | European hosting, strong | ~$2/$6 per 1M tokens |
| **Mistral** | `mistral-small-latest` | `api.mistral.ai/v1/chat/completions` | Budget option | ~$0.20/$0.60 per 1M tokens |

### Tier 2: Aggregator APIs β€” Access Multiple Models via One Key

| Aggregator | URL | Models Available | Notes |
|------------|-----|-----------------|-------|
| **OpenRouter** | `openrouter.ai/api/v1` | Claude, GPT-4o, Gemini, Llama, Mistral, etc. | Single API key for 200+ models, pay-per-use |
| **Together AI** | `api.together.xyz` | Llama 3.1, Mixtral, Qwen, CodeLlama | Great for open-source models, fast inference |
| **Fireworks AI** | `api.fireworks.ai` | Llama, Mixtral, custom fine-tunes | Fastest open-source inference |
| **Eden AI** | `api.edenai.run` | GPT, Claude, Gemini, Cohere, etc. | True multi-provider aggregator |
| **Groq** | `api.groq.com` | Llama 3.1 70B/8B, Mixtral | Extremely fast (custom LPU hardware) |

### Tier 3: Local/Private Models β€” No Data Leaves Your Machine

| Tool | Model | Notes |
|------|-------|-------|
| **Ollama** | `llama3.1:8b`, `mistral:7b`, `phi-3:mini` | Run locally, zero cost, full privacy |
| **LM Studio** | Any GGUF model | GUI + local API server at `localhost:1234` |
| **Jan.ai** | Various | Desktop app with built-in model management |
| **llama.cpp** | Any GGUF | CLI-based, most lightweight option |
| **vLLM** | Llama, Mistral, etc. | Self-hosted, production-grade serving |

### Recommended Setup

```
Production:  Claude Haiku 4.5 via Anthropic API (best cost/accuracy for structured extraction)
Development: Ollama + llama3.1:8b (free, private, no API key needed)
Fallback:    OpenRouter (auto-failover to cheapest available model)
```

---

## 8. City/Branch Routing Configuration

The `recipient_email` extracted by the AI determines which ICC branch the transaction belongs to.

```typescript
// packages/shared/src/constants/branches.ts
export const BRANCH_MAPPING: Record<string, string> = {
  "finances@iccameriques.org": "ICC MontrΓ©al",
  "montreal.finances@iccameriques.org": "ICC MontrΓ©al",
  "quebec.finances@iccameriques.org": "ICC QuΓ©bec",
  "troisrivieres.finances@iccameriques.org": "ICC Trois-Rivières",
  "trois-rivieres.finances@iccameriques.org": "ICC Trois-Rivières",
  "sherbrooke.finances@iccameriques.org": "ICC Sherbrooke",
  "gatineau.finances@iccameriques.org": "ICC Gatineau",
  "ottawa.finances@iccameriques.org": "ICC Ottawa",
  "gatineauottawa.finances@iccameriques.org": "ICC Gatineau-Ottawa",
  "toronto.finances@iccameriques.org": "ICC Toronto",
  "hamilton.finances@iccameriques.org": "ICC Hamilton",
  "london.finances@iccameriques.org": "ICC London",
  "windsor.finances@iccameriques.org": "ICC Windsor",
  "sudbury.finances@iccameriques.org": "ICC Sudbury",
  "timmins.finances@iccameriques.org": "ICC Timmins",
  "winnipeg.finances@iccameriques.org": "ICC Winnipeg",
  "regina.finances@iccameriques.org": "ICC Regina",
  "saskatoon.finances@iccameriques.org": "ICC Saskatoon",
  "calgary.finances@iccameriques.org": "ICC Calgary",
  "edmonton.finances@iccameriques.org": "ICC Edmonton",
  "vancouver.finances@iccameriques.org": "ICC Vancouver",
  "victoria.finances@iccameriques.org": "ICC Victoria",
  "halifax.finances@iccameriques.org": "ICC Halifax",
  "moncton.finances@iccameriques.org": "ICC Moncton",
  "charlottetown.finances@iccameriques.org": "ICC Charlottetown",
  "stjohns.finances@iccameriques.org": "ICC St. John's",
  "lvl.finances@iccameriques.org": "ICC Laval",
  "lgl.finances@iccameriques.org": "ICC Longueuil",
  "victoriaville.finances@iccameriques.org": "ICC Victoriaville",
  "valleyfield.finances@iccameriques.org": "ICC Valleyfield",
  "finances.rdl@iccameriques.org": "ICC Rivière-du-Loup",
  "rimouski.finances@iccameriques.org": "ICC Rimouski",
  "septiles.finances@iccameriques.org": "ICC Sept-Îles",
  "saguenay.finances@iccameriques.org": "ICC Saguenay",
  "chibougamau.finances@iccameriques.org": "ICC Chibougamau",
  "valdor.finances@iccameriques.org": "ICC Val-d'Or",
  "rouyn.finances@iccameriques.org": "ICC Rouyn-Noranda",
  "kingston.finances@iccameriques.org": "ICC Kingston",
  "shawinigan.finances@iccameriques.org": "ICC Shawinigan",
  "drummondville.finances@iccameriques.org": "ICC Drummondville",
  "granby.finances@iccameriques.org": "ICC Granby",
  "sthyacinthe.finances@iccameriques.org": "ICC St-Hyacinthe",
  "stjerome.finances@iccameriques.org": "ICC St-JΓ©rΓ΄me",
  "joliette.finances@iccameriques.org": "ICC Joliette",
  "terrebonne.finances@iccameriques.org": "ICC Terrebonne",
  "repentigny.finances@iccameriques.org": "ICC Repentigny",
  "siege@iccameriques.org": "ICC Siège",
  "mission.finances@iccameriques.org": "ICC Mission",
};

export function resolveBranch(recipientEmail: string): string {
  return BRANCH_MAPPING[recipientEmail.toLowerCase()] ?? "Non classifiΓ©";
}
```

The mapping is also stored in the `branch_config` database table and is editable from the Settings page.

---

## 9. Live Dashboard β€” Table UI

### Table Columns

| Column | Field | Type | Notes |
|--------|-------|------|-------|
| Date | `date` | DateTime | Format: `YYYY-MM-DD HH:mm` |
| ExpΓ©diteur | `sender` | String | Full name of sender |
| Montant | `amount` | Currency | Format: `1 500,00 $` or `$1,500.00` |
| RΓ©fΓ©rence | `reference` | String | Interac reference number |
| Succursale/Ville | `branch` | String | Resolved from city routing map |
| Statut | `status` | Badge | Color-coded status indicator |

### Status Badge Mapping

```typescript
export const STATUS_MAP = {
  deposited:  { label: "DΓ©posΓ©",     color: "bg-emerald-100 text-emerald-800", icon: "CheckCircle" },
  pending:    { label: "En attente", color: "bg-amber-100 text-amber-800",     icon: "Clock"       },
  expired:    { label: "ExpirΓ©",     color: "bg-red-100 text-red-800",         icon: "XCircle"     },
  cancelled:  { label: "AnnulΓ©",     color: "bg-gray-100 text-gray-600",       icon: "Ban"         },
} as const;
```

### Dashboard Features

- **Real-time updates**: WebSocket push from server when new scans complete; auto-refresh fallback every 5 min
- **Filters**: By branch/city (multi-select dropdown), date range picker, status checkboxes, amount range slider
- **Search**: Full-text search across sender, reference, message (debounced, 300ms)
- **Sort**: Clickable column headers with ascending/descending/none cycle
- **Pagination**: 25/50/100 rows per page with TanStack Table
- **Summary bar**: Total transactions count, total $ amount, breakdown by branch (mini bar chart)
- **Row expansion**: Click row to reveal full details β€” message/dime, raw email snippet, recipient email
- **Bulk actions**: Checkbox select β†’ Export PDF, Export CSV, Mark as reviewed
- **Scan controls**: Three quick-scan buttons β€” "Aujourd'hui" (today), "7 derniers jours" (last 7 days), "PΓ©riode personnalisΓ©e" (custom date range with dual date pickers). Progress bar with batch count during active scan.
- **Scan history**: View past scans with their date ranges, results count, and duration
- **Branch tabs**: Quick filter tabs at the top for the most active branches

### Key React Components

```typescript
// TransactionTable.tsx β€” powered by TanStack Table v8
// Uses server-side pagination for performance (API: GET /api/transactions?page=1&limit=25&branch=...)
// Columns are fully configurable and resizable
// Supports column visibility toggle

// SummaryBar.tsx β€” displays at the top of dashboard
// Shows: total count | total amount | deposited vs pending pie chart | top 5 branches

// FilterPanel.tsx β€” collapsible sidebar or top bar
// Branch multi-select, date range (react-day-picker), status checkboxes, amount min/max

// ScanProgress.tsx β€” shown during active scan
// WebSocket-powered: "Scanning... 47/120 emails processed"
// Shows: progress bar, date range being scanned, current email being parsed
// Example: "PΓ©riode: 10 janv. 2024 β†’ 12 mars 2025 | 47/120 courriels traitΓ©s"
```

---

## 10. PDF Receipt Generation

Each transaction is exportable as a branded PDF receipt:

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
│         ICC AMÉRIQUES                  │
β”‚     ReΓ§u de virement Interac           β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Date:          2025-02-15 14:30        β”‚
β”‚ ExpΓ©diteur:    John Doe                β”‚
β”‚ Montant:       1 500,00 $ CAD          β”‚
β”‚ RΓ©fΓ©rence:     CA1b2c3d4e5f            β”‚
β”‚ Message:       Dime pour mars 2025     β”‚
β”‚ Succursale:    ICC MontrΓ©al            β”‚
β”‚ Statut:        DΓ©posΓ© βœ“               β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ ReΓ§u gΓ©nΓ©rΓ© automatiquement par        β”‚
β”‚ ICC Interac Manager                    β”‚
β”‚ Date de gΓ©nΓ©ration: 2025-02-20         β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

**Implementation:**
- Client-side: `@react-pdf/renderer` for instant preview + download in browser
- Server-side: `PDFKit` for batch generation (POST /api/receipts/batch with array of transaction IDs)
- Both produce identical output using shared template constants

---

## 11. Database Schema

### PostgreSQL (Web / Production)

```sql
-- Users table (linked to Google accounts)
CREATE TABLE users (
  id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  google_id       TEXT UNIQUE NOT NULL,
  email           TEXT UNIQUE NOT NULL,
  name            TEXT,
  avatar_url      TEXT,
  access_token    TEXT,           -- encrypted Google OAuth token
  refresh_token   TEXT,           -- encrypted
  token_expires   TIMESTAMPTZ,
  role            TEXT DEFAULT 'viewer' CHECK(role IN ('admin','editor','viewer')),
  created_at      TIMESTAMPTZ DEFAULT NOW(),
  updated_at      TIMESTAMPTZ DEFAULT NOW()
);

-- Transactions table
CREATE TABLE transactions (
  id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  email_id        TEXT UNIQUE NOT NULL,        -- Gmail message ID or IMAP UID
  user_id         UUID REFERENCES users(id),   -- who scanned this
  date            TIMESTAMPTZ NOT NULL,
  sender          TEXT NOT NULL,
  amount          NUMERIC(12,2) NOT NULL,
  currency        TEXT DEFAULT 'CAD',
  reference       TEXT,
  message         TEXT,                        -- dime/memo
  recipient_email TEXT,
  branch          TEXT,                        -- resolved branch name
  status          TEXT CHECK(status IN ('deposited','pending','expired','cancelled')),
  raw_email       TEXT,                        -- original email body for audit
  parsed_at       TIMESTAMPTZ DEFAULT NOW(),
  reviewed        BOOLEAN DEFAULT FALSE,
  reviewed_by     UUID REFERENCES users(id),
  created_at      TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX idx_tx_date ON transactions(date DESC);
CREATE INDEX idx_tx_branch ON transactions(branch);
CREATE INDEX idx_tx_status ON transactions(status);
CREATE INDEX idx_tx_user ON transactions(user_id);
CREATE INDEX idx_tx_sender ON transactions(sender);

-- Branch configuration (editable from Settings)
CREATE TABLE branch_config (
  id      SERIAL PRIMARY KEY,
  email   TEXT UNIQUE NOT NULL,
  branch  TEXT NOT NULL,
  active  BOOLEAN DEFAULT TRUE,
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Scan logs (audit trail)
CREATE TABLE scan_logs (
  id              SERIAL PRIMARY KEY,
  user_id         UUID REFERENCES users(id),
  scan_preset     TEXT CHECK(scan_preset IN ('today','last7days','custom')),
  scan_start_date TIMESTAMPTZ NOT NULL,    -- start of scanned date range
  scan_end_date   TIMESTAMPTZ NOT NULL,    -- end of scanned date range
  force_rescan    BOOLEAN DEFAULT FALSE,
  started_at      TIMESTAMPTZ NOT NULL,
  finished_at     TIMESTAMPTZ,
  emails_found    INTEGER DEFAULT 0,
  emails_parsed   INTEGER DEFAULT 0,
  emails_skipped  INTEGER DEFAULT 0,      -- already in DB (deduplication)
  errors          INTEGER DEFAULT 0,
  error_details   JSONB,
  ai_provider     TEXT,                    -- which AI was used
  ai_model        TEXT,
  created_at      TIMESTAMPTZ DEFAULT NOW()
);

-- AI provider settings (per-user or global)
CREATE TABLE ai_settings (
  id          SERIAL PRIMARY KEY,
  user_id     UUID REFERENCES users(id),   -- NULL = global default
  provider    TEXT NOT NULL,                -- 'anthropic', 'openai', 'ollama', etc.
  model       TEXT NOT NULL,                -- 'claude-haiku-4-5-20251001', etc.
  api_key     TEXT,                         -- encrypted, NULL for Ollama
  base_url    TEXT,                         -- custom endpoint if needed
  is_active   BOOLEAN DEFAULT TRUE,
  created_at  TIMESTAMPTZ DEFAULT NOW()
);
```

---

## 12. API Endpoints (Backend)

### Authentication
```
GET  /api/auth/google           β†’ Redirect to Google OAuth
GET  /api/auth/google/callback  β†’ Handle OAuth callback, issue JWT
POST /api/auth/refresh          β†’ Refresh expired JWT
POST /api/auth/logout           β†’ Invalidate session
GET  /api/auth/me               β†’ Get current user info
```

### Email Scanning
```
POST /api/scan/start            β†’ Trigger email scan
  Body: {
    preset: "today" | "last7days" | "custom",
    startDate?: "2024-01-10",       // required if preset=custom (YYYY-MM-DD)
    endDate?: "2025-03-12",         // required if preset=custom (YYYY-MM-DD)
    forceRescan?: false             // re-process emails already in DB
  }
  Returns: { jobId, dateRange, estimatedEmails }

GET  /api/scan/status/:jobId    β†’ Get scan progress (or use WebSocket)
  Returns: {
    jobId, status, dateRange,
    progress: { found, processed, skipped, errored, currentEmail }
  }

GET  /api/scan/history          β†’ List past scan logs with date ranges used
  Returns: [{ id, dateRange, emailsFound, emailsParsed, startedAt, duration }]
```

### Transactions
```
GET    /api/transactions         β†’ List with filters (?branch=&status=&from=&to=&page=&limit=&search=)
GET    /api/transactions/:id     β†’ Single transaction detail
PATCH  /api/transactions/:id     β†’ Update (mark reviewed, edit branch)
DELETE /api/transactions/:id     β†’ Soft delete
GET    /api/transactions/stats   β†’ Summary statistics (totals by branch, status, month)
```

### Receipts & Export
```
GET  /api/receipts/:id/pdf      β†’ Generate single PDF receipt
POST /api/receipts/batch        β†’ Generate batch PDF (body: { ids: [...] })
GET  /api/export/csv             β†’ Export filtered results as CSV
GET  /api/export/xlsx            β†’ Export filtered results as Excel
```

### Settings
```
GET    /api/settings/branches      β†’ List branch mappings
POST   /api/settings/branches      β†’ Add new branch mapping
PUT    /api/settings/branches/:id  β†’ Update branch mapping
DELETE /api/settings/branches/:id  β†’ Delete branch mapping
GET    /api/settings/ai            β†’ Get AI provider config
PUT    /api/settings/ai            β†’ Update AI provider/model/key
```

### WebSocket Events
```
ws://localhost:3001/ws

Server β†’ Client events:
  scan:started      { jobId, timestamp, dateRange, totalEmails, newEmails, skipped }
  scan:progress     { jobId, processed, total, skipped, errored, latest: InteracTransaction }
  scan:completed    { jobId, summary: { found, parsed, skipped, errors }, dateRange }
  scan:error        { jobId, message, dateRange }
  transaction:new   { transaction: InteracTransaction }   // real-time insert
```

---

## 13. Application Flow

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  User Login  │────▢│  Select Date │────▢│  Gmail API   │────▢│  AI Parse    β”‚
β”‚  Google OAuthβ”‚     β”‚  Range:      β”‚     β”‚  Fetch emailsβ”‚     β”‚  Each Email  β”‚
β”‚  (Vite SPA)  β”‚     β”‚  β€’ Today     β”‚     β”‚  from:notify β”‚     β”‚  β†’ JSON      β”‚
β”‚              β”‚     β”‚  β€’ 7 days    β”‚     β”‚  @payments.  β”‚     β”‚              β”‚
β”‚              β”‚     β”‚  β€’ Custom    β”‚     β”‚  interac.ca  β”‚     β”‚              β”‚
β”‚              β”‚     β”‚  ────────    β”‚     β”‚  after:/     β”‚     β”‚              β”‚
β”‚              β”‚     β”‚  POST /api/  β”‚     β”‚  before:     β”‚     β”‚              β”‚
β”‚              β”‚     β”‚  scan/start  β”‚     β”‚  date filter β”‚     β”‚              β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜
                            β”‚                                          β”‚
                            β”‚ WebSocket: scan:progress                 β”‚
                            β–Ό                                          β–Ό
                     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                     β”‚  Vite React  │◀─────────────────────────│ Route to     β”‚
                     β”‚  Dashboard   β”‚   transaction:new event  β”‚ Branch by    β”‚
                     β”‚  (Live Table)β”‚                          β”‚ recipient    β”‚
                     β”‚              β”‚                          β”‚ email        β”‚
                     β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜                          β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                            β”‚
                   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”
                   β–Ό        β–Ό        β–Ό
            β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
            β”‚Export CSV β”‚ β”‚ PDF  β”‚ β”‚ Reports  β”‚
            β”‚/ Excel   β”‚ β”‚ReΓ§us β”‚ β”‚& Charts  β”‚
            β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

---

## 14. Deployment β€” Web Version

### Option A: Vercel + Railway (Recommended)

```
Frontend (Vite):     Vercel (free tier works for starters)
Backend (Express):   Railway or Render
Database:            Neon (serverless PostgreSQL) or Supabase
Redis:               Upstash (serverless Redis for job queues)
```

### Option B: VPS / Self-hosted

```
Server:              Ubuntu 24.04 VPS (DigitalOcean, Hetzner, OVH)
Process Manager:     PM2 (Node.js backend)
Reverse Proxy:       Nginx or Caddy (auto-HTTPS)
Database:            PostgreSQL 16 (same server or managed)
Frontend:            Vite build β†’ served as static files by Nginx
CI/CD:               GitHub Actions β†’ SSH deploy or Docker
```

### Option C: Docker Compose (Full Stack)

```yaml
# docker-compose.yml
version: '3.9'
services:
  frontend:
    build:
      context: ./packages/web
      dockerfile: Dockerfile
    ports:
      - "5173:80"
    depends_on:
      - backend

  backend:
    build:
      context: ./packages/server
      dockerfile: Dockerfile
    ports:
      - "3001:3001"
    environment:
      - DATABASE_URL=postgresql://icc:password@postgres:5432/icc_interac
      - REDIS_URL=redis://redis:6379
    depends_on:
      - postgres
      - redis

  postgres:
    image: postgres:16-alpine
    environment:
      POSTGRES_DB: icc_interac
      POSTGRES_USER: icc
      POSTGRES_PASSWORD: password
    volumes:
      - pgdata:/var/lib/postgresql/data
    ports:
      - "5432:5432"

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"

volumes:
  pgdata:
```

### Dockerfile for Vite Frontend

```dockerfile
# packages/web/Dockerfile
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
```

---

## 15. Security Requirements

- **Never store Gmail passwords** β€” OAuth tokens only, encrypted at rest (AES-256)
- **Encrypt all API keys** β€” Use environment variables, never commit to git
- **JWT sessions** β€” Short-lived access tokens (15 min) + refresh tokens (7 days)
- **HTTPS only** β€” Enforce in production (Caddy auto-TLS or Cloudflare)
- **Rate limiting** β€” API rate limits (express-rate-limit) + respect Gmail API quota
- **CORS** β€” Restrict to known frontend origins only
- **Input validation** β€” Zod schemas on every API endpoint
- **SQL injection prevention** β€” Parameterized queries via ORM (Drizzle/Prisma)
- **Role-based access** β€” Admin can manage settings, Viewer can only see dashboard
- **Audit log** β€” Log every scan operation with user, timestamp, results
- **Content Security Policy** β€” Strict CSP headers in production

---

## 16. Sample Interac Email Structure (for AI testing)

```
From: notify@payments.interac.ca
To: montreal.finances@iccameriques.org
Subject: INTERAC e-Transfer: John Doe vous a envoyΓ© de l'argent

Bonjour,

John Doe vous a envoyΓ© un virement INTERAC de 150,00 $ (CAD).

Le virement a Γ©tΓ© automatiquement dΓ©posΓ© dans votre compte.

RΓ©fΓ©rence: CA1b2c3d4e5f
Message de l'expΓ©diteur: Dime pour mars 2025

Merci d'utiliser le Virement INTERAC.
```

---

## 17. Internationalization Notes

- The app UI should be in **French** by default (matching the ICC operational language)
- Use `react-i18next` for translations (French primary, English secondary)
- Status labels: DΓ©posΓ©, En attente, ExpirΓ©, AnnulΓ©
- Currency format: `1 500,00 $` (French-Canadian format using `Intl.NumberFormat('fr-CA', { style: 'currency', currency: 'CAD' })`)
- Date format: `YYYY-MM-DD` (ISO) by default β€” use `date-fns` with `fr-CA` locale
- All form labels, buttons, error messages, and toasts in French

---

## 18. Implementation Checklist

### Phase 1: Project Scaffolding & Auth
- [ ] Initialize monorepo (pnpm workspaces or npm workspaces)
- [ ] Scaffold Vite + React + TypeScript frontend (`npm create vite@latest`)
- [ ] Set up Tailwind CSS 4 + shadcn/ui component library
- [ ] Scaffold Express.js backend with TypeScript
- [ ] Set up PostgreSQL + Drizzle ORM with migrations
- [ ] Implement Google OAuth 2.0 flow (frontend redirect + backend callback + JWT)
- [ ] Build login page with "Se connecter avec Google" button
- [ ] Implement protected routes and auth middleware
- [ ] Set up shared package with types and constants

### Phase 2: Email Scanning Engine
- [ ] Implement Gmail API service (search + fetch full MIME body)
- [ ] Implement IMAP fallback service
- [ ] Build scan date range system with 3 presets: today, last 7 days, custom
- [ ] Implement `resolveScanDates()` helper (shared package)
- [ ] Implement `buildGmailQuery()` with `after:` / `before:` date operators
- [ ] Implement `buildIMAPSearch()` with `SINCE` / `BEFORE` date filters
- [ ] Build ScanControls UI component (ToggleGroup + DatePicker for custom range)
- [ ] Add date validation (start < end, end not in future)
- [ ] Build scan job system (BullMQ or simple async queue)
- [ ] Implement batched processing for large date ranges (50 emails per batch)
- [ ] Add rate limiting between Gmail API calls (respect quota)
- [ ] Add deduplication (check email_id before processing)
- [ ] Add `forceRescan` option to re-process existing emails
- [ ] Implement WebSocket for real-time scan progress with date range context
- [ ] Build progress bar UI showing batch count + current email + date range
- [ ] Add quick-scan buttons in dashboard header ("Aujourd'hui" / "7 jours")
- [ ] Build scan history page showing past scans with date ranges and results

### Phase 3: AI Integration
- [ ] Create unified `AIProvider` interface + factory
- [ ] Implement Anthropic Claude adapter
- [ ] Implement OpenAI GPT adapter
- [ ] Implement Google Gemini adapter
- [ ] Implement OpenRouter adapter
- [ ] Implement Ollama (local) adapter
- [ ] Build extraction prompt + Zod JSON validation layer
- [ ] Add retry logic with exponential backoff
- [ ] Build Settings page for AI provider/model selection

### Phase 4: Branch Routing & Business Logic
- [ ] Implement branch routing with shared BRANCH_MAPPING
- [ ] Seed database with all 48 branch email mappings
- [ ] Build Settings page for managing branch mappings (CRUD)
- [ ] Handle "Non classifiΓ©" fallback routing

### Phase 5: Dashboard UI
- [ ] Build main TransactionTable with TanStack Table v8
- [ ] Implement all columns: Date, ExpΓ©diteur, Montant, RΓ©fΓ©rence, Succursale, Statut
- [ ] Add status badges with color coding
- [ ] Build FilterPanel (branch multi-select, date range, status, amount)
- [ ] Add full-text search with debounce
- [ ] Add sortable column headers
- [ ] Add pagination (25/50/100 per page)
- [ ] Build SummaryBar with statistics
- [ ] Implement row expansion for full transaction details
- [ ] Add bulk selection + actions (export, mark reviewed)
- [ ] Connect WebSocket for live "transaction:new" updates
- [ ] Build branch quick-filter tabs

### Phase 6: Receipts & Export
- [ ] Implement PDF receipt template with @react-pdf/renderer
- [ ] Build server-side PDF generation with PDFKit
- [ ] Add single receipt download from row action menu
- [ ] Implement batch PDF export endpoint
- [ ] Implement CSV export
- [ ] Implement Excel (xlsx) export via SheetJS

### Phase 7: Reports Page
- [ ] Monthly summary by branch (bar chart)
- [ ] Trend line: total amount over time (line chart)
- [ ] Status distribution pie chart
- [ ] Top senders table
- [ ] Date range selector for custom report periods

### Phase 8: Polish & Deploy
- [ ] Error handling and user-friendly error messages (French)
- [ ] Loading skeletons and progress bars
- [ ] Responsive design (mobile-friendly dashboard)
- [ ] Dark mode support (Tailwind dark: prefix)
- [ ] Docker Compose for local development
- [ ] Production deployment (Vercel + Railway or Docker on VPS)
- [ ] CI/CD pipeline (GitHub Actions: lint β†’ test β†’ build β†’ deploy)
- [ ] Write user documentation (French)
- [ ] Set up monitoring (Sentry for errors, Uptime Robot for availability)

### Phase 9: Desktop Wrapper (Optional)
- [ ] Wrap Vite build in Electron
- [ ] Add native file save dialogs for PDF/CSV export
- [ ] Add system tray with scan notifications
- [ ] Build installers (Windows .exe, macOS .dmg)

---

*This prompt contains everything needed to build the ICC Interac Manager as a Vite.js web application with Express backend. Feed it to Claude, GPT-4, or any capable coding assistant along with the specific phase you want to implement.*