-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2124 lines (1819 loc) · 77 KB
/
Copy pathapp.js
File metadata and controls
2124 lines (1819 loc) · 77 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
/* ========================================
UNMESSIFY - Core Application Logic
======================================== */
// ==========================================
// CONSTANTS & CONFIGURATION
// ==========================================
const STORAGE_KEY = 'unmessify_state_v1';
const ITEM_PRICES = {
veg: { min: 30, max: 80 },
paneer: { min: 60, max: 120 },
chicken: { min: 80, max: 150 },
dessert: { min: 30, max: 60 },
beverage: { min: 20, max: 50 },
other: { min: 20, max: 100 }
};
// ==========================================
// DATA MODELS
// ==========================================
/**
* Create a new user profile
* @returns {Object} Default user profile
*/
function createDefaultProfile() {
const today = new Date();
const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
const daysInMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0).getDate();
return {
userType: 'hostel_student',
monthlyCredits: 6000,
monthDays: daysInMonth,
startDate: formatDate(startOfMonth),
preferences: {
riskTolerance: 'medium',
weekendBoost: false,
examMode: false,
maxSpendPerDay: null,
vegetarian: false,
notificationThresholds: {
warning: 0.7,
danger: 0.9
}
}
};
}
/**
* Create a new expense entry
* @param {Object} data - Expense data
* @returns {Object} Expense entry with generated ID
*/
function createExpenseEntry(data) {
return {
id: generateUUID(),
date: data.date,
mealType: data.mealType || 'lunch',
itemType: data.itemType || 'veg',
quantity: parseInt(data.quantity) || 1,
cost: parseFloat(data.cost) || 0,
notes: data.notes || null
};
}
/**
* Compute derived data from profile and expenses
* @param {Object} profile - User profile
* @param {Array} expenses - Array of expense entries
* @returns {Object} Derived data
*/
function computeDerivedData(profile, expenses) {
const today = new Date();
const todayStr = formatDate(today);
const startDate = new Date(profile.startDate);
const endDate = new Date(startDate);
endDate.setDate(endDate.getDate() + profile.monthDays - 1);
// Calculate days elapsed and remaining
const daysElapsed = Math.max(0, Math.floor((today - startDate) / (1000 * 60 * 60 * 24)) + 1);
const remainingDays = Math.max(0, profile.monthDays - daysElapsed);
// Calculate totals
const totalSpent = expenses.reduce((sum, exp) => sum + exp.cost, 0);
const remainingCredits = Math.max(0, profile.monthlyCredits - totalSpent);
// Calculate today's spend
const todayExpenses = expenses.filter(exp => exp.date === todayStr);
const todaySpend = todayExpenses.reduce((sum, exp) => sum + exp.cost, 0);
// Calculate burn rates
const burnRateOverall = daysElapsed > 0 ? totalSpent / daysElapsed : 0;
const burnRate7d = calculateBurnRateWindow(expenses, 7, startDate);
const burnRate3d = calculateBurnRateWindow(expenses, 3, startDate);
// Calculate target burn rate (ideal daily spend)
const targetBurnRate = profile.monthlyCredits / profile.monthDays;
// Calculate daily safe limit with adaptive logic
const dailySafeLimit = calculateDailySafeLimit(profile, expenses, {
remainingCredits,
remainingDays,
averageDailySpend: burnRateOverall,
targetBurnRate
});
// Predict exhaustion date
const { predictedExhaustionDate, daysUntilExhaustion } = predictExhaustionDate(
remainingCredits,
burnRate7d > 0 ? burnRate7d : burnRateOverall,
today,
endDate
);
// Calculate surplus or deficit at month end
const projectedTotalSpend = burnRateOverall * profile.monthDays;
const surplusOrDeficit = profile.monthlyCredits - projectedTotalSpend;
// Determine risk level
const riskLevel = determineRiskLevel(
totalSpent,
profile.monthlyCredits,
daysElapsed,
profile.monthDays,
daysUntilExhaustion,
remainingDays,
profile.preferences.notificationThresholds
);
// Ratios for display
const creditsUsedRatio = profile.monthlyCredits > 0 ? totalSpent / profile.monthlyCredits : 0;
const timeElapsedRatio = profile.monthDays > 0 ? daysElapsed / profile.monthDays : 0;
// Confidence level for predictions
const confidenceLevel = determineConfidenceLevel(expenses.length, daysElapsed);
return {
today: todayStr,
daysElapsed,
remainingDays,
totalSpent,
remainingCredits,
todaySpend,
dailySafeLimit,
averageDailySpend: burnRateOverall,
burnRate7d,
burnRate3d,
burnRateOverall,
targetBurnRate,
predictedExhaustionDate,
daysUntilExhaustion,
riskLevel,
surplusOrDeficit,
creditsUsedRatio,
timeElapsedRatio,
confidenceLevel,
endDate: formatDate(endDate)
};
}
// ==========================================
// CALCULATION FUNCTIONS
// ==========================================
/**
* Calculate burn rate for a specific window of days
*/
function calculateBurnRateWindow(expenses, windowDays, startDate) {
const today = new Date();
const windowStart = new Date(today);
windowStart.setDate(windowStart.getDate() - windowDays + 1);
// Ensure we don't go before the start date
const effectiveStart = windowStart > startDate ? windowStart : startDate;
const windowExpenses = expenses.filter(exp => {
const expDate = new Date(exp.date);
return expDate >= effectiveStart && expDate <= today;
});
const windowTotal = windowExpenses.reduce((sum, exp) => sum + exp.cost, 0);
const actualWindowDays = Math.max(1, Math.floor((today - effectiveStart) / (1000 * 60 * 60 * 24)) + 1);
return windowTotal / actualWindowDays;
}
/**
* Calculate adaptive daily safe limit
*/
function calculateDailySafeLimit(profile, expenses, derivedBase) {
const { remainingCredits, remainingDays, averageDailySpend, targetBurnRate } = derivedBase;
if (remainingDays <= 0) return 0;
// Base calculation: simple division
let base = remainingCredits / remainingDays;
// Adaptive adjustment: if spending higher than ideal, reduce limit
if (averageDailySpend > 0 && targetBurnRate > 0 && averageDailySpend > targetBurnRate) {
const overshootRatio = averageDailySpend / targetBurnRate;
// Apply a dampening factor (not full overshoot correction)
base = base / Math.pow(overshootRatio, 0.5);
}
// Apply risk tolerance factor
const toleranceFactors = {
low: 0.85,
medium: 1.0,
high: 1.1
};
const factor = toleranceFactors[profile.preferences.riskTolerance] || 1.0;
base = base * factor;
// Apply weekend boost if enabled and it's a weekend
const today = new Date();
const isWeekend = today.getDay() === 0 || today.getDay() === 6;
if (profile.preferences.weekendBoost && isWeekend) {
base = base * 1.15; // 15% boost on weekends
}
// Apply exam mode if enabled (slightly higher limit for snacks)
if (profile.preferences.examMode) {
base = base * 1.05;
}
// Apply user-defined cap if set
if (profile.preferences.maxSpendPerDay && profile.preferences.maxSpendPerDay > 0) {
base = Math.min(base, profile.preferences.maxSpendPerDay);
}
return Math.max(0, Math.round(base));
}
/**
* Predict credit exhaustion date
*/
function predictExhaustionDate(remainingCredits, burnRate, today, endDate) {
if (remainingCredits <= 0) {
return {
predictedExhaustionDate: formatDate(today),
daysUntilExhaustion: 0
};
}
if (burnRate <= 0) {
return {
predictedExhaustionDate: null,
daysUntilExhaustion: Infinity
};
}
const daysUntilExhaustion = Math.ceil(remainingCredits / burnRate);
const exhaustionDate = new Date(today);
exhaustionDate.setDate(exhaustionDate.getDate() + daysUntilExhaustion);
return {
predictedExhaustionDate: formatDate(exhaustionDate),
daysUntilExhaustion
};
}
/**
* Determine risk level based on multiple factors
*/
function determineRiskLevel(totalSpent, monthlyCredits, daysElapsed, monthDays, daysUntilExhaustion, remainingDays, thresholds) {
const creditsUsedRatio = monthlyCredits > 0 ? totalSpent / monthlyCredits : 0;
const timeElapsedRatio = monthDays > 0 ? daysElapsed / monthDays : 0;
// Check if exhaustion will happen before month end
if (daysUntilExhaustion !== Infinity && daysUntilExhaustion < remainingDays - 3) {
return 'danger';
}
// Check against thresholds
if (creditsUsedRatio >= thresholds.danger) {
return 'danger';
}
if (creditsUsedRatio >= thresholds.warning) {
return 'watch';
}
// Spending faster than time passing
if (creditsUsedRatio > timeElapsedRatio + 0.15) {
return 'danger';
}
if (creditsUsedRatio > timeElapsedRatio + 0.05) {
return 'watch';
}
return 'safe';
}
/**
* Determine confidence level for predictions
*/
function determineConfidenceLevel(expenseCount, daysElapsed) {
if (expenseCount < 3 || daysElapsed < 2) {
return 'low';
}
if (expenseCount < 10 || daysElapsed < 5) {
return 'medium';
}
return 'high';
}
/**
* Get confidence percentage (0-100)
*/
function getConfidencePercent(expenseCount, daysElapsed) {
// Max confidence at 15 days and 20+ expenses
const daysFactor = Math.min(daysElapsed / 15, 1) * 50;
const expensesFactor = Math.min(expenseCount / 20, 1) * 50;
return Math.round(daysFactor + expensesFactor);
}
/**
* Compute "Today's Context" insights
*/
function computeTodayContext(profile, expenses, derived) {
const insights = [];
const today = new Date();
const todayStr = formatDate(today);
const dayOfWeek = today.getDay();
// Get today's expenses
const todayExpenses = expenses.filter(exp => exp.date === todayStr);
const todayTotal = todayExpenses.reduce((sum, exp) => sum + exp.cost, 0);
// Get 7-day average
const avg7d = derived.burnRate7d;
// Compare today vs 7-day average
if (todayTotal > 0 && avg7d > 0) {
const percentDiff = Math.round(((todayTotal - avg7d) / avg7d) * 100);
if (percentDiff > 20) {
insights.push({
icon: '⬆️',
text: `Today is ${percentDiff}% higher than your 7-day average`,
type: 'warning'
});
} else if (percentDiff < -20) {
insights.push({
icon: '⬇️',
text: `Today is ${Math.abs(percentDiff)}% lower than your 7-day average`,
type: 'good'
});
}
}
// Check meal type dominance
const mealCosts = {};
todayExpenses.forEach(exp => {
mealCosts[exp.mealType] = (mealCosts[exp.mealType] || 0) + exp.cost;
});
const topMeal = Object.entries(mealCosts).sort((a, b) => b[1] - a[1])[0];
if (topMeal && topMeal[1] > todayTotal * 0.5) {
const mealNames = { breakfast: 'Breakfast', lunch: 'Lunch', snacks: 'Snacks', dinner: 'Dinner' };
insights.push({
icon: '🍽️',
text: `${mealNames[topMeal[0]] || topMeal[0]} accounts for ${Math.round(topMeal[1] / todayTotal * 100)}% of today's spend`,
type: 'info'
});
}
// Check item type impact (chicken vs veg)
const chickenCost = todayExpenses.filter(e => e.itemType === 'chicken').reduce((s, e) => s + e.cost, 0);
const vegCost = todayExpenses.filter(e => e.itemType === 'veg').reduce((s, e) => s + e.cost, 0);
if (chickenCost > vegCost + 100) {
insights.push({
icon: '🍗',
text: `Chicken items cost ₹${chickenCost - vegCost} more than veg alternatives`,
type: 'info'
});
}
// Day-of-week pattern (only if we have enough data)
const sameDayExpenses = expenses.filter(exp => {
const expDate = new Date(exp.date);
return expDate.getDay() === dayOfWeek && exp.date !== todayStr;
});
if (sameDayExpenses.length >= 2) {
const sameDayAvg = sameDayExpenses.reduce((s, e) => s + e.cost, 0) / (sameDayExpenses.length / 3); // Rough avg per day
const dayNames = ['Sundays', 'Mondays', 'Tuesdays', 'Wednesdays', 'Thursdays', 'Fridays', 'Saturdays'];
if (dayOfWeek === 5 || dayOfWeek === 6) { // Friday or Saturday
insights.push({
icon: '📅',
text: `${dayNames[dayOfWeek]} are typically your highest-spend days`,
type: 'warning'
});
}
}
return insights.slice(0, 3); // Max 3 insights
}
/**
* Compute 3-day forecast
*/
function computeForecast(profile, expenses, derived) {
const avgBurn = derived.burnRate7d > 0 ? derived.burnRate7d : derived.targetBurnRate;
const forecasts = [];
for (let i = 1; i <= 3; i++) {
const futureRemaining = derived.remainingCredits - (avgBurn * i);
const futureRemainingDays = derived.remainingDays - i;
let safeSpend = futureRemainingDays > 0 ? Math.round(futureRemaining / futureRemainingDays) : 0;
safeSpend = Math.max(0, safeSpend);
// Determine risk level
let risk = 'safe';
let riskLabel = 'Low risk';
if (futureRemaining <= 0) {
risk = 'danger';
riskLabel = 'Critical';
} else if (safeSpend < derived.targetBurnRate * 0.7) {
risk = 'danger';
riskLabel = 'High risk';
} else if (safeSpend < derived.targetBurnRate * 0.9) {
risk = 'watch';
riskLabel = 'Watch';
}
forecasts.push({
day: i,
safeSpend,
risk,
riskLabel
});
}
return forecasts;
}
/**
* Compute what changed since yesterday
*/
function computeYesterdayDelta(profile, expenses, derived) {
const deltas = [];
// Get yesterday's date
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const yesterdayStr = formatDate(yesterday);
// Calculate yesterday's derived data (simulate)
const yesterdayExpenses = expenses.filter(exp => exp.date <= yesterdayStr);
if (yesterdayExpenses.length < 3) return deltas;
const yesterdayDerived = computeDerivedData(profile, yesterdayExpenses);
// Compare burn rates
const burnDelta = Math.round(derived.burnRateOverall - yesterdayDerived.burnRateOverall);
if (Math.abs(burnDelta) >= 10) {
deltas.push({
icon: burnDelta > 0 ? '↑' : '↓',
text: `Burn rate ${burnDelta > 0 ? 'increased' : 'decreased'} by ₹${Math.abs(burnDelta)}/day`,
type: burnDelta > 0 ? 'warning' : 'good'
});
}
// Compare safe limits
const safeDelta = Math.round(derived.dailySafeLimit - yesterdayDerived.dailySafeLimit);
if (Math.abs(safeDelta) >= 10) {
deltas.push({
icon: safeDelta > 0 ? '↑' : '↓',
text: `Safe limit ${safeDelta > 0 ? 'increased' : 'reduced'} by ₹${Math.abs(safeDelta)}`,
type: safeDelta > 0 ? 'good' : 'warning'
});
}
// Check for spending spikes by category today
const todayExpenses = expenses.filter(exp => exp.date === derived.today);
const snackSpend = todayExpenses.filter(e => e.mealType === 'snacks').reduce((s, e) => s + e.cost, 0);
if (snackSpend > derived.dailySafeLimit * 0.3) {
deltas.push({
icon: '⚠',
text: 'Snack spending spiked today',
type: 'warning'
});
}
return deltas.slice(0, 3);
}
/**
* Calculate spending personality
*/
function calculatePersonality(profile, expenses, derived) {
if (expenses.length < 5) return null;
// Calculate category percentages
const categoryTotals = {};
expenses.forEach(exp => {
categoryTotals[exp.itemType] = (categoryTotals[exp.itemType] || 0) + exp.cost;
});
const proteinPercent = ((categoryTotals.chicken || 0) + (categoryTotals.paneer || 0)) / derived.totalSpent * 100;
const snackTotal = expenses.filter(e => e.mealType === 'snacks').reduce((s, e) => s + e.cost, 0);
const snackPercent = (snackTotal / derived.totalSpent) * 100;
// Weekend vs weekday analysis
let weekendSpend = 0, weekdaySpend = 0, weekendDays = 0, weekdayDays = 0;
const daySpends = {};
expenses.forEach(exp => {
const d = new Date(exp.date);
if (!daySpends[exp.date]) daySpends[exp.date] = { total: 0, isWeekend: d.getDay() === 0 || d.getDay() === 6 };
daySpends[exp.date].total += exp.cost;
});
Object.values(daySpends).forEach(day => {
if (day.isWeekend) { weekendSpend += day.total; weekendDays++; }
else { weekdaySpend += day.total; weekdayDays++; }
});
const weekendAvg = weekendDays > 0 ? weekendSpend / weekendDays : 0;
const weekdayAvg = weekdayDays > 0 ? weekdaySpend / weekdayDays : 0;
// Variance calculation
const dailySpends = Object.values(daySpends).map(d => d.total);
const avgSpend = derived.burnRateOverall;
const variance = dailySpends.reduce((sum, s) => sum + Math.pow(s - avgSpend, 2), 0) / dailySpends.length;
const stdDev = Math.sqrt(variance);
const isConsistent = stdDev < avgSpend * 0.3;
// Determine personality
if (weekendAvg > weekdayAvg * 1.3 && weekendDays >= 2) {
return {
icon: '🔥',
label: 'Weekend Spender',
desc: 'You tend to spend more on weekends. Consider weekend boost mode!'
};
}
if (snackPercent > 15) {
return {
icon: '☕',
label: 'Snack Lover',
desc: 'Snacks and beverages make up a significant portion of your spending.'
};
}
if (proteinPercent > 40) {
return {
icon: '🍗',
label: 'Protein Focused',
desc: 'You prefer chicken and paneer dishes. They cost more but you get your protein!'
};
}
if (isConsistent && derived.creditsUsedRatio < derived.timeElapsedRatio) {
return {
icon: '🐢',
label: 'Conservative Eater',
desc: 'You spend consistently and stay under budget. Great discipline!'
};
}
return {
icon: '⚖️',
label: 'Balanced Spender',
desc: 'Your spending patterns are well-distributed across categories and days.'
};
}
/**
* Generate personal spending rules/insights
*/
function generatePersonalRules(profile, expenses, derived) {
const rules = [];
if (expenses.length < 7) return rules;
// Analyze by time/meal
const mealCosts = { breakfast: 0, lunch: 0, snacks: 0, dinner: 0, other: 0 };
const mealCounts = { breakfast: 0, lunch: 0, snacks: 0, dinner: 0, other: 0 };
expenses.forEach(exp => {
mealCosts[exp.mealType] = (mealCosts[exp.mealType] || 0) + exp.cost;
mealCounts[exp.mealType] = (mealCounts[exp.mealType] || 0) + 1;
});
// Find most expensive meal type
const avgMealCosts = Object.entries(mealCosts).map(([meal, cost]) => ({
meal,
avg: mealCounts[meal] > 0 ? cost / mealCounts[meal] : 0
})).filter(m => m.avg > 0);
avgMealCosts.sort((a, b) => b.avg - a.avg);
if (avgMealCosts.length > 0 && avgMealCosts[0].avg > derived.targetBurnRate * 0.4) {
const mealNames = { breakfast: 'breakfasts', lunch: 'lunches', snacks: 'snacks', dinner: 'dinners' };
rules.push(`Your ${mealNames[avgMealCosts[0].meal] || avgMealCosts[0].meal} average ₹${Math.round(avgMealCosts[0].avg)} each`);
}
// Check chicken impact
const chickenExpenses = expenses.filter(e => e.itemType === 'chicken');
if (chickenExpenses.length >= 3) {
const chickenTotal = chickenExpenses.reduce((s, e) => s + e.cost, 0);
const chickenPercent = Math.round((chickenTotal / derived.totalSpent) * 100);
if (chickenPercent > 25) {
rules.push(`Chicken dishes cause ${chickenPercent}% of your total spending`);
}
}
// Day of week analysis
const dayTotals = [0, 0, 0, 0, 0, 0, 0];
const dayCounts = [0, 0, 0, 0, 0, 0, 0];
expenses.forEach(exp => {
const d = new Date(exp.date).getDay();
dayTotals[d] += exp.cost;
dayCounts[d]++;
});
const dayAvgs = dayTotals.map((t, i) => dayCounts[i] > 0 ? t / dayCounts[i] : 0);
const maxDayIdx = dayAvgs.indexOf(Math.max(...dayAvgs.filter(a => a > 0)));
const dayNames = ['Sundays', 'Mondays', 'Tuesdays', 'Wednesdays', 'Thursdays', 'Fridays', 'Saturdays'];
if (dayAvgs[maxDayIdx] > derived.burnRateOverall * 1.2) {
rules.push(`${dayNames[maxDayIdx]} are your riskiest spending days`);
}
return rules.slice(0, 3);
}
/**
* Generate end-of-month narrative
*/
function generateMonthNarrative(profile, expenses, derived) {
if (derived.daysElapsed < 20) return null;
const narrative = [];
// Opening based on spending pattern
const firstHalfExpenses = expenses.filter(exp => {
const expDate = new Date(exp.date);
const startDate = new Date(profile.startDate);
const dayNum = Math.floor((expDate - startDate) / (1000 * 60 * 60 * 24)) + 1;
return dayNum <= profile.monthDays / 2;
});
const firstHalfTotal = firstHalfExpenses.reduce((s, e) => s + e.cost, 0);
const secondHalfTotal = derived.totalSpent - firstHalfTotal;
if (firstHalfTotal < secondHalfTotal * 0.8) {
narrative.push('You started the month conservatively, then spending accelerated in the second half.');
} else if (firstHalfTotal > secondHalfTotal * 1.2) {
narrative.push('You spent heavily early on but have been more disciplined recently.');
} else {
narrative.push('Your spending has been fairly consistent throughout the month.');
}
// Category insight
const categoryTotals = {};
expenses.forEach(exp => {
categoryTotals[exp.itemType] = (categoryTotals[exp.itemType] || 0) + exp.cost;
});
const topCategory = Object.entries(categoryTotals).sort((a, b) => b[1] - a[1])[0];
if (topCategory) {
const catNames = { veg: 'vegetarian dishes', chicken: 'chicken items', paneer: 'paneer dishes', dessert: 'desserts', snacks: 'snacks' };
narrative.push(`${catNames[topCategory[0]] || topCategory[0]} dominated your spending this month.`);
}
// Projection
if (derived.surplusOrDeficit > 0) {
narrative.push(`If you maintain current discipline, you'll finish with ~₹${Math.round(derived.surplusOrDeficit)} surplus.`);
} else if (derived.surplusOrDeficit < -200) {
narrative.push(`At current pace, you may need an extra ₹${Math.abs(Math.round(derived.surplusOrDeficit))} to finish the month.`);
}
return narrative.join(' ');
}
/**
* Simulate spending impact on exhaustion
*/
function simulateSpend(profile, expenses, derived, amount) {
// Add hypothetical expense for tomorrow
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
const newRemaining = derived.remainingCredits - amount;
const newRemainingDays = derived.remainingDays - 1;
if (newRemainingDays <= 0) {
return {
exhaustionDate: formatDateDisplay(tomorrow.toISOString().split('T')[0]),
risk: 'danger'
};
}
const newBurnRate = (derived.totalSpent + amount) / (derived.daysElapsed + 1);
const daysUntilExhaustion = newRemaining > 0 ? Math.ceil(newRemaining / newBurnRate) : 0;
const exhaustionDate = new Date(tomorrow);
exhaustionDate.setDate(exhaustionDate.getDate() + daysUntilExhaustion);
// Determine new risk level
let risk = 'safe';
if (daysUntilExhaustion < newRemainingDays - 3) {
risk = 'danger';
} else if (daysUntilExhaustion < newRemainingDays) {
risk = 'watch';
}
return {
exhaustionDate: formatDateDisplay(exhaustionDate.toISOString().split('T')[0]),
risk
};
}
// ==========================================
// ADVICE ENGINE
// ==========================================
const adviceRules = [
{
id: 'on_track',
when: (profile, derived, expenses) =>
derived.riskLevel === 'safe' && expenses.length >= 3,
message: (profile, derived) =>
`You're on track! Maintain your current spending pattern to finish the month with ~₹${Math.abs(Math.round(derived.surplusOrDeficit))} ${derived.surplusOrDeficit >= 0 ? 'surplus' : 'to spare'}.`,
severity: 'low',
category: 'positive',
title: '✅ Great Progress'
},
{
id: 'overspending_early',
when: (profile, derived, expenses) =>
derived.daysElapsed <= profile.monthDays / 2 &&
derived.creditsUsedRatio > derived.timeElapsedRatio + 0.1,
message: (profile, derived) =>
`You've used ${Math.round(derived.creditsUsedRatio * 100)}% of credits in ${Math.round(derived.timeElapsedRatio * 100)}% of the month. Consider reducing spending for the next ${Math.max(3, Math.round(derived.remainingDays / 3))} days.`,
severity: 'high',
category: 'spend_control',
title: '⚠️ Early Overspending'
},
{
id: 'exhaustion_warning',
when: (profile, derived, expenses) =>
derived.daysUntilExhaustion !== Infinity &&
derived.daysUntilExhaustion < derived.remainingDays,
message: (profile, derived) => {
const shortfall = derived.remainingDays - derived.daysUntilExhaustion;
return `At current rate, credits will finish ${shortfall} day(s) before month end. You'll need to reduce daily spending to ₹${Math.round(derived.remainingCredits / derived.remainingDays)} to last the full month.`;
},
severity: 'high',
category: 'prediction',
title: '🚨 Credit Exhaustion Alert'
},
{
id: 'frequent_chicken',
when: (profile, derived, expenses) => {
const chickenCount = expenses.filter(e => e.itemType === 'chicken').length;
return chickenCount >= 5;
},
message: (profile, derived, expenses) => {
const chickenCount = expenses.filter(e => e.itemType === 'chicken').length;
const chickenCost = expenses.filter(e => e.itemType === 'chicken').reduce((s, e) => s + e.cost, 0);
return `You've had chicken ${chickenCount} times (₹${chickenCost} total). Swapping some for paneer or veg items could save ₹${Math.round(chickenCost * 0.3)}.`;
},
severity: 'medium',
category: 'category_mix',
title: '🍗 Chicken Frequency'
},
{
id: 'dessert_spending',
when: (profile, derived, expenses) => {
const dessertTotal = expenses.filter(e => e.itemType === 'dessert').reduce((s, e) => s + e.cost, 0);
return dessertTotal > profile.monthlyCredits * 0.1;
},
message: (profile, derived, expenses) => {
const dessertTotal = expenses.filter(e => e.itemType === 'dessert').reduce((s, e) => s + e.cost, 0);
return `Desserts account for ₹${dessertTotal} (${Math.round(dessertTotal / profile.monthlyCredits * 100)}% of budget). Consider limiting to weekends to save credits.`;
},
severity: 'medium',
category: 'luxury',
title: '🍰 Dessert Alert'
},
{
id: 'daily_limit_exceeded',
when: (profile, derived, expenses) =>
derived.todaySpend > derived.dailySafeLimit && derived.dailySafeLimit > 0,
message: (profile, derived) =>
`Today's spending (₹${derived.todaySpend}) exceeded your safe limit (₹${derived.dailySafeLimit}). Consider a lighter dinner or skip snacks to balance.`,
severity: 'high',
category: 'daily',
title: '📊 Daily Limit Exceeded'
},
{
id: 'weekend_boost_suggestion',
when: (profile, derived, expenses) => {
const today = new Date();
const isWeekday = today.getDay() >= 1 && today.getDay() <= 5;
return !profile.preferences.weekendBoost &&
isWeekday &&
derived.todaySpend < derived.dailySafeLimit * 0.8;
},
message: () =>
'Tip: Enable "Weekend Boost" in preferences to save credits on weekdays and enjoy more on weekends.',
severity: 'low',
category: 'tip',
title: '💡 Weekend Boost'
},
{
id: 'surplus_projection',
when: (profile, derived, expenses) =>
derived.surplusOrDeficit > profile.monthlyCredits * 0.1 && expenses.length >= 5,
message: (profile, derived) =>
`Great news! At current pace, you'll finish with ~₹${Math.round(derived.surplusOrDeficit)} surplus. You can afford a bit more flexibility.`,
severity: 'low',
category: 'positive',
title: '🎉 Surplus Projected'
},
{
id: 'queue_risk',
when: (profile, derived, expenses) =>
derived.riskLevel === 'danger' && derived.remainingCredits < 500,
message: (profile, derived) =>
`Credits are critically low (₹${derived.remainingCredits}). You may need to use cash and face longer queues for the remaining ${derived.remainingDays} days.`,
severity: 'high',
category: 'warning',
title: '🚶 Queue Risk'
}
];
/**
* Generate advice based on current state
*/
function generateAdvice(profile, derived, expenses) {
const triggeredRules = adviceRules
.filter(rule => rule.when(profile, derived, expenses))
.map(rule => ({
id: rule.id,
title: rule.title,
message: rule.message(profile, derived, expenses),
severity: rule.severity,
category: rule.category
}));
// Sort by severity (high -> medium -> low)
const severityOrder = { high: 0, medium: 1, low: 2 };
triggeredRules.sort((a, b) => severityOrder[a.severity] - severityOrder[b.severity]);
// Limit to top 5 advice items
return triggeredRules.slice(0, 5);
}
// ==========================================
// LOCAL STORAGE MANAGEMENT
// ==========================================
/**
* Load app state from localStorage
*/
function loadState() {
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
const state = JSON.parse(stored);
// Migration logic for future versions
return migrateState(state);
}
} catch (error) {
console.error('Error loading state:', error);
showToast('Could not load saved data. Starting fresh.', 'warning');
}
return null;
}
/**
* Save app state to localStorage
*/
function saveState(state) {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
return true;
} catch (error) {
console.error('Error saving state:', error);
showToast('Could not save data. You may be in private browsing mode.', 'warning');
return false;
}
}
/**
* Migrate state from older versions
*/
function migrateState(state) {
// Add migration logic here when schema changes
// For now, just return as-is
return state;
}
/**
* Export state as JSON file
*/
function exportState(state) {
const dataStr = JSON.stringify(state, null, 2);
const blob = new Blob([dataStr], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `unmessify_backup_${formatDate(new Date())}.json`;
link.click();
URL.revokeObjectURL(url);
showToast('Data exported successfully!', 'success');
}
/**
* Import state from JSON file
*/
function importState(file, callback) {
const reader = new FileReader();
reader.onload = (e) => {
try {
const state = JSON.parse(e.target.result);
if (state.profile && state.expenses) {
callback(state);
showToast('Data imported successfully!', 'success');
} else {
showToast('Invalid backup file format.', 'error');
}
} catch (error) {
console.error('Import error:', error);
showToast('Could not read backup file.', 'error');
}
};
reader.readAsText(file);
}
// ==========================================
// UTILITY FUNCTIONS
// ==========================================
function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
function formatDate(date) {
const d = new Date(date);
const year = d.getFullYear();
const month = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
function formatDateDisplay(dateStr) {
const date = new Date(dateStr);
const options = { month: 'short', day: 'numeric' };
return date.toLocaleDateString('en-IN', options);
}
function formatCurrency(amount) {
return `₹${Math.round(amount).toLocaleString('en-IN')}`;
}
// ==========================================
// UI FUNCTIONS
// ==========================================
function showToast(message, type = 'success') {
const container = document.getElementById('toastContainer');
const icons = {
success: '✅',
warning: '⚠️',
error: '❌'
};
const toast = document.createElement('div');
toast.className = `toast ${type}`;
toast.innerHTML = `
<span class="toast-icon">${icons[type]}</span>
<span class="toast-message">${message}</span>
<button class="toast-close" onclick="this.parentElement.remove()">×</button>
`;
container.appendChild(toast);
// Auto-remove after 4 seconds
setTimeout(() => {
if (toast.parentElement) {
toast.style.opacity = '0';
setTimeout(() => toast.remove(), 300);
}
}, 4000);
}
function showConfirmModal(title, message, onConfirm) {
const modal = document.getElementById('confirmModal');
document.getElementById('confirmTitle').textContent = title;
document.getElementById('confirmMessage').textContent = message;
modal.setAttribute('aria-hidden', 'false');
const confirmBtn = document.getElementById('confirmOk');