Repository navigation
Expand file tree
/
Copy pathindex.inline.js
More file actions
7594 lines (7209 loc) · 485 KB
/
Copy pathindex.inline.js
File metadata and controls
7594 lines (7209 loc) · 485 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
// ═══════════════════════════════════════════════════════════════
// TFSA & FHSA Tracker — Unified Engine (v12)
// Compliance, hardening, explainability, and safer import/export
// ═══════════════════════════════════════════════════════════════
// ─── CRA Official TFSA Annual Limits (2009–2035) ───
const OFFICIAL_TFSA_LIMITS = {
2009:5000,2010:5000,2011:5000,2012:5000,2013:5500,2014:5500,
2015:10000,2016:5500,2017:5500,2018:5500,2019:6000,2020:6000,
2021:6000,2022:6000,2023:6500,2024:7000,2025:7000,2026:7000
};
const CONFIG_DEFAULTS = {
tfsaEligibleStartYear: 2015,
currentYear: 2026,
fhsaFirstYear: 2023,
fhsaAnnualLimit: 8000,
fhsaLifetimeLimit: 40000,
fhsaCarryforwardCap: 8000,
fhsaBirthDate: '',
tfsaAnnualLimits: Object.assign({}, OFFICIAL_TFSA_LIMITS, {2027:0,2028:0,2029:0,2030:0,2031:0,2032:0,2033:0,2034:0,2035:0})
};
const UI_DEFAULTS = {
TFSA: {inst:'Wealthsimple',acct:'manual',type:'Contribution',treat:'Include'},
FHSA: {inst:'Wealthsimple',acct:'DEMO-FHSA-CAD-001',type:'Contribution',status:'Include'},
importDefaults: {sourceKind:'auto',plan:'AUTO',signMode:'positive_inflow',dateFormat:'AUTO',institution:'',account:'',mergeMode:'skip'},
craSnapshots: {tfsa:null,fhsa:null},
lastImportSummary: null,
importHistory: [],
postImportNotice: null,
activityLog: [],
demoSeedActive: false
};
// ─── RRSP Seeded Data ───
const DEFAULT_RRSP_META = {province:'Ontario',hasHbpHistory:false,hasLlpHistory:false,hasSpousalRrsp:false,hasGroupRrsp:false,hasOvercontributionHistory:false,moduleVersion:'rrsp-v1.2',seedState:'seeded',notes:'',rrspInitialized:false};
const INIT_RRSP={"meta":{"province":"Ontario","hasHbpHistory":false,"hasLlpHistory":false,"hasSpousalRrsp":false,"hasGroupRrsp":false,"hasOvercontributionHistory":false,"notes":"Synthetic RRSP demo dataset with carryforward, first-60-days usage, and a room-neutral transfer."},"annual":[{"taxYear":2022,"availableContributionRoom":28000.0,"deductionLimit":28000.0,"regularPeriodContributions":4500.0,"first60DaysContributions":0.0,"totalContributionsForReturn":4500.0,"deductionClaimed":4500.0,"unusedContributionsCarryforwardStart":0.0,"unusedContributionsCarryforwardEnd":0.0,"unusedDeductionRoomEnd":23500.0,"actualRefundOrBalance":1800.0,"actualTotalIncome":72000.0,"actualTaxableIncome":67500.0,"actualTotalPayable":14000.0,"sourceQuality":"Demo seed","notes":"All contributions deducted."},{"taxYear":2023,"availableContributionRoom":36000.0,"deductionLimit":36000.0,"regularPeriodContributions":6000.0,"first60DaysContributions":3000.0,"totalContributionsForReturn":9000.0,"deductionClaimed":7000.0,"unusedContributionsCarryforwardStart":0.0,"unusedContributionsCarryforwardEnd":2000.0,"unusedDeductionRoomEnd":29000.0,"actualRefundOrBalance":2400.0,"actualTotalIncome":88000.0,"actualTaxableIncome":81000.0,"actualTotalPayable":16500.0,"sourceQuality":"Demo seed","notes":"Intentional carryforward example."},{"taxYear":2024,"availableContributionRoom":46500.0,"deductionLimit":46500.0,"regularPeriodContributions":5200.0,"first60DaysContributions":4800.0,"totalContributionsForReturn":10000.0,"deductionClaimed":11000.0,"unusedContributionsCarryforwardStart":2000.0,"unusedContributionsCarryforwardEnd":1000.0,"unusedDeductionRoomEnd":35500.0,"actualRefundOrBalance":3100.0,"actualTotalIncome":97000.0,"actualTaxableIncome":86000.0,"actualTotalPayable":19000.0,"sourceQuality":"Demo seed","notes":"Carryforward partially used and a room-neutral transfer occurs this year."},{"taxYear":2025,"availableContributionRoom":59000.0,"deductionLimit":59000.0,"regularPeriodContributions":4200.0,"first60DaysContributions":6800.0,"totalContributionsForReturn":11000.0,"deductionClaimed":10500.0,"unusedContributionsCarryforwardStart":1000.0,"unusedContributionsCarryforwardEnd":1500.0,"unusedDeductionRoomEnd":48500.0,"actualRefundOrBalance":4200.0,"actualTotalIncome":108000.0,"actualTaxableIncome":97500.0,"actualTotalPayable":22000.0,"sourceQuality":"Demo seed","notes":"Mixed regular-year and first-60-days contributions with a small carryforward retained."},{"taxYear":2026,"availableContributionRoom":68000.0,"deductionLimit":68000.0,"regularPeriodContributions":0.0,"first60DaysContributions":0.0,"totalContributionsForReturn":0.0,"deductionClaimed":0.0,"unusedContributionsCarryforwardStart":1500.0,"unusedContributionsCarryforwardEnd":1500.0,"unusedDeductionRoomEnd":68000.0,"actualRefundOrBalance":0.0,"actualTotalIncome":0.0,"actualTaxableIncome":0.0,"actualTotalPayable":0.0,"sourceQuality":"Demo seed","notes":"Current opening RRSP room for planning scenarios."}],"receipts":[{"taxYear":2023,"institution":"NorthHarbour","accountId":"RRSP-8231","regularPeriodAmount":6000.0,"first60DaysAmount":3000.0,"sourceRef":"Demo RRSP receipt","notes":"Synthetic example with first-60-days usage."},{"taxYear":2024,"institution":"MapleInvest","accountId":"RRSP-2044","regularPeriodAmount":5200.0,"first60DaysAmount":4800.0,"sourceRef":"Demo RRSP receipt","notes":"Synthetic example with a separate institutional transfer in the same year."},{"taxYear":2025,"institution":"NorthHarbour","accountId":"RRSP-8231","regularPeriodAmount":4200.0,"first60DaysAmount":2800.0,"sourceRef":"Demo RRSP receipt","notes":"Synthetic example."},{"taxYear":2025,"institution":"PrairieDirect","accountId":"RRSP-5518","regularPeriodAmount":0.0,"first60DaysAmount":4000.0,"sourceRef":"Demo RRSP receipt","notes":"Synthetic example."}],"txns":[{"d":"2023-11-30","inst":"NorthHarbour","acct":"RRSP-8231","type":"Contribution","amt":6000.0,"taxYearTarget":2023,"window":"regular_year","roomEffect":"consumes_room","sourceType":"receipt","note":"Synthetic regular-year contribution."},{"d":"2024-02-20","inst":"NorthHarbour","acct":"RRSP-8231","type":"First 60 Contribution","amt":3000.0,"taxYearTarget":2023,"window":"first_60_days","roomEffect":"consumes_room","sourceType":"receipt","note":"Synthetic first-60-days contribution."},{"d":"2024-06-18","inst":"NorthHarbour","acct":"RRSP-8231","type":"Institutional Transfer In","amt":7500.0,"taxYearTarget":2024,"window":"not_applicable","roomEffect":"room_neutral","sourceType":"activity","note":"Synthetic room-neutral RRSP transfer from another institution."},{"d":"2024-10-10","inst":"MapleInvest","acct":"RRSP-2044","type":"Contribution","amt":5200.0,"taxYearTarget":2024,"window":"regular_year","roomEffect":"consumes_room","sourceType":"receipt","note":"Synthetic regular-year contribution."},{"d":"2025-02-25","inst":"MapleInvest","acct":"RRSP-2044","type":"First 60 Contribution","amt":4800.0,"taxYearTarget":2024,"window":"first_60_days","roomEffect":"consumes_room","sourceType":"receipt","note":"Synthetic first-60-days contribution."},{"d":"2025-07-12","inst":"NorthHarbour","acct":"RRSP-8231","type":"Contribution","amt":4200.0,"taxYearTarget":2025,"window":"regular_year","roomEffect":"consumes_room","sourceType":"receipt","note":"Synthetic regular-year contribution."},{"d":"2026-02-20","inst":"NorthHarbour","acct":"RRSP-8231","type":"First 60 Contribution","amt":2800.0,"taxYearTarget":2025,"window":"first_60_days","roomEffect":"consumes_room","sourceType":"receipt","note":"Synthetic first-60-days contribution."},{"d":"2026-03-01","inst":"PrairieDirect","acct":"RRSP-5518","type":"First 60 Contribution","amt":4000.0,"taxYearTarget":2025,"window":"first_60_days","roomEffect":"consumes_room","sourceType":"receipt","note":"Synthetic first-60-days contribution."}]};
function cloneRrspSeed(){return clone(INIT_RRSP)}
function rrspStateHasData(state){
return !!(state && ((Array.isArray(state.txns)&&state.txns.length) || (Array.isArray(state.annual)&&state.annual.length) || (Array.isArray(state.receipts)&&state.receipts.length)));
}
function makeEmptyRrspState(meta,intentionalEmpty=false){const merged=Object.assign(clone(DEFAULT_RRSP_META),meta||{}); if(intentionalEmpty){ merged.seedState='empty-by-user'; merged.userEmptyExplicitVersion=RRSP_EMPTY_EXPLICIT_VERSION; merged.userEmptyExplicitAt=Date.now(); merged.rrspInitialized=true; } else { delete merged.userEmptyExplicitVersion; delete merged.userEmptyExplicitAt; if(!Object.prototype.hasOwnProperty.call(merged,'rrspInitialized')) merged.rrspInitialized=false; } return {txns:[],annual:[],receipts:[],meta:merged,intentionalEmpty:!!intentionalEmpty}}
function normalizeRrspState(state,seeded){
const base=seeded?cloneRrspSeed():makeEmptyRrspState();
const src=state&&typeof state==='object'?state:{};
const rawMeta=(src&&src.meta&&typeof src.meta==='object')?src.meta:{};
const currentModuleVersion=String((DEFAULT_RRSP_META&&DEFAULT_RRSP_META.moduleVersion)||'');
const explicitUserEmpty=!!(rawMeta&&rawMeta.userEmptyExplicitVersion===RRSP_EMPTY_EXPLICIT_VERSION&&String(rawMeta.moduleVersion||'')===currentModuleVersion&&rawMeta.rrspInitialized===true);
const legacyUninitializedEmpty=!!(seeded && !rrspStateHasData(src) && rawMeta.rrspInitialized!==true);
const useSeedFallback=!!(seeded && !rrspStateHasData(src) && !explicitUserEmpty);
const meta=Object.assign(clone(DEFAULT_RRSP_META), base.meta||{}, src.meta||{});
if(explicitUserEmpty){
meta.seedState='empty-by-user';
meta.userEmptyExplicitVersion=RRSP_EMPTY_EXPLICIT_VERSION;
meta.rrspInitialized=true;
}else if(useSeedFallback){
meta.seedState='seeded';
meta.moduleVersion=currentModuleVersion;
meta.rrspInitialized=true;
delete meta.userEmptyExplicitVersion;
delete meta.userEmptyExplicitAt;
}else{
delete meta.userEmptyExplicitVersion;
delete meta.userEmptyExplicitAt;
if(meta.seedState==='empty-by-user')meta.seedState=seeded?'seeded':'empty';
meta.moduleVersion=currentModuleVersion||meta.moduleVersion;
if(legacyUninitializedEmpty) meta.rrspInitialized=true;
}
return {
txns:useSeedFallback?clone(base.txns):(Array.isArray(src.txns)?clone(src.txns):clone(base.txns)),
annual:useSeedFallback?clone(base.annual):(Array.isArray(src.annual)?clone(src.annual):clone(base.annual)),
receipts:useSeedFallback?clone(base.receipts):(Array.isArray(src.receipts)?clone(src.receipts):clone(base.receipts)),
meta,
intentionalEmpty:explicitUserEmpty && !useSeedFallback
};
}
function normalizeRrspType(value){
const s=String(value||'').trim().toLowerCase();
if(!s)return 'Contribution';
if(s==='contribution')return 'Contribution';
if(s==='first 60 contribution'||s==='first60 contribution'||s==='first 60 days contribution'||s==='first-60 contribution')return 'First 60 Contribution';
if(s==='institutional transfer in'||s==='transfer in')return 'Institutional Transfer In';
if(s==='institutional transfer out'||s==='transfer out')return 'Institutional Transfer Out';
if(s==='withdrawal')return 'Withdrawal';
if(s==='adjustment')return 'Adjustment';
return String(value||'Contribution').trim();
}
function rrspTypeMeta(type){
const t=normalizeRrspType(type);
if(t==='Contribution')return {pill:'pill-rrsp',amountClass:'green',label:'Contribution',fullLabel:t};
if(t==='First 60 Contribution')return {pill:'pill-rrsp',amountClass:'green',label:'First 60',fullLabel:t};
if(t==='Institutional Transfer In')return {pill:'pill-rrsp',amountClass:'blue',label:'Transfer In',fullLabel:t};
if(t==='Institutional Transfer Out')return {pill:'pill-rrsp',amountClass:'blue',label:'Transfer Out',fullLabel:t};
if(t==='Withdrawal')return {pill:'pill-rrsp',amountClass:'red',label:'Withdraw',fullLabel:t};
return {pill:'pill-rrsp',amountClass:'gold',label:t,fullLabel:t};
}
function getRrspWindowLabel(v){
if(v==='regular_year')return 'Regular year';
if(v==='first_60_days')return 'First 60 days';
if(v==='not_applicable')return 'N/A';
return String(v||'—');
}
function getRrspSourceLabel(t){
const sourceType=String((t&&t.sourceType)||'').trim();
if(sourceType==='rrsp_cra_doc')return 'CRA RRSP doc';
if(sourceType==='imported_csv')return 'Imported CSV';
if(sourceType==='manual')return 'Manual';
if(sourceType)return sourceType.replace(/_/g,' ');
if(String((t&&t.roomEffect)||'')==='room_neutral')return 'Transfer / manual';
return 'Manual';
}
function getRrspRoomEffectLabel(v){
if(v==='consumes_room')return 'Consumes room';
if(v==='room_neutral')return 'Room-neutral';
if(v==='asset_only')return 'Asset only';
return String(v||'—');
}
// ─── Initial Seeded Data ───
const INIT_T=[
["2022-01-14", "Maple Bank", "TFSA-DEMO-01", "C", 1800],
["2022-03-11", "Maple Bank", "TFSA-DEMO-01", "C", 950],
["2022-05-27", "Maple Bank", "TFSA-DEMO-01", "C", 1250],
["2022-09-09", "Maple Bank", "TFSA-DEMO-01", "W", 600],
["2022-11-18", "Maple Bank", "TFSA-DEMO-01", "C", 700],
["2023-01-12", "Maple Bank", "TFSA-DEMO-01", "C", 2500],
["2023-02-24", "Maple Bank", "TFSA-DEMO-01", "C", 900],
["2023-04-07", "Maple Bank", "TFSA-DEMO-01", "C", 1200],
["2023-06-16", "Maple Bank", "TFSA-DEMO-01", "W", 350],
["2023-09-15", "Maple Bank", "TFSA-DEMO-01", "W", 400],
["2023-11-10", "Maple Bank", "TFSA-DEMO-01", "C", 650],
["2024-01-19", "Headroom Invest", "TFSA-DEMO-02", "C", 2200],
["2024-02-20", "Headroom Invest", "TFSA-DEMO-02", "C", 3000],
["2024-04-12", "Headroom Invest", "TFSA-DEMO-02", "C", 850],
["2024-05-10", "Headroom Invest", "TFSA-DEMO-02", "C", 1800],
["2024-07-26", "Headroom Invest", "TFSA-DEMO-02", "W", 500],
["2024-09-13", "Headroom Invest", "TFSA-DEMO-02", "C", 725],
["2024-11-01", "Headroom Invest", "TFSA-DEMO-02", "W", 950],
["2024-11-15", "Headroom Invest", "TFSA-DEMO-02", "C", 900],
["2024-12-06", "Headroom Invest", "TFSA-DEMO-02", "C", 400],
["2024-12-13", "Headroom Invest", "TFSA-DEMO-02", "C", 1200],
["2025-01-08", "Demo Brokerage", "TFSA-DEMO-03", "C", 4200],
["2025-02-14", "Demo Brokerage", "TFSA-DEMO-03", "C", 650],
["2025-03-21", "Demo Brokerage", "TFSA-DEMO-03", "C", 950],
["2025-05-30", "Demo Brokerage", "TFSA-DEMO-03", "W", 600],
["2025-07-11", "Demo Brokerage", "TFSA-DEMO-03", "C", 1100],
["2025-08-29", "Demo Brokerage", "TFSA-DEMO-03", "W", 1200],
["2025-10-17", "Demo Brokerage", "TFSA-DEMO-03", "C", 500],
["2025-12-05", "Demo Brokerage", "TFSA-DEMO-03", "C", 450],
["2026-01-10", "Summit Direct", "TFSA-DEMO-04", "C", 600],
["2026-02-14", "Summit Direct", "TFSA-DEMO-04", "C", 425],
["2026-03-07", "Summit Direct", "TFSA-DEMO-04", "C", 500],
["2026-04-18", "Summit Direct", "TFSA-DEMO-04", "W", 250],
["2026-05-22", "Summit Direct", "TFSA-DEMO-04", "C", 375],
["2026-07-10", "Summit Direct", "TFSA-DEMO-04", "C", 425],
["2026-09-04", "Summit Direct", "TFSA-DEMO-04", "W", 300]
];
const INIT_F=[
["2023-01-20", "Maple Bank", "FHSA-DEMO-01", 2000],
["2023-04-14", "Maple Bank", "FHSA-DEMO-01", 1500],
["2023-07-21", "Maple Bank", "FHSA-DEMO-01", 2250],
["2023-11-24", "Maple Bank", "FHSA-DEMO-01", 2250],
["2024-01-26", "Maple Bank", "FHSA-DEMO-01", 1000],
["2024-02-23", "Maple Bank", "FHSA-DEMO-01", 1000],
["2024-03-22", "Maple Bank", "FHSA-DEMO-01", 850],
["2024-04-19", "Maple Bank", "FHSA-DEMO-01", 900],
["2024-05-24", "Maple Bank", "FHSA-DEMO-01", 1100],
["2024-06-21", "Maple Bank", "FHSA-DEMO-01", 1200],
["2024-08-16", "Maple Bank", "FHSA-DEMO-01", 750],
["2024-09-20", "Maple Bank", "FHSA-DEMO-01", 800],
["2024-10-18", "Maple Bank", "FHSA-DEMO-01", 450],
["2024-11-22", "Maple Bank", "FHSA-DEMO-01", 400],
["2025-01-10", "Headroom Invest", "FHSA-DEMO-02", 1200],
["2025-03-14", "Headroom Invest", "FHSA-DEMO-02", 900],
["2025-05-09", "Headroom Invest", "FHSA-DEMO-02", 1000],
["2025-06-18", "Headroom Invest", "FHSA-DEMO-02", 850],
["2025-07-19", "Headroom Invest", "FHSA-DEMO-02", "FHSA Direct Transfer Out", 600],
["2025-07-19", "Headroom Invest", "FHSA-DEMO-USD", "FHSA Direct Transfer In", 600],
["2025-08-22", "Headroom Invest", "FHSA-DEMO-02", 700],
["2025-09-26", "Headroom Invest", "FHSA-DEMO-02", 600],
["2025-11-07", "Headroom Invest", "FHSA-DEMO-02", 500],
["2025-12-12", "Headroom Invest", "FHSA-DEMO-02", 450],
["2026-01-25", "Demo Brokerage", "FHSA-DEMO-03", 500],
["2026-03-12", "Demo Brokerage", "FHSA-DEMO-03", 450],
["2026-05-16", "Demo Brokerage", "FHSA-DEMO-03", 400],
["2026-07-18", "Demo Brokerage", "FHSA-DEMO-03", 350]
];
function expandT(arr){return arr.map((a,i)=>({id:'TFSA-SEED-'+String(i+1).padStart(5,'0'),seq:i+1,d:a[0],inst:a[1],acct:a[2],type:a[3]==='C'?'Contribution':a[3]==='W'?'Withdrawal':a[3],amt:a[4],treat:'Include',note:''}))}
function expandF(arr){
return arr.map((a,i)=>({
id:'FHSA-SEED-'+String(i+1).padStart(5,'0'),
seq:i+1,
d:a[0],
inst:a[1],
acct:a[2],
type:a.length>=5?normalizeFhsaType(a[3]):'Contribution',
status:'Include',
amt:a.length>=5?a[4]:a[3],
note:''
}))
}
// ─── State ───
let tT=[], fT=[], rT=[];
let rrspYears=[], rrspReceipts=[], rrspMeta=clone(DEFAULT_RRSP_META);
let trackerConfig = clone(CONFIG_DEFAULTS);
let uiPrefs = clone(UI_DEFAULTS);
let txnFilters = {TFSA:'all', FHSA:'all', RRSP:'all', tfsaPg:0, fhsaPg:0, rrspPg:0};
let txnSearch = {TFSA:'', FHSA:'', RRSP:''};
let txnAdvancedFilters = {TFSA:{from:'',to:'',min:'',max:''}, FHSA:{from:'',to:'',min:'',max:''}, RRSP:{from:'',to:'',min:'',max:''}};
let selectedTxnRow = {TFSA:-1, FHSA:-1, RRSP:-1};
let importBusyState = {active:false,message:''};
let curView = 'dashboard';
let modalPlan = '';
let editingIndex = -1; // -1 = adding, >=0 = editing
let undoStack = []; // for undo
let _cachedSelfTest = null; // cache self-test results
let _isDarkTheme = true;
let _loadWarnings = []; // surfaced after successful boot
let importSourceBuffer = {name:'',text:'',meta:null,files:[]};
let importSession = null;
let _deferredInstallPrompt=null;
let _pwaReg=null;
let _pwaState={supported:typeof navigator!=='undefined'&&'serviceWorker'in navigator,localFile:typeof location!=='undefined'&&location.protocol==='file:',online:typeof navigator!=='undefined'?navigator.onLine:true,registered:false,controller:false,installReady:false,installed:false,lastError:'',scope:''};
if(typeof window!=='undefined'){
window.addEventListener('beforeinstallprompt',e=>{
e.preventDefault();
_deferredInstallPrompt=e;
_pwaState.installReady=true;
if(typeof render==='function'&&document.readyState!=='loading'){try{render()}catch(_){}}
});
window.addEventListener('appinstalled',()=>{
_deferredInstallPrompt=null;
_pwaState.installReady=false;
_pwaState.installed=true;
if(typeof showToast==='function')showToast('Tracker installed for quicker access.',null,2800);
if(typeof render==='function'&&document.readyState!=='loading'){try{render()}catch(_){}}
});
window.addEventListener('online',()=>{_pwaState.online=true;if(typeof render==='function'&&document.readyState!=='loading'&&curView==='dashboard'){try{render()}catch(_){}}});
window.addEventListener('offline',()=>{_pwaState.online=false;if(typeof render==='function'&&document.readyState!=='loading'&&curView==='dashboard'){try{render()}catch(_){}}});
if(_pwaState.supported&&navigator.serviceWorker){
navigator.serviceWorker.addEventListener('controllerchange',()=>{_pwaState.controller=true;if(typeof render==='function'&&document.readyState!=='loading'&&curView==='dashboard'){try{render()}catch(_){}}});
}
}
async function registerPwaSupport(){
if(!_pwaState.supported)return;
if(_pwaState.localFile){_pwaState.lastError='Offline install activates after hosting on HTTPS or localhost. Local file mode still works, but service-worker caching is unavailable.';return;}
try{
_pwaReg=await navigator.serviceWorker.register('./roommap_demo_sw.js');
_pwaState.registered=true;
_pwaState.controller=!!navigator.serviceWorker.controller;
_pwaState.scope=_pwaReg&&_pwaReg.scope?_pwaReg.scope:'';
_pwaState.lastError='';
if(typeof render==='function'&&document.readyState!=='loading'&&curView==='dashboard'){try{render()}catch(_){}}
}catch(e){
_pwaState.lastError=String((e&&e.message)||e||'PWA registration failed.');
if(typeof render==='function'&&document.readyState!=='loading'&&curView==='dashboard'){try{render()}catch(_){}}
}
}
async function promptInstallPwa(){
if(_pwaState.localFile){if(typeof showToast==='function')showToast('Install prompts are available on the hosted HTTPS version, not file://.',null,3600);return;}
if(!_deferredInstallPrompt){if(typeof showToast==='function')showToast('Install prompt not available yet. Open the hosted page in Chrome or Edge and interact with it once first.',null,4200);return;}
try{
_deferredInstallPrompt.prompt();
await _deferredInstallPrompt.userChoice.catch(()=>null);
}catch(e){
if(typeof showToast==='function')showToast('Could not open the install prompt.',null,3200);
}
}
async function refreshOfflineCache(){
if(_pwaState.localFile){if(typeof showToast==='function')showToast('Offline cache refresh is available on the hosted HTTPS version.',null,3400);return;}
try{
const reg=_pwaReg||await navigator.serviceWorker.getRegistration();
if(!reg){if(typeof showToast==='function')showToast('No service-worker registration found yet.',null,3200);return;}
await reg.update();
if(reg.active)reg.active.postMessage({type:'refresh-cache'});
if(typeof showToast==='function')showToast('Offline cache refresh requested.',null,2600);
}catch(e){
if(typeof showToast==='function')showToast('Could not refresh the offline cache.',null,3200);
}
}
function buildPwaPanel(){
const s=_pwaState||{};
const statusText=!s.supported?'Unsupported browser':s.localFile?'Local file mode':(s.registered?'Offline-ready shell active':'Hosted mode detected');
const statusClass=!s.supported?'warn':s.localFile?'warn':(s.registered?'ok':'neutral');
const detail=s.lastError?escapeHtml(s.lastError):(s.scope?`Service-worker scope: <b>${escapeHtml(s.scope)}</b>.`:(s.localFile?'Open this same tracker from a hosted HTTPS URL to enable install and offline caching.':'Hosted mode detected. If offline support is not active yet, make sure the matching <b>service worker</b>, <b>manifest</b>, and the icon files are deployed in the same folder as this HTML.'));
return `<div class="panel mt-lg pwa-panel"><div class="panel-head"><div><h3 class="panel-title">Offline / Install Hardening</h3><div class="panel-sub">For GitHub Pages or any HTTPS deployment. Keep the HTML, manifest, service worker, and icons together in the same hosted folder.</div></div><div class="panel-head-actions">${s.installReady?'<button type="button" onclick="promptInstallPwa()">Install App</button>':''}${s.supported&&!s.localFile?'<button type="button" onclick="refreshOfflineCache()">Refresh Offline Cache</button>':''}</div></div><div class="pwa-status-row"><span class="status-pill ${statusClass}">${statusText}</span><span class="status-pill ${s.online?'ok':'warn'}">${s.online?'Online':'Offline'}</span>${s.registered?'<span class="status-pill ok">Service worker registered</span>':''}${s.installed?'<span class="status-pill ok">Installed</span>':''}</div><div class="pwa-note">${detail}</div><div class="pwa-note" style="margin-top:8px">Local <b>file://</b> usage still works as a normal HTML tracker. PWA install and offline caching become active after you publish the files to <b>localhost</b> or any <b>HTTPS</b> host such as GitHub Pages.</div></div>`;
}
// ─── Utilities ───
function clone(obj){return JSON.parse(JSON.stringify(obj))}
function cloneConfig(config){
const cfg=config||{};
return Object.assign(clone(CONFIG_DEFAULTS),cfg,{tfsaAnnualLimits:Object.assign(clone(CONFIG_DEFAULTS.tfsaAnnualLimits),(cfg&&cfg.tfsaAnnualLimits)||{})});
}
function clonePrefs(prefs){
return Object.assign(clone(UI_DEFAULTS),prefs||{});
}
function hasCustomBaseline(bundle){
return !!(bundle&&bundle.customBaseline&&typeof bundle.customBaseline==='object'&&Array.isArray(bundle.customBaseline.t)&&Array.isArray(bundle.customBaseline.f));
}
function normalizeBaselineSnapshot(snapshot,id){
if(!snapshot||typeof snapshot!=='object')return null;
const normalized=normalizeProfileBundle(Object.assign({},snapshot,{customBaseline:null}),id);
delete normalized.customBaseline;
return {label:normalized.label,t:clone(normalized.t),f:clone(normalized.f),rrsp:clone(normalized.rrsp),config:cloneConfig(normalized.config),prefs:clonePrefs(normalized.prefs),resetMode:'baseline'};
}
function sanitizePrefsForBaseline(prefs){
const out=clonePrefs(prefs);
out.demoSeedActive=false;
out.postImportNotice=null;
return out;
}
function buildCurrentProfileBaselineSnapshot(activeId,labelOverride){
return {label:labelOverride||getActiveProfileLabel(),t:clone(tT),f:clone(fT),rrsp:{txns:clone(rT),annual:clone(rrspYears),receipts:clone(rrspReceipts),meta:clone(rrspMeta)},config:cloneConfig(trackerConfig),prefs:sanitizePrefsForBaseline(uiPrefs),resetMode:'baseline'};
}
function activeProfileHasLedgerData(){
return !!(tT.length||fT.length||rT.length||rrspYears.length||rrspReceipts.length);
}
function clearDemoModeForActiveProfile(){
if(Object.prototype.hasOwnProperty.call(uiPrefs,'demoSeedActive')) uiPrefs.demoSeedActive=false;
if(profileState&&profileState.profiles){
const active=profileState.active||'p1';
const current=profileState.profiles[active];
if(current&¤t.prefs){ current.prefs=clonePrefs(current.prefs); current.prefs.demoSeedActive=false; }
}
}
const SECOND_PROFILE_LABEL='Profile 2';
let profileState=null;
function makeEmptyProfileBundle(label){
const prefs=clonePrefs();
if(Object.prototype.hasOwnProperty.call(prefs,'demoSeedActive'))prefs.demoSeedActive=false;
if(prefs&&prefs.craSnapshots)prefs.craSnapshots={tfsa:null,fhsa:null};
return {label:label||SECOND_PROFILE_LABEL,t:[],f:[],rrsp:makeEmptyRrspState(),config:cloneConfig(),prefs,resetMode:'empty',customBaseline:null};
}
function makeSeedProfileBundle(label){
const prefs=clonePrefs();
if(Object.prototype.hasOwnProperty.call(prefs,'demoSeedActive')) prefs.demoSeedActive=true;
return {label:label||'Demo Profile',t:expandT(INIT_T),f:expandF(INIT_F),rrsp:cloneRrspSeed(),config:cloneConfig(),prefs,resetMode:'seeded',customBaseline:null};
}
function normalizeProfileBundle(bundle,id){
const fallback=id==='p1'?makeSeedProfileBundle((bundle&&bundle.label)||'Profile 1'):makeEmptyProfileBundle((bundle&&bundle.label)||SECOND_PROFILE_LABEL);
const sourcePrefs=bundle&&bundle.prefs&&typeof bundle.prefs==='object'?bundle.prefs:null;
const sourceHasDemoSeedActive=!!(sourcePrefs&&Object.prototype.hasOwnProperty.call(sourcePrefs,'demoSeedActive'));
const out={
label:(bundle&&bundle.label)||fallback.label,
t:Array.isArray(bundle&&bundle.t)?bundle.t:fallback.t,
f:Array.isArray(bundle&&bundle.f)?bundle.f:fallback.f,
rrsp:normalizeRrspState(bundle&&bundle.rrsp, id==='p1'),
config:bundle&&bundle.config?cloneConfig(bundle.config):fallback.config,
prefs:bundle&&bundle.prefs?clonePrefs(bundle.prefs):fallback.prefs,
resetMode:(bundle&&bundle.resetMode)||fallback.resetMode,
customBaseline:normalizeBaselineSnapshot(bundle&&bundle.customBaseline,id)
};
const rrspVersion=String((out.rrsp&&out.rrsp.meta&&out.rrsp.meta.moduleVersion)||'');
const rrspExplicitUserEmpty=!!(out.rrsp&&out.rrsp.meta&&out.rrsp.meta.userEmptyExplicitVersion===RRSP_EMPTY_EXPLICIT_VERSION&&rrspVersion===String((DEFAULT_RRSP_META&&DEFAULT_RRSP_META.moduleVersion)||'')&&out.rrsp.intentionalEmpty===true);
const legacySeededProfile=id==='p1' && !rrspStateHasData(out.rrsp) && (out.t.length>0 || out.f.length>0 || out.resetMode==='seeded') && !rrspExplicitUserEmpty;
if(legacySeededProfile){
out.rrsp=cloneRrspSeed();
out.rrsp.meta.moduleVersion=DEFAULT_RRSP_META.moduleVersion;
out.rrsp.meta.seedState='seeded';
out.rrsp.intentionalEmpty=false;
if(out.resetMode!=='seeded')out.resetMode='seeded';
}
if(id==='p1' && !sourceHasDemoSeedActive && out.resetMode==='seeded' && !hasCustomBaseline(out)) out.prefs.demoSeedActive=true;
if(Object.prototype.hasOwnProperty.call(out.prefs,'demoSeedActive') && id!=='p1') out.prefs.demoSeedActive=false;
return out;
}
function buildInitialProfileStateFromCurrent(){
return {
active:'p1',
profiles:{
p1:normalizeProfileBundle({label:'Demo Profile',t:clone(tT),f:clone(fT),rrsp:{txns:clone(rT),annual:clone(rrspYears),receipts:clone(rrspReceipts),meta:clone(rrspMeta)},config:cloneConfig(trackerConfig),prefs:clonePrefs(uiPrefs),resetMode:'seeded',customBaseline:null},'p1'),
p2:makeEmptyProfileBundle(SECOND_PROFILE_LABEL)
}
};
}
function ensureProfileState(){
if(!profileState||!profileState.profiles){
profileState=buildInitialProfileStateFromCurrent();
}
profileState.profiles.p1=normalizeProfileBundle(profileState.profiles.p1,'p1');
profileState.profiles.p2=normalizeProfileBundle(profileState.profiles.p2,'p2');
if(!['p1','p2'].includes(profileState.active))profileState.active='p1';
}
function captureCurrentProfile(){
ensureProfileState();
const active=profileState.active||'p1';
const existing=profileState.profiles[active]||normalizeProfileBundle(null,active);
profileState.profiles[active]={
label:existing.label|| (active==='p1'?'Profile 1':SECOND_PROFILE_LABEL),
t:clone(tT),
f:clone(fT),
rrsp:{txns:clone(rT),annual:clone(rrspYears),receipts:clone(rrspReceipts),meta:clone(rrspMeta)},
config:cloneConfig(trackerConfig),
prefs:clonePrefs(uiPrefs),
resetMode:existing.resetMode||(active==='p1'?'seeded':'empty'),
customBaseline:normalizeBaselineSnapshot(existing.customBaseline,active)
};
}
function applyProfileBundle(id){
ensureProfileState();
const bundle=normalizeProfileBundle(profileState.profiles[id],id);
profileState.profiles[id]=bundle;
profileState.active=id;
tT=clone(bundle.t);
fT=clone(bundle.f);
rT=clone((bundle.rrsp&&bundle.rrsp.txns)||[]);
rrspYears=clone((bundle.rrsp&&bundle.rrsp.annual)||[]);
rrspReceipts=clone((bundle.rrsp&&bundle.rrsp.receipts)||[]);
rrspMeta=Object.assign(clone(DEFAULT_RRSP_META),(bundle.rrsp&&bundle.rrsp.meta)||{});
trackerConfig=cloneConfig(bundle.config);
uiPrefs=clonePrefs(bundle.prefs);
importSession=null;
importSourceBuffer={name:'',text:'',meta:null,files:[]};
seedNormalizedData();
_cachedSelfTest=null;
}
function switchProfile(id){
ensureProfileState();
if(id===profileState.active)return;
undoStack=[];
captureCurrentProfile();
applyProfileBundle(id);
save();
render();
showToast(`Switched to ${profileState.profiles[id].label}.`,null,2400);
}
function getActiveProfileLabel(){
ensureProfileState();
return (profileState.profiles[profileState.active]&&profileState.profiles[profileState.active].label)||'Profile';
}
function updateProfileBar(){
ensureProfileState();
const p1=profileState.profiles.p1||normalizeProfileBundle(null,'p1');
const p2=profileState.profiles.p2||normalizeProfileBundle(null,'p2');
const sel=document.getElementById('profile-select');
const chip=document.querySelector('.profile-chip');
if(sel){
const active=profileState.active||'p1';
sel.innerHTML=`<option value="p1">${escapeHtml(p1.label||'Demo Profile')}</option><option value="p2">${escapeHtml(p2.label||SECOND_PROFILE_LABEL)}</option>`;
sel.value=['p1','p2'].includes(active)?active:'p1';
sel.title=`Active profile: ${getActiveProfileLabel()}.`;
}
if(chip){
const label=getActiveProfileLabel();
chip.textContent='Profile';
chip.title=`Active profile: ${label}`;
chip.setAttribute('aria-label',`Active profile: ${label}`);
}
}
function onProfileSelectChange(value){
switchProfile(value);
}
function renameActiveProfile(){
ensureProfileState();
const active=profileState.active||'p1';
const current=profileState.profiles[active]||normalizeProfileBundle(null,active);
const next=prompt('Rename this profile:', current.label||'');
if(next===null)return;
const cleaned=String(next||'').trim().slice(0,40);
if(!cleaned){ alert('Profile name cannot be empty.'); return; }
current.label=cleaned;
profileState.profiles[active]=current;
save();
updateProfileBar();
render();
showToast(`Renamed profile to ${cleaned}.`,null,2200);
}
function getResetSeedForCurrentProfile(){
ensureProfileState();
const active=profileState.active||'p1';
const current=profileState.profiles[active]||normalizeProfileBundle(null,active);
if(active==='p1'){
if(hasCustomBaseline(current)){
const baseline=normalizeBaselineSnapshot(current.customBaseline,active);
baseline.label=current.label||baseline.label||'Profile 1';
baseline.resetMode='baseline';
return baseline;
}
return makeSeedProfileBundle(current.label||'Demo Profile');
}
return makeEmptyProfileBundle(current.label||SECOND_PROFILE_LABEL);
}
function setCurrentAsBaseline(){
ensureProfileState();
const active=profileState.active||'p1';
if(active!=='p1'){ alert('A saved baseline is only supported for Profile 1 in this demo build.'); return; }
if(!activeProfileHasLedgerData()){ alert('Load or enter data first, then save the current state as the baseline.'); return; }
const current=profileState.profiles[active]||normalizeProfileBundle(null,active);
const hasBaseline=hasCustomBaseline(current);
const msg=hasBaseline
? 'Replace the saved reset baseline for this profile with the current data?\n\nFuture Reset actions will restore this current state instead of the factory demo.'
: 'Save the current data as this profile\'s reset baseline?\n\nFuture Reset actions will restore this current state instead of the factory demo.';
if(!confirm(msg)) return;
if(typeof clearDemoModeForActiveProfile==='function')clearDemoModeForActiveProfile();
const snapshot=buildCurrentProfileBaselineSnapshot(active,current.label||getActiveProfileLabel());
current.customBaseline=normalizeBaselineSnapshot(snapshot,active);
current.resetMode='baseline';
current.prefs=clonePrefs(uiPrefs);
current.prefs.demoSeedActive=false;
profileState.profiles[active]=current;
appendActivityLog({kind:'baseline_save'});
save(); render();
showToast('Saved current data as the reset baseline.', null, 2600);
}
function restoreFactoryDemo(){
ensureProfileState();
const active=profileState.active||'p1';
if(active!=='p1'){ alert('Factory demo restore is only available for Profile 1 in this demo build.'); return; }
const current=profileState.profiles[active]||normalizeProfileBundle(null,active);
const hasBaseline=hasCustomBaseline(current);
const msg=hasBaseline
? 'Load the factory demo data for this profile?\n\nYour saved personal baseline will be kept. Use Reset later to restore your saved baseline.'
: 'Load the factory demo data for this profile?\n\nThis will replace the current local state with the bundled demo examples.';
if(!confirm(msg)) return;
const restored=makeSeedProfileBundle(current.label||'Demo Profile');
restored.customBaseline=normalizeBaselineSnapshot(current.customBaseline,active);
restored.resetMode=hasBaseline?'baseline':'seeded';
profileState.profiles[active]=restored;
applyProfileBundle(active);
appendActivityLog({kind:'factory_demo_restore'});
save(); render();
showToast('Factory demo restored.', null, 2400);
}
function safeNum(v){const n=Number(v); return Number.isFinite(n)?n:0}
function parseIsoDate(v){
const s=String(v||'').trim();
const m=/^(\d{4})-(\d{2})-(\d{2})$/.exec(s);
if(!m)return null;
const y=+m[1], mo=+m[2], d=+m[3];
const dt=new Date(Date.UTC(y,mo-1,d));
if(dt.getUTCFullYear()!==y||dt.getUTCMonth()!==mo-1||dt.getUTCDate()!==d)return null;
return {y,m:mo,d,iso:s,date:dt};
}
function isRealIsoDate(v){return !!parseIsoDate(v)}
function actualCalendarYear(){return new Date().getFullYear()}
function getCurrentYear(){return Math.max(2009,+trackerConfig.currentYear||actualCalendarYear())}
function getProjectionEndYear(){return Math.max(getCurrentYear(), getLatestLoadedYear())}
function getTfsaStartYear(){return +trackerConfig.tfsaEligibleStartYear||2009}
function getFhsaStartYear(){return +trackerConfig.fhsaFirstYear||2023}
function getTfsaLimits(){return trackerConfig.tfsaAnnualLimits||clone(CONFIG_DEFAULTS.tfsaAnnualLimits)}
function getLatestLoadedYear(){
let max=actualCalendarYear();
tT.forEach(t=>{const parsed=parseIsoDate(t.d);if(parsed&&parsed.y>max)max=parsed.y});
fT.forEach(t=>{const parsed=parseIsoDate(t.d);if(parsed&&parsed.y>max)max=parsed.y});
return max;
}
function currentMonthSlotsRemaining(cy){return cy===actualCalendarYear()?Math.max(1,12-new Date().getMonth()):12}
function monthKey(d){return String(d||'').slice(0,7)}
function escAttr(v){return String(v??'').replace(/&/g,'&').replace(/"/g,'"').replace(/</g,'<').replace(/>/g,'>')}
const F=n=>'$'+Math.abs(n||0).toLocaleString('en-CA',{minimumFractionDigits:2,maximumFractionDigits:2});
const OFFICIAL_TFSA_YEARS=new Set(Object.keys(OFFICIAL_TFSA_LIMITS).map(Number));
let _txnSeqSeed=1;
function resetTxnSeqSeed(){_txnSeqSeed=1}
function nextTxnSeq(){return _txnSeqSeed++}
function makeTxnId(plan,seq){return `${plan}-${String(seq).padStart(6,'0')}`}
function ensureTxnIdentity(plan,txn,fallbackSeq){
const out=Object.assign({},txn||{});
const seqCandidate=Math.floor(safeNum(out.seq||fallbackSeq||0));
const seq=seqCandidate>0?seqCandidate:nextTxnSeq();
_txnSeqSeed=Math.max(_txnSeqSeed,seq+1);
out.seq=seq;
out.id=String(out.id||makeTxnId(plan,seq));
return out;
}
function sortTxnsAsc(a,b){return String(a.d||'').localeCompare(String(b.d||''))||safeNum(a.seq)-safeNum(b.seq)||String(a.id||'').localeCompare(String(b.id||''))}
function sortTxnsDesc(a,b){return String(b.d||'').localeCompare(String(a.d||''))||safeNum(b.seq)-safeNum(a.seq)||String(b.id||'').localeCompare(String(a.id||''))}
function simpleChecksum(obj){
const s=typeof obj==='string'?obj:JSON.stringify(obj);
let h=0;
for(let i=0;i<s.length;i++){h=((h<<5)-h+s.charCodeAt(i))|0}
return 'chk-'+(h>>>0).toString(16);
}
function downloadTextFile(filename,text,type){
const blob=new Blob([text],{type:type||'text/plain;charset=utf-8'});
const u=URL.createObjectURL(blob),a=document.createElement('a');
a.href=u;a.download=filename;a.click();URL.revokeObjectURL(u);
}
function toCSV(rows){
const esc=v=>{const s=String(v??'');return /[",\n]/.test(s)?'"'+s.replace(/"/g,'""')+'"':s};
return rows.map(r=>r.map(esc).join(',')).join('\n');
}
function downloadCsvRows(filename,rows){downloadTextFile(filename,toCSV(rows),'text/csv;charset=utf-8')}
function todayISO(){return new Date().toISOString().split('T')[0]}
function slugifyFilePart(v){return String(v||'profile').trim().toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-+|-+$/g,'')||'profile'}
function summarizeTxnChanges(oldTxn,newTxn,plan){
if(!oldTxn||!newTxn)return '';
const bits=[];
const flagKey=plan==='TFSA'?'treat':'status';
const labels={d:'date',inst:'institution',acct:'account',type:'type',amt:'amount',note:'note'};
['d','inst','acct','type','amt','note'].forEach(key=>{
const a=key==='amt'?safeNum(oldTxn[key]):String(oldTxn[key]||'');
const b=key==='amt'?safeNum(newTxn[key]):String(newTxn[key]||'');
if(key==='amt' ? Math.abs(a-b)>0.005 : a!==b){
const from=key==='amt'?F(a):(a||'—');
const to=key==='amt'?F(b):(b||'—');
bits.push(`${labels[key]} ${from} → ${to}`);
}
});
const fa=normalizeFlag(oldTxn[flagKey],'Include');
const fb=normalizeFlag(newTxn[flagKey],'Include');
if(fa!==fb)bits.push(`${plan==='TFSA'?'treatment':'status'} ${fa} → ${fb}`);
return bits.join(' • ');
}
function formatDateTime(ts){
if(!ts)return '—';
const d=new Date(ts);
if(Number.isNaN(+d))return '—';
return d.toLocaleString(undefined,{year:'numeric',month:'short',day:'numeric',hour:'numeric',minute:'2-digit'});
}
function setImportBusy(active,msg){
importBusyState={active:!!active,message:String(msg||'').trim()};
const el=document.getElementById('import-busy');
const analyzeBtn=document.getElementById('import-analyze-btn');
const commitBtn=document.getElementById('import-commit-btn');
if(el){
if(importBusyState.active){
el.classList.remove('hidden');
el.innerHTML=`<div class="spinner" aria-hidden="true"></div><div><b>${escapeHtml(importBusyState.message||'Working…')}</b><div class="dim">Large PDFs and spreadsheets can take a moment. Keep this tab open until parsing finishes.</div></div>`;
}else{
el.classList.add('hidden');
el.innerHTML='';
}
}
if(analyzeBtn)analyzeBtn.disabled=importBusyState.active;
if(commitBtn&&importBusyState.active)commitBtn.disabled=true;
}
function getTxnFilterState(plan){
if(!txnAdvancedFilters[plan])txnAdvancedFilters[plan]={from:'',to:'',min:'',max:''};
return txnAdvancedFilters[plan];
}
function setTxnFilter(plan,key,val){
const state=getTxnFilterState(plan);
state[key]=String(val??'');
txnFilters[plan.toLowerCase()+'Pg']=0;
renderFilteredTxns(plan);
}
function clearTxnFilters(plan){
txnSearch[plan]='';
txnAdvancedFilters[plan]={from:'',to:'',min:'',max:''};
txnFilters[plan.toLowerCase()+'Pg']=0;
const ids=['search','from','to','min','max'];
ids.forEach(id=>{
const el=document.getElementById(`${plan.toLowerCase()}-filter-${id}`);
if(el)el.value='';
});
renderFilteredTxns(plan);
}
function getTxnFilteredRows(plan){
const txns=plan==='TFSA'?tT:plan==='FHSA'?fT:rT;
const yr=txnFilters[plan];
const q=(txnSearch[plan]||'').toLowerCase();
const adv=getTxnFilterState(plan);
const minAmt=adv.min===''?null:safeNum(adv.min);
const maxAmt=adv.max===''?null:safeNum(adv.max);
const from=String(adv.from||'');
const to=String(adv.to||'');
let filtered=[...txns].sort(sortTxnsDesc);
if(yr!=='all')filtered=filtered.filter(t=>String(t.d||'').startsWith(yr));
if(q)filtered=filtered.filter(t=>[t.d,t.inst,t.acct,t.type,t.note,String(t.amt)].join(' ').toLowerCase().includes(q));
if(from)filtered=filtered.filter(t=>String(t.d||'')>=from);
if(to)filtered=filtered.filter(t=>String(t.d||'')<=to);
if(minAmt!==null&&!Number.isNaN(minAmt))filtered=filtered.filter(t=>safeNum(t.amt)>=minAmt-0.005);
if(maxAmt!==null&&!Number.isNaN(maxAmt))filtered=filtered.filter(t=>safeNum(t.amt)<=maxAmt+0.005);
return filtered;
}
function buildCombinedContributionPace(year){
const monthly=new Array(12).fill(0);
tT.forEach(t=>{
if(String(t.d||'').slice(0,4)!==String(year))return;
if(normalizeFlag(t.treat,'Include')!=='Include')return;
if(normalizeTfsaType(t.type)!=='Contribution')return;
const m=+String(t.d||'').slice(5,7);
if(m>=1&&m<=12)monthly[m-1]+=safeNum(t.amt);
});
fT.forEach(t=>{
if(String(t.d||'').slice(0,4)!==String(year))return;
if(normalizeFlag(t.status,'Include')!=='Include')return;
const meta=fhsaTypeMeta(normalizeFhsaType(t.type));
if(meta.bucket!=='counted_inflow')return;
const m=+String(t.d||'').slice(5,7);
if(m>=1&&m<=12)monthly[m-1]+=safeNum(t.amt);
});
const cumulative=[];
let running=0;
monthly.forEach(v=>{running+=v; cumulative.push(running);});
return {monthly,cumulative,total:running};
}
function appendImportHistory(entry){
uiPrefs=uiPrefs||clonePrefs();
const hist=Array.isArray(uiPrefs.importHistory)?uiPrefs.importHistory.slice():[];
hist.unshift(Object.assign({ts:Date.now(),profile:getActiveProfileLabel()},entry||{}));
uiPrefs.importHistory=hist.slice(0,20);
}
function buildImportHistoryPanel(){
const hist=Array.isArray(uiPrefs.importHistory)?uiPrefs.importHistory:[];
if(!hist.length)return '';
let h='<div class="panel mt-lg"><div class="panel-head"><div><h3 class="panel-title">Import History</h3></div><div class="panel-head-actions"><button type="button" onclick="exportImportHistoryCsv()">Export CSV</button><button type="button" onclick="clearImportHistory()">Clear</button></div></div><div class="import-history-list">';
hist.slice(0,8).forEach(item=>{
const label=item.kind==='commit'?'Import committed':(item.kind==='snapshot'?'CRA snapshot saved':'Import analyzed');
const parts=[];
if(item.source)parts.push(escapeHtml(item.source));
if(item.fileName)parts.push(escapeHtml(item.fileName));
if(item.rows!==undefined)parts.push(`${item.rows} parsed row(s)`);
if(item.imported!==undefined)parts.push(`${item.imported} imported`);
if(item.skippedDuplicates!==undefined)parts.push(`${item.skippedDuplicates} duplicate(s) skipped`);
if(item.futureWarnings)parts.push(`${item.futureWarnings} future-date warning(s)`);
h+=`<div class="import-history-item"><div class="import-history-item-main"><div class="import-history-item-title">${label}</div><div class="import-history-item-meta">${parts.join(' • ')||'Manual activity'}</div></div><div class="import-history-item-side">${escapeHtml(item.profile||getActiveProfileLabel())}<br>${escapeHtml(formatDateTime(item.ts))}</div></div>`;
});
h+='</div><p class="panel-sub">Stored per profile so you can see what was analyzed and imported into the active ledger.</p></div>';
return h;
}
function getLastSavedLabel(){
try{
const raw=localStorage.getItem(STORAGE_KEY);
if(!raw) return 'Last saved locally during this session';
const payload=JSON.parse(raw||'null');
if(!payload||!payload.savedAt) return 'Last saved locally during this session';
return 'Last saved '+formatDateTime(payload.savedAt);
}catch(_){
return 'Last saved locally during this session';
}
}
function exportImportHistoryCsv(){
const hist=Array.isArray(uiPrefs&&uiPrefs.importHistory)?uiPrefs.importHistory:[];
if(!hist.length){alert('No import history to export for this profile.');return}
const rows=[['timestamp','profile','kind','source','file_name','rows','imported','skipped_duplicates','future_warnings']];
hist.forEach(item=>{
rows.push([
new Date(item.ts||Date.now()).toISOString(),
item.profile||getActiveProfileLabel(),
item.kind||'',
item.source||'',
item.fileName||'',
item.rows!==undefined?item.rows:'',
item.imported!==undefined?item.imported:'',
item.skippedDuplicates!==undefined?item.skippedDuplicates:'',
item.futureWarnings!==undefined?item.futureWarnings:''
]);
});
downloadCsvRows(`import_history_${slugifyFilePart(getActiveProfileLabel())}_${todayISO()}.csv`,rows);
}
function clearImportHistory(){
const hist=Array.isArray(uiPrefs&&uiPrefs.importHistory)?uiPrefs.importHistory:[];
if(!hist.length)return;
if(!confirm('Clear the import history for the active profile?'))return;
uiPrefs.importHistory=[];
save(); render();
}
function appendActivityLog(entry){
uiPrefs=uiPrefs||clonePrefs();
const hist=Array.isArray(uiPrefs.activityLog)?uiPrefs.activityLog.slice():[];
hist.unshift(Object.assign({ts:Date.now(),profile:getActiveProfileLabel()},entry||{}));
uiPrefs.activityLog=hist.slice(0,30);
}
function buildActivityLogPanel(){
const hist=Array.isArray(uiPrefs.activityLog)?uiPrefs.activityLog:[];
if(!hist.length)return '';
let h='<div class="panel mt-lg"><div class="panel-head"><div><h3 class="panel-title">Recent Ledger Activity</h3></div><div class="panel-head-actions"><button type="button" onclick="exportActivityLogCsv()">Export CSV</button><button type="button" onclick="clearActivityLog()">Clear</button></div></div><div class="activity-log-list">';
hist.slice(0,8).forEach(item=>{
const parts=[];
let label='Manual activity';
if(item.kind==='add')label=`Added ${item.plan||''} transaction`.trim();
else if(item.kind==='edit')label=`Edited ${item.plan||''} transaction`.trim();
else if(item.kind==='delete')label=`Deleted ${item.plan||''} transaction`.trim();
else if(item.kind==='import')label='Imported parsed rows';
else if(item.kind==='snapshot')label='Saved CRA room snapshot';
else if(item.kind==='start_empty')label='Started empty ledger';
else if(item.kind==='reset')label='Reset profile';
else if(item.kind==='json_import')label='Imported JSON backup';
if(item.date)parts.push(item.date);
if(item.type)parts.push(item.type);
if(item.amount!==undefined)parts.push(F(item.amount));
if(item.fileName)parts.push(escapeHtml(item.fileName));
if(item.rows!==undefined)parts.push(`${item.rows} parsed row(s)`);
if(item.imported!==undefined)parts.push(`${item.imported} imported`);
if(item.skippedDuplicates)parts.push(`${item.skippedDuplicates} duplicate(s) skipped`);
if(item.snapshotCount)parts.push(`${item.snapshotCount} snapshot(s)`);
if(item.mode)parts.push(item.mode==='seeded'?'seeded defaults':'empty profile');
if(item.note)parts.push('note: '+escapeHtml(item.note));
if(item.changeSummary)parts.push(escapeHtml(item.changeSummary));
h+=`<div class="activity-log-item"><div class="activity-log-item-main"><div class="activity-log-item-title">${label}</div><div class="activity-log-item-meta">${parts.join(' • ')||'No extra details recorded.'}</div></div><div class="activity-log-item-side">${escapeHtml(item.profile||getActiveProfileLabel())}<br>${escapeHtml(formatDateTime(item.ts))}</div></div>`;
});
h+='</div><p class="panel-sub">This is a per-profile audit trail for adds, edits, deletes, resets, snapshot saves, and committed imports.</p></div>';
return h;
}
function exportActivityLogCsv(){
const hist=Array.isArray(uiPrefs&&uiPrefs.activityLog)?uiPrefs.activityLog:[];
if(!hist.length){alert('No activity log to export for this profile.');return}
const rows=[['timestamp','profile','kind','plan','date','type','amount','note','change_summary','source','file_name','rows','imported','skipped_duplicates','snapshot_count','mode']];
hist.forEach(item=>{
rows.push([
new Date(item.ts||Date.now()).toISOString(),
item.profile||getActiveProfileLabel(),
item.kind||'',
item.plan||'',
item.date||'',
item.type||'',
item.amount!==undefined?item.amount:'',
item.note||'',
item.changeSummary||'',
item.source||'',
item.fileName||'',
item.rows!==undefined?item.rows:'',
item.imported!==undefined?item.imported:'',
item.skippedDuplicates!==undefined?item.skippedDuplicates:'',
item.snapshotCount!==undefined?item.snapshotCount:'',
item.mode||''
]);
});
downloadCsvRows(`activity_log_${slugifyFilePart(getActiveProfileLabel())}_${todayISO()}.csv`,rows);
}
function clearActivityLog(){
const hist=Array.isArray(uiPrefs&&uiPrefs.activityLog)?uiPrefs.activityLog:[];
if(!hist.length)return;
if(!confirm('Clear the activity log for the active profile?'))return;
uiPrefs.activityLog=[];
save(); render();
}
function buildCraReconciliationPanel(tfsa,fhsa){
const snaps=(uiPrefs&&uiPrefs.craSnapshots)||{};
const cards=[];
if(snaps.tfsa&&snaps.tfsa.year){
const year=String(snaps.tfsa.year);
const yr=tfsa.years&&tfsa.years[year]||{};
const ledger=safeNum(yr.openRoom);
const cra=safeNum(snaps.tfsa.amount);
const diff=ledger-cra;
const state=Math.abs(diff)<=0.005?'match':(Math.abs(diff)<=250?'warn':'alert');
cards.push(`<div class="recon-card ${state}"><div class="recon-eyebrow">TFSA snapshot • ${escapeHtml(year)}</div><div class="recon-value">${F(diff)}</div><div class="recon-detail"><b>Ledger opening room:</b> ${F(ledger)}<br><b>Saved CRA room:</b> ${F(cra)}<br><b>Delta:</b> ${diff>0?'+':''}${F(diff)}</div><div class="recon-detail" style="margin-top:8px">Compare this against CRA My Account after confirming your imported history through December 31 of the prior year.</div></div>`);
}
if(snaps.fhsa&&snaps.fhsa.year){
const year=String(snaps.fhsa.year);
const yr=fhsa.years&&fhsa.years[year]||{};
const ledger=safeNum(yr.participationRoom);
const cra=safeNum(snaps.fhsa.amount);
const diff=ledger-cra;
const state=Math.abs(diff)<=0.005?'match':(Math.abs(diff)<=250?'warn':'alert');
cards.push(`<div class="recon-card ${state}"><div class="recon-eyebrow">FHSA snapshot • ${escapeHtml(year)}</div><div class="recon-value">${F(diff)}</div><div class="recon-detail"><b>Ledger participation room:</b> ${F(ledger)}<br><b>Saved CRA room:</b> ${F(cra)}<br><b>Delta:</b> ${diff>0?'+':''}${F(diff)}</div><div class="recon-detail" style="margin-top:8px">For FHSA, direct FHSA-to-FHSA transfers should remain room-neutral. Investigate any material drift.</div></div>`);
}
if(!cards.length)return '';
return `<div class="panel mt-lg"><h3 class="panel-title">CRA Reconciliation Snapshot</h3><div class="recon-grid">${cards.join('')}</div><div class="recon-actions"><button type="button" onclick="openImportAssistant()">Import / refresh CRA source</button><button type="button" onclick="showView('annual')">Open Annual roll-forward</button></div><p class="panel-sub">Snapshots are stored per profile. TFSA compares against the opening room for the snapshot year; FHSA compares against participation room for the snapshot year.</p></div>`;
}
function buildTxnImpactText(plan,row){
if(plan==='TFSA'){
if(row.type==='Contribution')return 'Consumes TFSA room';
if(row.type==='Withdrawal')return 'Creates next-year TFSA addback';
if(row.type==='Transfer In'||row.type==='Transfer Out')return 'Room-neutral transfer';
return 'Review classification';
}
const meta=fhsaTypeMeta(row.type);
if(meta.bucket==='counted_inflow')return 'Consumes FHSA participation room';
if(meta.bucket==='taxable_withdrawal')return 'May generate later re-participation';
if(meta.bucket==='designated_amount')return 'Can restore lifetime room / reduce excess';
if(meta.bucket==='excluded_transfer')return 'Room-neutral FHSA transfer';
if(meta.bucket==='excluded_withdrawal')return 'Excluded withdrawal';
return 'Ignored / review';
}
function buildDrillTxnTable(plan,rows){
if(!rows.length)return '<p class="panel-sub">No included rows were found for the driver year behind this CRA snapshot.</p>';
const shown=rows.slice(0,30);
const body=shown.map(r=>`<tr><td>${escapeHtml(r.d||'')}</td><td>${escapeHtml(r.inst||'')}</td><td>${escapeHtml(r.acct||'')}</td><td>${escapeHtml(r.type||'')}</td><td>${escapeHtml(F(r.amt))}</td><td>${escapeHtml(buildTxnImpactText(plan,r))}</td></tr>`).join('');
const note=rows.length>shown.length?`<div class="panel-sub" style="margin-top:8px">Showing the first ${shown.length} of ${rows.length} included driver-year row(s).</div>`:'';
return `<div class="drill-table-wrap"><table class="mobile-stack"><thead><tr><th>Date</th><th>Institution</th><th>Account</th><th>Type</th><th>Amount</th><th>Why it matters</th></tr></thead><tbody>${body}</tbody></table></div>${note}`;
}
function buildTfsaCraDrilldown(tfsa,snapshot){
const year=+snapshot.year||0;if(!year)return '';
const current=tfsa.years&&tfsa.years[year]||{};
const prior=tfsa.years&&tfsa.years[year-1]||{};
const ledger=safeNum(current.openRoom), cra=safeNum(snapshot.amount), diff=ledger-cra;
const state=Math.abs(diff)<=0.005?'match':(Math.abs(diff)<=250?'warn':'alert');
const rows=tT.map(t=>({d:String(t.d||''),inst:t.inst||'',acct:t.acct||'',type:normalizeTfsaType(t.type),amt:safeNum(t.amt),treat:normalizeFlag(t.treat,'Include'),note:t.note||''})).filter(r=>r.treat==='Include'&&String(r.d||'').startsWith(String(year-1))).sort(sortTxnsAsc);
const contributions=rows.filter(r=>r.type==='Contribution').reduce((s,r)=>s+safeNum(r.amt),0);
const withdrawals=rows.filter(r=>r.type==='Withdrawal').reduce((s,r)=>s+safeNum(r.amt),0);
const neutralTransfers=rows.filter(r=>r.type==='Transfer In'||r.type==='Transfer Out').reduce((s,r)=>s+safeNum(r.amt),0);
const hint=Math.abs(diff)<=0.005?'The ledger and saved CRA room match for this snapshot.':'The delta usually comes from a missing, duplicated, or mis-dated TFSA contribution / withdrawal before January 1 of the snapshot year, or from a start-year configuration mismatch.';
return `<div class="drill-card ${state}"><div class="panel-head"><div><h3 class="panel-title">TFSA discrepancy drill-down • ${escapeHtml(String(year))}</h3><div class="panel-sub">Only included rows dated in <b>${year-1}</b> are shown because they drive the TFSA opening room for <b>${year}</b>.</div></div><div class="panel-head-actions"><button type="button" onclick="showView('tfsa')">Open TFSA</button><button type="button" onclick="showView('annual')">Open Annual</button></div></div><div class="drill-kpis"><div class="drill-kpi"><div class="eyebrow">Modeled formula</div><div class="value">${F(ledger)}</div><div class="sub">max(0, prior net room ${F(prior.netRoom)} + withdrawal addback ${F(prior.addbackWD)} + ${year} limit ${F(current.limit)})</div></div><div class="drill-kpi"><div class="eyebrow">Saved CRA room</div><div class="value">${F(cra)}</div><div class="sub">Reference snapshot for the start of ${year}</div></div><div class="drill-kpi"><div class="eyebrow">Delta</div><div class="value">${diff>0?'+':''}${F(diff)}</div><div class="sub">Ledger minus saved CRA room</div></div><div class="drill-kpi"><div class="eyebrow">Driver-year totals</div><div class="value">${F(contributions)}</div><div class="sub">Contributions in ${year-1}; withdrawals ${F(withdrawals)} • neutral transfers ${F(neutralTransfers)}</div></div></div><div class="drill-callout ${state==='match'?'':'warn'}">${hint}</div>${buildDrillTxnTable('TFSA',rows)}</div>`;
}
function buildFhsaCraDrilldown(fhsa,snapshot){
const year=+snapshot.year||0;if(!year)return '';
const current=fhsa.years&&fhsa.years[year]||{};
const ledger=safeNum(current.participationRoom), cra=safeNum(snapshot.amount), diff=ledger-cra;
const state=Math.abs(diff)<=0.005?'match':(Math.abs(diff)<=250?'warn':'alert');
const rows=fT.map((t,i)=>ensureTxnIdentity('FHSA',{d:String(t.d||''),inst:t.inst||'',acct:t.acct||'',type:normalizeFhsaType(t.type)||'Unknown',amt:safeNum(t.amt),status:normalizeFlag(t.status,'Include'),note:t.note||'',id:t.id,seq:t.seq},i+1)).filter(r=>r.status==='Include'&&String(r.d||'').startsWith(String(year-1))).sort(sortTxnsAsc);
const counted=rows.filter(r=>fhsaTypeMeta(r.type).bucket==='counted_inflow').reduce((s,r)=>s+safeNum(r.amt),0);
const taxable=rows.filter(r=>fhsaTypeMeta(r.type).bucket==='taxable_withdrawal').reduce((s,r)=>s+safeNum(r.amt),0);
const designated=rows.filter(r=>fhsaTypeMeta(r.type).bucket==='designated_amount').reduce((s,r)=>s+safeNum(r.amt),0);
const transfers=rows.filter(r=>fhsaTypeMeta(r.type).bucket==='excluded_transfer').reduce((s,r)=>s+safeNum(r.amt),0);
const hint=Math.abs(diff)<=0.005?'The ledger and saved CRA FHSA room match for this snapshot.':'The biggest causes of FHSA drift are duplicate counted inflows, a direct FHSA transfer classified as a contribution, an opening-year mismatch, or a missing taxable / designated withdrawal history.';
return `<div class="drill-card ${state}"><div class="panel-head"><div><h3 class="panel-title">FHSA discrepancy drill-down • ${escapeHtml(String(year))}</h3><div class="panel-sub">The driver year is <b>${year-1}</b>. Direct FHSA-to-FHSA transfers should remain room-neutral.</div></div><div class="panel-head-actions"><button type="button" onclick="showView('fhsa')">Open FHSA</button><button type="button" onclick="showView('annual')">Open Annual</button></div></div><div class="drill-kpis"><div class="drill-kpi"><div class="eyebrow">Participation room</div><div class="value">${F(ledger)}</div><div class="sub">Annual component ${F(current.annualComponent)} + prior re-participation ${F(current.reParticipationPrior)} • carryforward ${F(current.carryforward)}</div></div><div class="drill-kpi"><div class="eyebrow">Saved CRA room</div><div class="value">${F(cra)}</div><div class="sub">Reference snapshot for the start of ${year}</div></div><div class="drill-kpi"><div class="eyebrow">Delta</div><div class="value">${diff>0?'+':''}${F(diff)}</div><div class="sub">Ledger minus saved CRA room</div></div><div class="drill-kpi"><div class="eyebrow">Driver-year buckets</div><div class="value">${F(counted)}</div><div class="sub">Counted inflows • taxable ${F(taxable)} • designated ${F(designated)} • direct transfers ${F(transfers)}</div></div></div><div class="drill-callout ${state==='match'?'':'alert'}">${hint}</div>${buildDrillTxnTable('FHSA',rows)}</div>`;
}
function buildCraDrilldownPanel(tfsa,fhsa){
const snaps=(uiPrefs&&uiPrefs.craSnapshots)||{};
const sections=[];
if(snaps.tfsa&&snaps.tfsa.year)sections.push(buildTfsaCraDrilldown(tfsa,snaps.tfsa));
if(snaps.fhsa&&snaps.fhsa.year)sections.push(buildFhsaCraDrilldown(fhsa,snaps.fhsa));
if(!sections.length)return '';
return `<div class="panel mt-lg"><h3 class="panel-title">CRA discrepancy drill-down</h3><p class="panel-sub">This forensic view turns snapshot deltas into year-specific formulas and transaction-level driver tables so you can audit exactly which rows shape the CRA comparison.</p><div class="drill-stack">${sections.join('')}</div></div>`;
}
function setPostImportNotice(data){
uiPrefs=uiPrefs||clonePrefs();
uiPrefs.postImportNotice=Object.assign({createdAt:Date.now(),profile:getActiveProfileLabel()},data||{});
}
function dismissPostImportNotice(){
uiPrefs=uiPrefs||clonePrefs();
uiPrefs.postImportNotice=null;
save();
render();
}
function buildPostImportNotice(){
const notice=uiPrefs&&uiPrefs.postImportNotice;
if(!notice)return '';
const parts=[];
if(notice.imported!==undefined)parts.push(`<b>${notice.imported}</b> row(s) imported`);
if(notice.skippedDuplicates)parts.push(`<b>${notice.skippedDuplicates}</b> duplicate row(s) skipped`);
if(notice.reviewRows)parts.push(`<b>${notice.reviewRows}</b> review row(s) flagged`);
if(notice.futureWarnings)parts.push(`<b>${notice.futureWarnings}</b> future-date warning(s)`);
if(notice.snapshotCount)parts.push(`<b>${notice.snapshotCount}</b> CRA snapshot(s) saved`);
return `<div class="note-box recon-banner"><h3>Reconcile this import before relying on the dashboard</h3><p><b>Source:</b> ${escapeHtml(notice.source||'Imported data')}${notice.fileName?` • <b>File:</b> ${escapeHtml(notice.fileName)}`:''}</p><p>${parts.join(' • ')||'Import activity recorded.'}</p><p class="note-inline">After any non-trivial import, compare the resulting room and annual totals against CRA My Account and your institution exports. Use <b>Insights</b> for reconciliation and <b>Export JSON</b> for a backup checkpoint.</p><div class="recon-banner-actions"><button type="button" onclick="showView('insights')">Open Insights</button><button type="button" onclick="exportJSON()">Export Backup</button><button type="button" onclick="dismissPostImportNotice()">Dismiss</button></div></div>`;
}
function normalizeTfsaType(v,opts){
const strict=!!(opts&&opts.strict);
const s=String(v||'Contribution').trim().toLowerCase();
const map={
'c':'Contribution','contribution':'Contribution','contribute':'Contribution',
'w':'Withdrawal','withdrawal':'Withdrawal','withdraw':'Withdrawal',
'transfer in':'Transfer In','transfer_in':'Transfer In','xfer in':'Transfer In','tfsa direct transfer in':'Transfer In',
'transfer out':'Transfer Out','transfer_out':'Transfer Out','xfer out':'Transfer Out','tfsa direct transfer out':'Transfer Out'
};
const resolved=map[s];
if(resolved) return resolved;
return strict?'':'Contribution';
}
function normalizeFhsaType(v,opts){
const strict=!!(opts&&opts.strict);
const raw=String(v||'Contribution').trim();
const s=raw.toLowerCase();
const map={
'contribution':'Contribution','c':'Contribution',
'rrsp transfer in':'RRSP Transfer In','rrsp transfer':'RRSP Transfer In','rrsp_transfer_in':'RRSP Transfer In','rrsp→fhsa transfer':'RRSP Transfer In',
'transfer in':'Transfer In',
'withdrawal':'Taxable Withdrawal','taxable withdrawal':'Taxable Withdrawal',
'designated withdrawal':'Designated Withdrawal','designated transfer out':'Designated Transfer Out',
'fhsa direct transfer in':'FHSA Direct Transfer In','direct transfer in':'FHSA Direct Transfer In','fhsa transfer in':'FHSA Direct Transfer In',
'transfer out':'Transfer Out',
'fhsa direct transfer out':'FHSA Direct Transfer Out','direct transfer out':'FHSA Direct Transfer Out','fhsa transfer out':'FHSA Direct Transfer Out',
'qualifying withdrawal':'Qualifying Withdrawal'
};
const resolved=map[s];
if(resolved) return resolved;
return strict?'':(raw||'Contribution');
}
function normalizeFlag(v, fallback){
const s=String(v||fallback||'Include').trim().toLowerCase();
if(s==='exclude') return 'Exclude';
if(s==='review') return 'Review';
return 'Include';
}
function fhsaTypeMeta(type){
const t=String(type||'Contribution');
if(t==='Contribution') return {bucket:'counted_inflow',pill:'pill-c',amountClass:'green',label:t,warning:false};
if(t==='RRSP Transfer In') return {bucket:'counted_inflow',pill:'pill-fhsa',amountClass:'green',label:t,warning:false};
if(t==='Transfer In') return {bucket:'counted_inflow',pill:'pill-fhsa',amountClass:'green',label:'Transfer In',warning:true,warningText:'Legacy "Transfer In" treated as RRSP transfer. Reclassify if FHSA-to-FHSA direct transfer.'};
if(t==='Taxable Withdrawal') return {bucket:'taxable_withdrawal',pill:'pill-w',amountClass:'red',label:t,warning:false};
if(t==='Designated Withdrawal') return {bucket:'designated_amount',pill:'pill-w',amountClass:'red',label:t,warning:false};
if(t==='Designated Transfer Out') return {bucket:'designated_amount',pill:'pill-w',amountClass:'red',label:t,warning:false};
if(t==='FHSA Direct Transfer In') return {bucket:'excluded_transfer',pill:'pill-fhsa',amountClass:'blue',label:t,warning:false};
if(t==='FHSA Direct Transfer Out') return {bucket:'excluded_transfer',pill:'pill-fhsa',amountClass:'blue',label:t,warning:false};
if(t==='Transfer Out') return {bucket:'excluded_transfer',pill:'pill-fhsa',amountClass:'blue',label:'Transfer Out',warning:true,warningText:'Legacy "Transfer Out" treated as FHSA direct transfer. Reclassify if designated transfer.'};
if(t==='Qualifying Withdrawal') return {bucket:'excluded_withdrawal',pill:'pill-w',amountClass:'red',label:t,warning:false};
return {bucket:'unknown',pill:'pill-w',amountClass:'gold',label:t||'Unknown',warning:true,warningText:'Unknown type — ignored for room calculations.'};
}
function tfsaTypeMeta(type){
if(type==='Contribution') return {pill:'pill-c',amountClass:'green',label:'Contribution'};
if(type==='Withdrawal') return {pill:'pill-w',amountClass:'red',label:'Withdrawal'};
if(type==='Transfer In') return {pill:'pill-t',amountClass:'purple',label:'Transfer In'};
if(type==='Transfer Out') return {pill:'pill-t',amountClass:'purple',label:'Transfer Out'};
if(type==='Unknown') return {pill:'pill-w',amountClass:'gold',label:'Unknown'};
return {pill:'pill-c',amountClass:'green',label:type};
}