-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2561 lines (2188 loc) · 80.8 KB
/
Copy pathscript.js
File metadata and controls
2561 lines (2188 loc) · 80.8 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
// LocalStorage Keys
const STORAGE_KEY = "emi_tracker_data";
const SORT_PREFS_KEY = "emi_tracker_sort_prefs";
const ARCHIVED_KEY = "emi_tracker_archived";
const SEAL_STATE_KEY = "emi_tracker_seal_state";
// Global state
let searchQuery = "";
let showArchived = false;
let showPeriodic = false;
let periodicFreqFilter = 'all'; // 'all' | 'quarterly' | 'halfyearly' | 'yearly' | 'custom'
let isSealCountdownActive = false;
let sealCountdownTimer = null;
let undoGracePeriodTimer = null;
let lastSealedItems = []; // Track items sealed in current seal operation
let previousSealState = null; // Store seal state before adding new items (for UNDO)
// Get current month in YYYY-MM format
function getCurrentMonth() {
const now = new Date();
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
}
// ========== PERIODIC PAYMENT HELPERS ==========
const AVG_DAYS_PER_MONTH = 30.44; // Average days per calendar month
// Convert frequency preset to days
function frequencyToDays(frequency, customValue, customUnit) {
switch (frequency) {
case 'monthly': return null;
case 'quarterly': return 90;
case 'halfyearly': return 180;
case 'yearly': return 365;
case 'custom':
if (customUnit === 'months') return Math.round(parseFloat(customValue) * AVG_DAYS_PER_MONTH);
if (customUnit === 'days') return parseInt(customValue);
return null;
default: return null;
}
}
// Get human-readable frequency label
function getFrequencyLabel(frequency, frequencyDays) {
switch (frequency) {
case 'monthly': return 'Monthly';
case 'quarterly': return 'Every 3 months';
case 'halfyearly': return 'Every 6 months';
case 'yearly': return 'Yearly';
case 'custom': return `Every ${frequencyDays} days`;
default: return 'Monthly';
}
}
// Calculate next due date
function calculateNextDueDate(fromDateStr, frequencyDays) {
const date = new Date(fromDateStr);
date.setDate(date.getDate() + frequencyDays);
return date.toISOString().split('T')[0];
}
// Check if a periodic item is currently due (nextDueDate <= today)
function isPeriodicItemDue(emi) {
if (!emi.paymentFrequency || emi.paymentFrequency === 'monthly') return true;
const today = new Date();
today.setHours(0, 0, 0, 0);
const nextDue = new Date(emi.nextDueDate);
nextDue.setHours(0, 0, 0, 0);
return today >= nextDue;
}
// Check if periodic item is paid in its current cycle
function isPaidInCurrentCycle(emi) {
if (!emi.paymentFrequency || emi.paymentFrequency === 'monthly') {
return emi.isPaidThisMonth && emi.currentMonth === getCurrentMonth();
}
return emi.isPaidThisCycle === true && emi.currentCycleId === emi.nextDueDate;
}
// Toggle visibility of frequency-related form fields
function toggleFrequencyFields() {
const selected = document.querySelector('input[name="paymentFrequency"]:checked');
if (!selected) return;
const freq = selected.value;
const customFields = document.getElementById('customFrequencyFields');
const cycleStartGroup = document.getElementById('cycleStartGroup');
const dueDateGroup = document.getElementById('dueDateGroup');
const amountLabel = document.getElementById('amountLabel');
if (freq === 'monthly') {
customFields.style.display = 'none';
cycleStartGroup.style.display = 'none';
dueDateGroup.style.display = 'block';
// Re-enable dueDate required validation
const dueDateInput = document.getElementById('dueDate');
if (dueDateInput) dueDateInput.required = true;
if (amountLabel) amountLabel.innerHTML = 'Monthly Amount (₹) <span class="required">*</span>';
} else {
customFields.style.display = freq === 'custom' ? 'block' : 'none';
cycleStartGroup.style.display = 'block';
dueDateGroup.style.display = 'none';
// Disable dueDate required validation since it's hidden
const dueDateInput = document.getElementById('dueDate');
if (dueDateInput) { dueDateInput.required = false; dueDateInput.value = ''; }
if (amountLabel) amountLabel.innerHTML = 'Payment Amount (₹) <span class="required">*</span>';
}
// Update cycle preview
updateCyclePreview();
}
// Update the cycle preview text based on selected frequency and start date
function updateCyclePreview() {
const selected = document.querySelector('input[name="paymentFrequency"]:checked');
if (!selected || selected.value === 'monthly') return;
const freq = selected.value;
const cycleStartDateVal = document.getElementById('cycleStartDate').value;
const preview = document.getElementById('cyclePreview');
if (!cycleStartDateVal || !preview) return;
const customValue = document.getElementById('customFreqValue').value;
const customUnitEl = document.querySelector('input[name="customFreqUnit"]:checked');
const customUnit = customUnitEl ? customUnitEl.value : 'days';
const days = frequencyToDays(freq, customValue, customUnit);
if (days && days > 0) {
const nextDate = calculateNextDueDate(cycleStartDateVal, days);
const formatted = formatDate(nextDate);
preview.textContent = `Next due: ${formatted}`;
preview.style.display = 'block';
} else {
preview.textContent = '';
preview.style.display = 'none';
}
}
// Render the periodic payments summary section
function renderPeriodicSummary(periodicItems) {
const section = document.getElementById('periodicPaymentsSection');
if (!section) return;
if (!periodicItems || periodicItems.length === 0) {
section.style.display = 'none';
return;
}
section.style.display = 'block';
const dueNow = periodicItems.filter(emi => isPeriodicItemDue(emi) && !isPaidInCurrentCycle(emi));
const paidCycle = periodicItems.filter(emi => isPaidInCurrentCycle(emi));
const upcoming = periodicItems.filter(emi => !isPeriodicItemDue(emi));
const dueTotal = dueNow.reduce((s, e) => s + parseFloat(e.emiAmount || 0), 0);
let html = '';
if (dueNow.length > 0) {
html += `<div class="periodic-group-label">Due Now</div>`;
dueNow.forEach(emi => {
const freqLabel = getFrequencyLabel(emi.paymentFrequency, emi.frequencyDays);
const nextDueFormatted = formatDate(emi.nextDueDate);
html += `<div class="periodic-item due-now">
<div class="periodic-item-info">
<span class="periodic-item-name">${emi.emiName}</span>
<span class="freq-badge">${freqLabel}</span>
<span class="periodic-item-due">Due: ${nextDueFormatted}</span>
</div>
<div class="periodic-item-amount">${formatCurrency(emi.emiAmount)}</div>
<span class="due-now-badge">Due!</span>
</div>`;
});
html += `<div class="periodic-due-total">Total due now: ${formatCurrency(dueTotal)}</div>`;
}
if (paidCycle.length > 0) {
html += `<div class="periodic-group-label">Paid This Cycle</div>`;
paidCycle.forEach(emi => {
const freqLabel = getFrequencyLabel(emi.paymentFrequency, emi.frequencyDays);
const nextDueFormatted = formatDate(emi.nextDueDate);
html += `<div class="periodic-item paid-cycle">
<div class="periodic-item-info">
<span class="periodic-item-name">${emi.emiName}</span>
<span class="freq-badge">${freqLabel}</span>
<span class="periodic-item-due">Cycle ends: ${nextDueFormatted}</span>
</div>
<div class="periodic-item-amount">${formatCurrency(emi.emiAmount)}</div>
<span class="paid-badge">✓ Paid</span>
</div>`;
});
}
if (upcoming.length > 0) {
html += `<div class="periodic-group-label">Upcoming</div>`;
upcoming.forEach(emi => {
const freqLabel = getFrequencyLabel(emi.paymentFrequency, emi.frequencyDays);
const nextDueFormatted = formatDate(emi.nextDueDate);
html += `<div class="periodic-item upcoming">
<div class="periodic-item-info">
<span class="periodic-item-name">${emi.emiName}</span>
<span class="freq-badge">${freqLabel}</span>
<span class="periodic-item-due">Next due: ${nextDueFormatted}</span>
</div>
<div class="periodic-item-amount">${formatCurrency(emi.emiAmount)}</div>
</div>`;
});
}
document.getElementById('periodicPaymentsList').innerHTML = html;
}
// Toggle form fields based on type selection
function toggleFormFields() {
const isEMI = document.getElementById("typeEMI").checked;
const emiOnlyFields = document.getElementById("emiOnlyFields");
const endDateInput = document.getElementById("emiEndDate");
const endDateRequired = document.getElementById("endDateRequired");
const endDateHelper = document.getElementById("endDateHelper");
const endDateGroup = document.getElementById("endDateGroup");
const nameInput = document.getElementById("emiName");
const nameLabel = document.getElementById("nameLabel");
const amountLabel = document.getElementById("amountLabel");
const endDateLabel = document.getElementById("endDateLabel");
const categoryExpenseOption = document.getElementById(
"categoryExpenseOption"
);
if (isEMI) {
// EMI mode
categoryExpenseOption.textContent = "Loan/Debt";
endDateInput.required = true;
endDateRequired.style.display = "inline";
endDateHelper.style.display = "none";
endDateGroup.style.display = "block";
nameInput.placeholder = "e.g., Home Loan, Car EMI, SIP, RD";
nameLabel.innerHTML = 'Name <span class="required">*</span>';
amountLabel.innerHTML =
'Monthly Amount (₹) <span class="required">*</span>';
endDateLabel.innerHTML =
'End Date <span class="required" id="endDateRequired">*</span>';
// Check category to show/hide EMI Details
toggleCategoryFields();
} else {
// Constant Expense mode
emiOnlyFields.classList.remove("active");
categoryExpenseOption.textContent = "Expense";
endDateInput.required = false;
endDateRequired.style.display = "none";
endDateHelper.style.display = "none";
endDateGroup.style.display = "none";
nameInput.placeholder = "e. g., Rent, Utilities, SIP, Insurance";
nameLabel.innerHTML = 'Name <span class="required">*</span>';
amountLabel.innerHTML =
'Monthly Amount (₹) <span class="required">*</span>';
// Clear EMI-only fields
document.getElementById("totalAmount").value = "";
document.getElementById("principalPaid").value = "";
document.getElementById("interestPaid").value = "";
document.getElementById("emiEndDate").value = "";
}
}
// Toggle category-specific fields
function toggleCategoryFields() {
const isEMI = document.getElementById("typeEMI").checked;
const category = document.getElementById("emiCategory").value;
const emiOnlyFields = document.getElementById("emiOnlyFields");
// Only show EMI Details for EMI type with Expense/Debt category
if (isEMI && category === "expense") {
emiOnlyFields.classList.add("active");
} else {
emiOnlyFields.classList.remove("active");
// Clear fields when hiding
if (category === "savings") {
document.getElementById("totalAmount").value = "";
document.getElementById("principalPaid").value = "";
document.getElementById("interestPaid").value = "";
}
}
}
// Load EMIs from localStorage
function loadEMIs() {
const data = localStorage.getItem(STORAGE_KEY);
return data ? JSON.parse(data) : [];
}
// Save EMIs to localStorage
function saveEMIs(emis) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(emis));
}
// Load archived items
function loadArchived() {
const data = localStorage.getItem(ARCHIVED_KEY);
return data ? JSON.parse(data) : [];
}
// Save archived items
function saveArchived(archived) {
localStorage.setItem(ARCHIVED_KEY, JSON.stringify(archived));
}
// ========== SEAL STATE MANAGEMENT ==========
// Load seal state from localStorage
function loadSealState() {
const data = localStorage.getItem(SEAL_STATE_KEY);
return data ? JSON.parse(data) : {
isSealed: false,
sealedMonth: null,
sealedDate: null,
sealedItems: []
};
}
// Save seal state to localStorage
function saveSealState(state) {
localStorage.setItem(SEAL_STATE_KEY, JSON.stringify(state));
}
// Check if current month is sealed
function isSealedThisMonth() {
const sealState = loadSealState();
const currentMonth = getCurrentMonth();
return sealState.isSealed && sealState.sealedMonth === currentMonth;
}
// Check if sealing process is currently active (countdown or undo period)
function isSealingInProgress() {
return sealCountdownTimer !== null || undoGracePeriodTimer !== null;
}
// Check if a specific item was sealed (not just if month is sealed)
function wasItemSealed(emi) {
const sealState = loadSealState();
const currentMonth = getCurrentMonth();
if (!sealState.isSealed || sealState.sealedMonth !== currentMonth) {
return false;
}
// Check if this item exists in the sealed snapshot
return sealState.sealedItems.some(sealed => {
const nameMatch = sealed.emiName === emi.emiName;
const amountMatch = sealed.emiAmount === emi.emiAmount;
const isPeriodicItem = emi.paymentFrequency && emi.paymentFrequency !== 'monthly';
if (isPeriodicItem) {
return nameMatch && amountMatch && sealed.nextDueDate === emi.nextDueDate;
}
return nameMatch && amountMatch && sealed.dueDate === emi.dueDate;
});
}
// Check if all current active items are sealed
function areAllActiveItemsSealed() {
const emis = loadEMIs();
const sealState = loadSealState();
const currentMonth = getCurrentMonth();
if (!sealState.isSealed || sealState.sealedMonth !== currentMonth) {
return false;
}
const today = new Date();
const activeItems = emis.filter(emi => {
if (emi.emiEndDate) {
const endDate = new Date(emi.emiEndDate);
return endDate >= today;
}
return true;
});
if (activeItems.length === 0) return false;
// Check if ALL active items are in sealed list
return activeItems.every(emi => wasItemSealed(emi));
}
// Check if seal button should be enabled (at least 1 payment checked)
function checkSealButtonState() {
const emis = loadEMIs();
const currentMonth = getCurrentMonth();
// Filter active items only
const today = new Date();
const activeItems = emis.filter(emi => {
if (emi.emiEndDate) {
const endDate = new Date(emi.emiEndDate);
return endDate >= today;
}
return true; // Ongoing items
});
// No items?
if (activeItems.length === 0) {
return { enabled: false, reason: "No active items to seal" };
}
// Find unsealed items (items not in the sealed snapshot)
const unsealedItems = activeItems.filter(emi => !wasItemSealed(emi));
if (unsealedItems.length === 0) {
// All items already sealed
return { enabled: false, reason: "All items already sealed" };
}
// Check if at least one UNSEALED item is paid
const unsealedPaidItems = unsealedItems.filter(emi => {
if (!emi.paymentFrequency || emi.paymentFrequency === 'monthly') {
return emi.isPaidThisMonth && emi.currentMonth === currentMonth;
}
// Periodic: paid this cycle AND currently due
return emi.isPaidThisCycle && isPeriodicItemDue(emi);
});
if (unsealedPaidItems.length === 0) {
return { enabled: false, reason: "Check at least one payment to enable" };
}
return { enabled: true, reason: "" };
}
// Get next month's first date
function getNextMonthDate() {
const now = new Date();
const nextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
return `${monthNames[nextMonth.getMonth()]} ${nextMonth.getDate()}, ${nextMonth.getFullYear()}`;
}
// Check and unlock if new month started
function checkAndUnlockNewMonth() {
const sealState = loadSealState();
const currentMonth = getCurrentMonth();
if (sealState.isSealed && sealState.sealedMonth !== currentMonth) {
// New month - unlock!
saveSealState({
isSealed: false,
sealedMonth: null,
sealedDate: null,
sealedItems: []
});
removeSealedUI();
// Show toast
const toast = document.getElementById("paymentToast");
toast.textContent = "🎊 New month started! Payment status reset.";
toast.classList.add("show");
setTimeout(() => toast.classList.remove("show"), 4000);
}
}
// ========== SEAL WORKFLOW FUNCTIONS ==========
// Update seal button state (enabled/disabled)
function updateSealButton() {
const btn = document.getElementById('sealControlBtn');
const state = checkSealButtonState();
if (state.enabled) {
btn.disabled = false;
btn.title = "Lock all payments for this month";
} else {
btn.disabled = true;
btn.title = state.reason;
}
}
// Step 1: User clicks "SEAL MONTH" button
function initiateSeal() {
const modal = document.getElementById('sealModal');
const nextMonth = getNextMonthDate();
document.getElementById('sealUntilDate').textContent = `📅 ${nextMonth}`;
modal.classList.add('active');
}
// Close seal confirmation modal
function closeSealModal() {
const modal = document.getElementById('sealModal');
modal.classList.remove('active');
}
// Step 2: User confirms - start countdown
function confirmSeal() {
closeSealModal();
startSealCountdown();
}
// Step 3: 3-second countdown with abort option
function startSealCountdown() {
isSealCountdownActive = true;
let countdown = 3;
const toast = document.getElementById('countdownToast');
const text = document.getElementById('countdownText');
const overlay = document.getElementById('sealingOverlay');
// Show overlay to disable background
overlay.classList.add('active');
toast.classList.add('show');
text.textContent = `⏳ Sealing... (${countdown}s)`;
sealCountdownTimer = setInterval(() => {
countdown--;
text.textContent = `⏳ Sealing... (${countdown}s)`;
if (countdown <= 0) {
clearInterval(sealCountdownTimer);
sealCountdownTimer = null;
toast.classList.remove('show');
// Keep overlay active for undo period
executeSeal();
}
}, 1000);
}
// Abort seal during countdown
function abortSeal() {
if (sealCountdownTimer) {
clearInterval(sealCountdownTimer);
sealCountdownTimer = null;
}
isSealCountdownActive = false;
const toast = document.getElementById('countdownToast');
const overlay = document.getElementById('sealingOverlay');
toast.classList.remove('show');
overlay.classList.remove('active'); // Hide overlay
}
// Step 4: Execute seal and start grace period
function executeSeal() {
const emis = loadEMIs();
const currentMonth = getCurrentMonth();
const existingSealState = loadSealState();
// Store previous seal state for UNDO functionality
previousSealState = JSON.parse(JSON.stringify(existingSealState));
// Get existing sealed items or empty array
const existingSealedItems = (existingSealState.isSealed && existingSealState.sealedMonth === currentMonth)
? existingSealState.sealedItems
: [];
// Add new items to sealed list (only unsealed AND PAID ones)
const newItemsToSeal = emis
.filter(emi => {
if (!wasItemSealed(emi)) {
// Monthly items
if (!emi.paymentFrequency || emi.paymentFrequency === 'monthly') {
return emi.isPaidThisMonth && emi.currentMonth === currentMonth;
}
// Periodic items: paid this cycle AND currently due
return emi.isPaidThisCycle && isPeriodicItemDue(emi);
}
return false;
})
.map(emi => ({
emiName: emi.emiName,
emiAmount: emi.emiAmount,
dueDate: emi.dueDate,
nextDueDate: emi.nextDueDate || null,
paymentFrequency: emi.paymentFrequency || 'monthly'
}));
// Combine existing sealed items with new ones
const allSealedItems = [...existingSealedItems, ...newItemsToSeal];
// Store newly sealed items for finalizeSeal message
lastSealedItems = newItemsToSeal;
const sealState = {
isSealed: true,
sealedMonth: currentMonth,
sealedDate: new Date().toISOString(),
sealedItems: allSealedItems
};
saveSealState(sealState);
applySealedUI();
startUndoGracePeriod();
}
// Step 5: 5-second undo grace period
function startUndoGracePeriod() {
let countdown = 5;
const toast = document.getElementById('undoToast');
const text = document.getElementById('undoText');
const overlay = document.getElementById('sealingOverlay');
// Overlay should already be active from countdown
toast.classList.add('show');
text.textContent = `✅ Sealed! (${countdown}s)`;
undoGracePeriodTimer = setInterval(() => {
countdown--;
text.textContent = `✅ Sealed! (${countdown}s)`;
if (countdown <= 0) {
clearInterval(undoGracePeriodTimer);
undoGracePeriodTimer = null;
toast.classList.remove('show');
overlay.classList.remove('active'); // Hide overlay when done
finalizeSeal();
}
}, 1000);
}
// Undo seal during grace period
function undoSeal() {
if (undoGracePeriodTimer) {
clearInterval(undoGracePeriodTimer);
undoGracePeriodTimer = null;
}
const toast = document.getElementById('undoToast');
const overlay = document.getElementById('sealingOverlay');
toast.classList.remove('show');
overlay.classList.remove('active'); // Hide overlay
// Restore previous seal state (UNDO only the newly added items)
if (previousSealState) {
saveSealState(previousSealState);
previousSealState = null;
} else {
// Fallback: if no previous state, clear everything
saveSealState({
isSealed: false,
sealedMonth: null,
sealedDate: null,
sealedItems: []
});
}
removeSealedUI();
renderTable();
}
// Finalize seal after grace period
function finalizeSeal() {
const toast = document.getElementById('paymentToast');
// Check if ALL active items are now sealed
if (areAllActiveItemsSealed()) {
// All items sealed - show superToast for financial peace
const superToast = document.getElementById('superToast');
superToast.classList.add('show');
setTimeout(() => superToast.classList.remove('show'), 6000);
} else {
// Partial seal - show which items were sealed
if (lastSealedItems.length === 1) {
// Single item sealed
toast.textContent = `🔒 Sealed! Forget "${lastSealedItems[0].emiName}" this month`;
} else if (lastSealedItems.length === 2) {
// Two items sealed
toast.textContent = `🔒 Sealed! Forget "${lastSealedItems[0].emiName}" and "${lastSealedItems[1].emiName}" this month`;
} else {
// Multiple items sealed
const names = lastSealedItems.slice(0, 2).map(item => item.emiName).join('", "');
const remaining = lastSealedItems.length - 2;
toast.textContent = `🔒 Sealed! Forget "${names}" and ${remaining} more this month`;
}
toast.classList.add('show');
setTimeout(() => toast.classList.remove('show'), 5000);
}
// Clear last sealed items
lastSealedItems = [];
previousSealState = null;
}
// ========== SEAL UI TRANSFORMATIONS ==========
// Apply sealed UI state
function applySealedUI() {
const tableWrapper = document.getElementById('tableWrapper');
// Only show banner if ALL current items are sealed
if (areAllActiveItemsSealed()) {
tableWrapper.classList.add('sealed');
} else {
tableWrapper.classList.remove('sealed');
}
renderTable(); // Re-render with locks
}
// Remove sealed UI state
function removeSealedUI() {
const tableWrapper = document.getElementById('tableWrapper');
const badge = document.getElementById('sealedBadge');
tableWrapper.classList.remove('sealed');
badge.style.display = 'none'; // Ensure badge is hidden
}
// Check and auto-archive completed items
function autoArchiveCompleted() {
const emis = loadEMIs();
const exportBtn = document.getElementById("export");
const archived = loadArchived();
if (exportBtn) {
if (emis.length === 0 && archived.length === 0) {
exportBtn.disabled = true;
} else {
exportBtn.disabled = false;
}
}
const today = new Date();
today.setHours(0, 0, 0, 0);
const stillActive = [];
let archived_count = 0;
emis.forEach((emi) => {
if (emi.emiEndDate) {
const endDate = new Date(emi.emiEndDate);
endDate.setHours(0, 0, 0, 0);
if (endDate < today) {
// Archive this item
archived.push({
...emi,
archivedDate: new Date().toISOString(),
});
archived_count++;
} else {
stillActive.push(emi);
}
} else {
stillActive.push(emi);
}
});
if (archived_count > 0) {
saveEMIs(stillActive);
saveArchived(archived);
}
}
// Switch between Monthly, Periodic, and Archive views
function switchView(view) {
// Reset all states
showArchived = false;
showPeriodic = false;
// Set active state
if (view === 'archive') showArchived = true;
if (view === 'periodic') showPeriodic = true;
// Update button active states
document.getElementById('viewBtnMonthly').classList.toggle('active', view === 'monthly');
document.getElementById('viewBtnPeriodic').classList.toggle('active', view === 'periodic');
document.getElementById('viewBtnArchive').classList.toggle('active', view === 'archive');
// Show/hide frequency filter (only visible in Periodic view)
const freqFilter = document.getElementById('periodicFreqFilter');
if (freqFilter) freqFilter.style.display = view === 'periodic' ? 'flex' : 'none';
// Show/hide archive mode styling
const tableWrapper = document.getElementById('tableWrapper');
if (view === 'archive') {
tableWrapper.classList.add('archive-mode');
} else {
tableWrapper.classList.remove('archive-mode');
}
// Restore monthly summary labels when switching to monthly view
if (view === 'monthly') {
const totalEMIsCard = document.getElementById('totalEMIs');
if (totalEMIsCard) totalEMIsCard.closest('.summary-card').querySelector('.summary-label').textContent = 'Total Items';
const totalMonthlyCard = document.getElementById('totalMonthly');
if (totalMonthlyCard) totalMonthlyCard.closest('.summary-card').querySelector('.summary-label').textContent = 'Monthly Payment';
const totalDebtCard = document.getElementById('totalDebt');
if (totalDebtCard) totalDebtCard.closest('.summary-card').querySelector('.summary-label').textContent = 'Total Debt';
const freedomCard = document.getElementById('freedomCard');
if (freedomCard) freedomCard.style.display = '';
}
renderTable();
}
// Toggle archived view (kept for backward compatibility)
function toggleArchivedView() {
switchView(showArchived ? 'monthly' : 'archive');
}
// Set periodic frequency filter
function setPeriodicFilter(freq) {
periodicFreqFilter = freq;
// Update active button state
document.querySelectorAll('.freq-filter-btn').forEach(btn => {
btn.classList.toggle('active', btn.dataset.freq === freq);
});
renderTable();
}
// Mark item as paid
function markAsPaid(index) {
if (isSealingInProgress()) {
return; // Silently block when sealing in progress
}
const emis = loadEMIs();
// Block if THIS specific item is sealed
if (wasItemSealed(emis[index])) {
return; // Can't mark a sealed item
}
const emi = emis[index];
// PERIODIC ITEM
if (emi.paymentFrequency && emi.paymentFrequency !== 'monthly') {
if (!emi.isPaidThisCycle) {
emis[index].isPaidThisCycle = true;
emis[index].currentCycleId = emi.nextDueDate;
saveEMIs(emis);
const toast = document.getElementById("paymentToast");
const category = emi.emiCategory || "expense";
toast.textContent = category === "savings" ? "Thanks for Saving! 💰" : "Thanks for paying! 🎉";
toast.classList.add("show");
setTimeout(() => toast.classList.remove("show"), 3000);
checkAllPaidAndCelebrate();
renderTable();
}
return;
}
// MONTHLY ITEM — existing logic unchanged
const currentMonth = getCurrentMonth();
if (
!emis[index].isPaidThisMonth ||
emis[index].currentMonth !== currentMonth
) {
emis[index].isPaidThisMonth = true;
emis[index].currentMonth = currentMonth;
saveEMIs(emis);
// Get item category
const category = emis[index].emiCategory || "expense";
// Show toast based on category
const toast = document.getElementById("paymentToast");
if (category === "savings") {
toast.textContent = "Thanks for Saving! 💰";
} else {
toast.textContent = "Thanks for paying! 🎉";
}
toast.classList.add("show");
setTimeout(() => {
toast.classList.remove("show");
}, 3000);
// Check if all items are paid
checkAllPaidAndCelebrate();
renderTable();
}
}
// Check if all items are paid and show celebration
function checkAllPaidAndCelebrate() {
const emis = loadEMIs();
const currentMonth = getCurrentMonth();
if (emis.length === 0) return;
// Count active items (exclude completed/archived)
const today = new Date();
const activeItems = emis.filter((emi) => {
if (emi.emiEndDate) {
const endDate = new Date(emi.emiEndDate);
return endDate >= today;
}
return true; // Ongoing items
});
if (activeItems.length === 0) return;
// Filter to only UNSEALED items (so we don't count already sealed items)
const unsealedItems = activeItems.filter(emi => !wasItemSealed(emi));
if (unsealedItems.length === 0) return; // All items already sealed
// Count paid items among unsealed items
const paidItems = unsealedItems.filter((emi) => {
// Monthly
if (!emi.paymentFrequency || emi.paymentFrequency === 'monthly') {
return emi.isPaidThisMonth && emi.currentMonth === currentMonth;
}
// Periodic: only count if currently due
if (isPeriodicItemDue(emi)) {
return isPaidInCurrentCycle(emi);
}
return true; // Not yet due = doesn't block celebration
});
// All unsealed items paid?
if (paidItems.length === unsealedItems.length) {
const toast = document.getElementById("paymentToast");
toast.textContent = "🎉 Super! Now seal it to preserve from accidental touches, doubts and all";
toast.classList.add("show");
setTimeout(() => toast.classList.remove("show"), 5000); // Longer display
}
}
// Unmark item as paid
function unmarkAsPaid(index) {
if (isSealingInProgress()) {
return; // Silently block when sealing in progress
}
const emis = loadEMIs();
// Block if THIS specific item is sealed
if (wasItemSealed(emis[index])) {
return; // Can't unmark a sealed item
}
const emi = emis[index];
// PERIODIC ITEM
if (emi.paymentFrequency && emi.paymentFrequency !== 'monthly') {
emis[index].isPaidThisCycle = false;
saveEMIs(emis);
renderTable();
return;
}
// MONTHLY ITEM — existing logic unchanged
emis[index].isPaidThisMonth = false;
emis[index].currentMonth = "";
saveEMIs(emis);
renderTable();
}
// Handle search input
let searchTimeout;
function handleSearch() {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => {
searchQuery = document.getElementById("searchInput").value.toLowerCase();
renderTable();
}, 300);
}
// Filter items based on search
function filterBySearch(emis) {
if (!searchQuery) return emis;
return emis.filter((emi) => {
const nameMatch = emi.emiName.toLowerCase().includes(searchQuery);
const amountMatch = emi.emiAmount.toString().includes(searchQuery);
return nameMatch || amountMatch;
});
}
// Calculate period left for periodic (non-monthly) items — days to next due date
function calculatePeriodicPeriodLeft(emi) {
if (isPeriodicItemDue(emi)) {
return { text: "Due Now", class: "normal" };
}
const today = new Date();
today.setHours(0, 0, 0, 0);
const nextDue = new Date(emi.nextDueDate);
nextDue.setHours(0, 0, 0, 0);
const diffTime = nextDue - today;
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
const months = Math.floor(diffDays / 30);
const days = diffDays % 30;
let periodText = "";
if (months > 0) periodText += `${months}m `;
if (days > 0 || periodText === "") periodText += `${days}d`;
let statusClass = "normal";
if (diffDays <= 7) statusClass = "critical";