Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
3924 lines (3847 loc) · 242 KB
/
Copy pathapp.js
File metadata and controls
3924 lines (3847 loc) · 242 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
/* Kharcha — expenses, budgets, bills, goals, splits, calculator and money tools.
Plain JS, no build step. Data lives in the Claude artifact store when available,
otherwise in this browser's localStorage. */
(() => {
'use strict';
// ============================================================
// Helpers
// ============================================================
const $ = (sel, root = document) => root.querySelector(sel);
const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));
const ESC = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ESC[c]);
const uid = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
const pad2 = (n) => String(n).padStart(2, '0');
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
const sum = (arr, f = (x) => x) => arr.reduce((a, x) => a + f(x), 0);
const round2 = (n) => Math.round(n * 100) / 100;
const ic = (name, cls = '') => `<span class="ms ${cls}" aria-hidden="true">${name}</span>`;
const plural = (n, word, many) => `${n} ${n === 1 ? word : many || word + 's'}`;
const num = (v) => {
const n = parseFloat(String(v ?? '').replace(/[^0-9.\-]/g, ''));
return Number.isFinite(n) ? n : 0;
};
// ---------- Where the book lives ----------
// Inside a Claude artifact: the Claude account store. On the website with firebase-config.js
// filled in: Google sign-in + Firestore. Otherwise: this browser only.
const IN_CLAUDE = (() => { try { return !!(window.claude && typeof window.claude.use === 'function'); } catch { return false; } })();
// Inside the Android app (Capacitor), data is saved as files in the app's private storage.
const CAP = (() => { try { const c = window.Capacitor; return c && typeof c.isNativePlatform === 'function' && c.isNativePlatform() ? c : null; } catch { return null; } })();
const nativePlugin = (name) => (CAP && CAP.Plugins && CAP.Plugins[name]) || null;
// Google sign-in inside the Android app needs a native sign-in plugin, so for now the app keeps its book on the phone.
const FB_CONFIG = !IN_CLAUDE && !CAP && window.KHARCHA_FIREBASE && window.KHARCHA_FIREBASE.apiKey ? window.KHARCHA_FIREBASE : null;
const FB_SDK = 'https://www.gstatic.com/firebasejs/12.19.0';
const session = { mode: 'local', user: null, books: [], invites: [], bookId: 'personal', book: null, unsubs: [], openSeq: 0 };
let fb = null;
// JSON with sorted keys, so a document read back from a server compares equal to the local copy.
const stableJson = (v) => JSON.stringify(v, (k, val) => (val && typeof val === 'object' && !Array.isArray(val)
? Object.keys(val).sort().reduce((o, key) => { o[key] = val[key]; return o; }, {}) : val));
const safeId = (v) => String(v ?? '').replace(/[^A-Za-z0-9_-]/g, '').slice(0, 40);
// ---------- Dates (all local, stored as YYYY-MM-DD) ----------
const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const MON = MONTHS.map((m) => m.slice(0, 3));
const WD = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const WEEKDAY = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const toDateStr = (d) => `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
const parseDate = (s) => { const [y, m, d] = String(s).split('-').map(Number); return new Date(y, (m || 1) - 1, d || 1); };
const todayStr = () => toDateStr(new Date());
const thisMonth = () => todayStr().slice(0, 7);
const shiftMonth = (key, n) => { const [y, m] = key.split('-').map(Number); const d = new Date(y, m - 1 + n, 1); return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}`; };
const daysInMonth = (key) => { const [y, m] = key.split('-').map(Number); return new Date(y, m, 0).getDate(); };
const addDays = (s, n) => { const d = parseDate(s); d.setDate(d.getDate() + n); return toDateStr(d); };
const diffDays = (a, b) => Math.round((parseDate(a) - parseDate(b)) / 864e5);
const monthLabel = (key) => { const [y, m] = key.split('-').map(Number); return `${MONTHS[m - 1]} ${y}`; };
const monthShort = (key) => MON[Number(key.slice(5, 7)) - 1];
const dateLabel = (s) => {
const d = parseDate(s);
const yr = d.getFullYear() !== new Date().getFullYear() ? ` ${d.getFullYear()}` : '';
return `${d.getDate()} ${MON[d.getMonth()]}${yr}`;
};
const dayLabel = (s) => {
const t = todayStr();
if (s === t) return 'Today';
if (s === addDays(t, -1)) return 'Yesterday';
if (s === addDays(t, 1)) return 'Tomorrow';
const d = parseDate(s);
return `${WD[d.getDay()]}, ${dateLabel(s)}`;
};
const isDateStr = (s) => typeof s === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(s);
// ---------- Money ----------
const CURRENCIES = [
{ code: 'INR', name: 'Indian rupee', locale: 'en-IN' },
{ code: 'USD', name: 'US dollar', locale: 'en-US' },
{ code: 'EUR', name: 'Euro', locale: 'en-IE' },
{ code: 'GBP', name: 'British pound', locale: 'en-GB' },
{ code: 'AED', name: 'UAE dirham', locale: 'en-AE' },
{ code: 'SGD', name: 'Singapore dollar', locale: 'en-SG' },
{ code: 'AUD', name: 'Australian dollar', locale: 'en-AU' },
{ code: 'CAD', name: 'Canadian dollar', locale: 'en-CA' },
{ code: 'JPY', name: 'Japanese yen', locale: 'ja-JP' },
];
let cur = { code: 'INR', locale: 'en-IN', symbol: '₹' };
let fmtWhole, fmtDec, fmtNum;
function setCurrency(code) {
const c = CURRENCIES.find((x) => x.code === code) || CURRENCIES[0];
fmtWhole = new Intl.NumberFormat(c.locale, { style: 'currency', currency: c.code, maximumFractionDigits: 0, minimumFractionDigits: 0 });
fmtDec = c.code === 'JPY' ? fmtWhole : new Intl.NumberFormat(c.locale, { style: 'currency', currency: c.code, minimumFractionDigits: 2, maximumFractionDigits: 2 });
fmtNum = new Intl.NumberFormat(c.locale, { maximumFractionDigits: 2 });
const sym = fmtWhole.formatToParts(0).find((p) => p.type === 'currency');
cur = { code: c.code, locale: c.locale, symbol: sym ? sym.value : c.code };
}
function money(n, opts = {}) {
const v = Number(n) || 0;
const frac = Math.abs(v - Math.round(v)) > 0.004;
const s = frac && !opts.whole ? fmtDec.format(v) : fmtWhole.format(Math.round(v));
return opts.sign && v > 0 ? '+' + s : s;
}
const trim1 = (x) => (Math.round(x * 10) / 10).toString().replace(/\.0$/, '');
function compact(n) {
const v = Math.abs(n), sg = n < 0 ? '-' : '';
if (cur.code === 'INR') {
if (v >= 1e7) return `${sg}₹${trim1(v / 1e7)}Cr`;
if (v >= 1e5) return `${sg}₹${trim1(v / 1e5)}L`;
if (v >= 1e3) return `${sg}₹${trim1(v / 1e3)}K`;
return `${sg}₹${Math.round(v)}`;
}
return new Intl.NumberFormat(cur.locale, { style: 'currency', currency: cur.code, notation: 'compact', maximumFractionDigits: 1 }).format(n);
}
const fmtN = (n) => fmtNum.format(n);
const pct = (x, d = 0) => `${(x * 100).toFixed(d)}%`;
// ---------- Friends ----------
// Friends are matched by name, ignoring capitals and extra spaces.
const fkey = (name) => String(name ?? '').trim().replace(/\s+/g, ' ').toLowerCase();
// WhatsApp numbers are kept as digits with the country code, the way wa.me links want them.
// A 10-digit number typed without a code is taken as Indian while amounts are in rupees.
function phoneFromInput(raw) {
const s = String(raw ?? '').trim();
let d = s.replace(/\D/g, '');
if (!d) return '';
if (!s.startsWith('+')) {
if (d.startsWith('00')) d = d.slice(2);
else if (cur.code === 'INR' && d.length === 11 && d.startsWith('0')) d = '91' + d.slice(1);
else if (cur.code === 'INR' && d.length === 10) d = '91' + d;
}
return d.length >= 8 && d.length <= 15 ? d : '';
}
const cleanPhone = (v) => { const d = String(v ?? '').replace(/\D/g, ''); return d.length >= 8 && d.length <= 15 ? d : ''; };
const cleanUpi = (v) => { const s = String(v ?? '').trim().slice(0, 60); return /^[\w.-]{2,}@[A-Za-z][\w.-]*$/.test(s) ? s : ''; };
// ============================================================
// Categories, payment modes
// ============================================================
const EXPENSE_CATS = [
{ id: 'food', name: 'Food & dining', short: 'Food', icon: 'restaurant', h: 24 },
{ id: 'groceries', name: 'Groceries', short: 'Groceries', icon: 'local_grocery_store', h: 88 },
{ id: 'transport', name: 'Transport', short: 'Transport', icon: 'directions_bus', h: 210 },
{ id: 'fuel', name: 'Fuel', short: 'Fuel', icon: 'local_gas_station', h: 4 },
{ id: 'bike', name: 'Bike', short: 'Bike', icon: 'two_wheeler', h: 120 },
{ id: 'shopping', name: 'Shopping', short: 'Shopping', icon: 'shopping_bag', h: 318 },
{ id: 'bills', name: 'Bills & utilities', short: 'Bills', icon: 'receipt_long', h: 44 },
{ id: 'rent', name: 'Rent & housing', short: 'Rent', icon: 'home', h: 258 },
{ id: 'recharge', name: 'Mobile & internet', short: 'Recharge', icon: 'smartphone', h: 188 },
{ id: 'health', name: 'Health', short: 'Health', icon: 'medical_services', h: 350 },
{ id: 'entertainment', name: 'Entertainment', short: 'Fun', icon: 'movie', h: 280 },
{ id: 'education', name: 'Education', short: 'Education', icon: 'school', h: 232 },
{ id: 'travel', name: 'Travel', short: 'Travel', icon: 'flight', h: 198 },
{ id: 'personal', name: 'Personal care', short: 'Personal', icon: 'spa', h: 300 },
{ id: 'gifts', name: 'Gifts & donations', short: 'Gifts', icon: 'redeem', h: 336 },
{ id: 'emi', name: 'EMI & loans', short: 'EMI', icon: 'account_balance', h: 30 },
{ id: 'invest', name: 'Investments', short: 'Invest', icon: 'trending_up', h: 150 },
{ id: 'subs', name: 'Subscriptions', short: 'Subs', icon: 'subscriptions', h: 268 },
{ id: 'other', name: 'Other', short: 'Other', icon: 'category', h: 140, s: 0 },
];
const INCOME_CATS = [
{ id: 'salary', name: 'Salary', short: 'Salary', icon: 'payments', h: 145 },
{ id: 'business', name: 'Business', short: 'Business', icon: 'storefront', h: 200 },
{ id: 'freelance', name: 'Freelance', short: 'Freelance', icon: 'work', h: 260 },
{ id: 'interest', name: 'Interest & dividends', short: 'Interest', icon: 'savings', h: 40 },
{ id: 'refund', name: 'Refunds & cashback', short: 'Refunds', icon: 'currency_exchange', h: 180 },
{ id: 'giftin', name: 'Gifts received', short: 'Gifts', icon: 'redeem', h: 330 },
{ id: 'otherin', name: 'Other income', short: 'Other', icon: 'add_card', h: 140, s: 0 },
];
const UNKNOWN_CAT = { id: '?', name: 'Uncategorised', short: 'Other', icon: 'category', h: 140, s: 0 };
const MODES = [
{ id: 'upi', name: 'UPI', icon: 'qr_code_scanner', color: 'var(--s1)' },
{ id: 'cash', name: 'Cash', icon: 'payments', color: 'var(--s2)' },
{ id: 'debit', name: 'Debit card', icon: 'credit_card', color: 'var(--s3)' },
{ id: 'credit', name: 'Credit card', icon: 'credit_score', color: 'var(--s4)' },
{ id: 'netbanking', name: 'Net banking', icon: 'account_balance', color: 'var(--s5)' },
{ id: 'wallet', name: 'Wallet', icon: 'account_balance_wallet', color: 'var(--s6)' },
];
const modeOf = (id) => MODES.find((m) => m.id === id) || MODES[0];
const ICON_CHOICES = ['pets', 'child_care', 'sports_esports', 'fitness_center', 'local_cafe', 'local_bar', 'checkroom', 'build', 'local_laundry_service', 'directions_car', 'two_wheeler', 'local_taxi', 'train', 'hotel', 'park', 'celebration', 'cake', 'music_note', 'menu_book', 'laptop', 'headphones', 'local_pharmacy', 'volunteer_activism', 'water_drop', 'bolt', 'wifi', 'tv', 'savings', 'work', 'sell', 'favorite', 'beach_access', 'home', 'smartphone', 'flight', 'school'];
const GOAL_ICONS = ['savings', 'flight', 'smartphone', 'directions_car', 'two_wheeler', 'home', 'school', 'laptop', 'favorite', 'beach_access', 'celebration', 'medical_services'];
const HUES = [4, 24, 44, 88, 145, 188, 210, 232, 258, 280, 318, 340];
function allCats(type) {
return [...(type === 'income' ? INCOME_CATS : EXPENSE_CATS), ...state.customCats.filter((c) => c.type === type)];
}
function getCat(id) {
return EXPENSE_CATS.find((c) => c.id === id) || INCOME_CATS.find((c) => c.id === id) || state.customCats.find((c) => c.id === id) || UNKNOWN_CAT;
}
const catIco = (c, size = '') => `<span class="cat-ico ${size}" style="--h:${Number(c.h) || 0};--s:${c.s ?? 1}">${ic(c.icon)}</span>`;
// ============================================================
// State
// ============================================================
const DEFAULT_SETTINGS = { currency: 'INR', theme: 'system', name: '', upi: '' };
// friends: name + WhatsApp number for people you split with. Who owes what lives in splits.
const emptyData = () => ({ txns: [], budgets: { total: 0, cats: {} }, goals: [], bills: [], splits: [], customCats: [], friends: [] });
const state = { ...emptyData(), settings: { ...DEFAULT_SETTINGS }, sample: false, started: false, loaded: false };
const ui = {
tab: 'home',
month: thisMonth(),
filter: { q: '', type: 'all', cat: '', mode: '' },
insight: 'expense',
plan: 'budgets',
allSplits: false,
tools: 'calc',
theme: 'system',
};
const toolVals = {};
// While someone with their own data browses sample data, their book waits here untouched.
let sampleStash = null;
const takeData = () => JSON.parse(JSON.stringify({ txns: state.txns, budgets: state.budgets, goals: state.goals, bills: state.bills, splits: state.splits, customCats: state.customCats, friends: state.friends }));
const calc = { expr: '', done: false, error: '', history: [] };
// Per-viewer conveniences (tab, theme, calculator history) — never the book itself.
const PREFS_KEY = 'kharcha.prefs';
let prefs = {};
function prefsLoad() {
try { prefs = JSON.parse(localStorage.getItem(PREFS_KEY) || '{}') || {}; } catch { prefs = {}; }
return prefs;
}
function prefsSave() {
try {
localStorage.setItem(PREFS_KEY, JSON.stringify({ ...prefs, tab: ui.tab, plan: ui.plan, tools: ui.tools, insight: ui.insight, theme: ui.theme, calc: calc.history.slice(0, 30) }));
} catch { /* storage blocked: preferences just reset next visit */ }
}
// ============================================================
// Storage backends
// ============================================================
const LS_PREFIX = 'kharcha.v1.';
const localStore = {
kind: 'device',
async loadAll() {
const out = {};
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i);
if (k && k.startsWith(LS_PREFIX)) {
try { out[k.slice(LS_PREFIX.length)] = JSON.parse(localStorage.getItem(k)); } catch { /* skip corrupt doc */ }
}
}
return out;
},
async set(key, data) { localStorage.setItem(LS_PREFIX + key, JSON.stringify(data)); },
async del(key) { localStorage.removeItem(LS_PREFIX + key); },
};
const memoryStore = {
kind: 'memory', docs: {},
async loadAll() { return JSON.parse(JSON.stringify(this.docs)); },
async set(key, data) { this.docs[key] = data; },
async del(key) { delete this.docs[key]; },
};
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
async function withRetry(fn) {
try { return await fn(); } catch (e) {
if (e && e.code === 'unavailable') { await wait(400 + Math.random() * 600); return fn(); }
throw e;
}
}
function cloudStore(db, userId) {
const col = db.collection('data/users/' + userId);
return {
kind: 'cloud',
async loadAll() {
const snap = await withRetry(() => col.limit(1000).get());
const out = {};
snap.docs.forEach((d) => { if (d.exists) out[d.id] = JSON.parse(JSON.stringify(d.data())); });
return out;
},
set: (key, data) => withRetry(() => col.doc(key).set(data)),
del: (key) => withRetry(() => col.doc(key).delete()),
};
}
const capUse = (name) => {
try {
if (window.claude && typeof window.claude.use === 'function') return window.claude.use(name).catch(() => null);
} catch { /* not in a viewer */ }
return Promise.resolve(null);
};
// Android app: one JSON file per document in the app's private storage. A save writes a
// "<key>.new" copy first and removes it after the main file is written, so a crash
// mid-save never loses the latest data (loading prefers a leftover .new copy).
function phoneStore(FS) {
const dir = 'DATA';
const base = 'kharcha';
const read = async (name) => JSON.parse((await FS.readFile({ path: `${base}/${name}`, directory: dir, encoding: 'utf8' })).data);
return {
kind: 'phone',
async loadAll() {
const out = {};
let names = [];
try { names = ((await FS.readdir({ path: base, directory: dir })).files || []).map((f) => (typeof f === 'string' ? f : f.name)); } catch { return out; }
for (const name of names.filter((n) => n.endsWith('.json'))) {
try { out[name.slice(0, -5)] = await read(name); } catch { /* damaged file: a .new copy may cover it */ }
}
for (const name of names.filter((n) => n.endsWith('.new'))) {
try { out[name.slice(0, -4)] = await read(name); } catch { /* half-written copy: the .json file stands */ }
}
return out;
},
async set(key, data) {
const text = JSON.stringify(data);
await FS.writeFile({ path: `${base}/${key}.new`, directory: dir, encoding: 'utf8', data: text, recursive: true });
await FS.writeFile({ path: `${base}/${key}.json`, directory: dir, encoding: 'utf8', data: text, recursive: true });
await FS.deleteFile({ path: `${base}/${key}.new`, directory: dir }).catch(() => {});
},
async del(key) {
await FS.deleteFile({ path: `${base}/${key}.json`, directory: dir }).catch(() => {});
await FS.deleteFile({ path: `${base}/${key}.new`, directory: dir }).catch(() => {});
},
};
}
// Android app: after changes, keep a full backup in the phone's Documents/Kharcha folder
// (latest copy + one per day for a week). It survives uninstalling the app and can be
// restored with Settings → Restore from backup.
const backupInfo = { ok: null, at: 0 };
let backupTimer = null;
const backupPayload = () => ({ app: 'kharcha', v: 1, exportedAt: new Date().toISOString(), data: { txns: state.txns, budgets: state.budgets, goals: state.goals, bills: state.bills, splits: state.splits, customCats: state.customCats, friends: state.friends, settings: state.settings } });
function scheduleAutoBackup() {
if (store.kind !== 'phone' || state.sample) return;
clearTimeout(backupTimer);
backupTimer = setTimeout(autoBackup, 3000);
}
async function autoBackup() {
const FS = nativePlugin('Filesystem');
if (!FS || state.sample) return;
// Never replace a backup with an empty book (for example right after "Delete all data").
if (!state.txns.length && !state.goals.length && !state.bills.length && !state.splits.length) return;
const data = JSON.stringify(backupPayload(), null, 1);
const write = (name) => FS.writeFile({ path: `Kharcha/${name}`, directory: 'DOCUMENTS', encoding: 'utf8', data, recursive: true });
const names = () => { const b = prefs.backupBase || 'kharcha-backup'; return [`${b}-latest.json`, `${b}-${todayStr()}.json`]; };
try {
try {
for (const n of names()) await write(n);
} catch (e) {
// A file left by an earlier install of the app can't be overwritten; use fresh names instead.
if (prefs.backupBase) throw e;
prefs.backupBase = `kharcha-backup-${uid().slice(-4)}`;
prefsSave();
for (const n of names()) await write(n);
}
const b = prefs.backupBase || 'kharcha-backup';
const dated = ((await FS.readdir({ path: 'Kharcha', directory: 'DOCUMENTS' })).files || [])
.map((f) => (typeof f === 'string' ? f : f.name))
.filter((n) => n.startsWith(b + '-') && /-\d{4}-\d{2}-\d{2}\.json$/.test(n)).sort();
for (const old of dated.slice(0, -7)) await FS.deleteFile({ path: `Kharcha/${old}`, directory: 'DOCUMENTS' }).catch(() => {});
Object.assign(backupInfo, { ok: true, at: Date.now() });
} catch {
Object.assign(backupInfo, { ok: false, at: Date.now() });
}
}
function localWorks() {
try { const k = LS_PREFIX + '__t'; localStorage.setItem(k, '1'); localStorage.removeItem(k); return true; } catch { return false; }
}
async function pickStore() {
const FS = nativePlugin('Filesystem');
if (FS) return phoneStore(FS);
const [db, user] = await Promise.all([capUse('db'), capUse('user')]);
if (db && user) {
try {
const id = await user.id();
if (id) return cloudStore(db, id);
} catch { /* fall through to device storage */ }
}
return localWorks() ? localStore : memoryStore;
}
let store = memoryStore;
const downloadsCap = capUse('downloads');
// ---------- Documents <-> state ----------
const ITEM_COLS = ['txns', 'goals', 'bills', 'splits'];
function buildDocs() {
const meta = { v: 1, started: true, settings: state.settings, budgets: state.budgets, customCats: state.customCats, friends: state.friends };
if (store.granular) {
// One document per entry, so two people editing different entries never overwrite each other.
const out = { 'meta/main': meta };
for (const col of ITEM_COLS) for (const x of state[col]) out[`${col}/${x.id}`] = x;
return out;
}
const docs = {
meta,
goals: { items: state.goals },
bills: { items: state.bills },
splits: { items: state.splits },
};
for (const t of state.txns) {
const k = 'tx-' + t.date.slice(0, 7);
(docs[k] || (docs[k] = { items: [] })).items.push(t);
}
return docs;
}
const hasBook = (docs) => !!docs.meta || !!docs['meta/main'] || Object.keys(docs).some((k) => k.startsWith('tx-') || k.startsWith('txns/'));
function applyDocs(docs) {
if (Object.keys(docs).some((k) => k.includes('/'))) {
const m = docs['meta/main'] || {};
const pick = (col) => Object.keys(docs).filter((k) => k.startsWith(col + '/')).map((k) => ({ ...docs[k], id: k.slice(col.length + 1) }));
const data = { settings: m.settings, budgets: m.budgets, customCats: m.customCats, friends: m.friends, txns: pick('txns'), goals: pick('goals'), bills: pick('bills'), splits: pick('splits') };
Object.assign(state, sanitizeData(data), { sample: false, started: true });
return;
}
const m = docs.meta || {};
const data = {
settings: m.settings, budgets: m.budgets, customCats: m.customCats, friends: m.friends,
goals: docs.goals && docs.goals.items, bills: docs.bills && docs.bills.items, splits: docs.splits && docs.splits.items,
txns: Object.keys(docs).filter((k) => k.startsWith('tx-')).flatMap((k) => (docs[k] && docs[k].items) || []),
};
Object.assign(state, sanitizeData(data), { sample: false, started: true });
}
function sanitizeData(d) {
const str = (v, max = 80) => String(v ?? '').slice(0, max);
const pos = (v) => { const n = Number(v); return Number.isFinite(n) && n > 0 ? round2(n) : 0; };
const arr = (v) => (Array.isArray(v) ? v : []);
const settings = { ...DEFAULT_SETTINGS, ...(d.settings || {}) };
if (!CURRENCIES.some((c) => c.code === settings.currency)) settings.currency = 'INR';
if (!['system', 'light', 'dark'].includes(settings.theme)) settings.theme = 'system';
settings.name = str(settings.name, 40);
settings.upi = cleanUpi(settings.upi);
const customCats = arr(d.customCats).filter((c) => c && c.id && c.name).map((c) => ({
id: str(c.id, 40), name: str(c.name, 30), short: str(c.name, 12), type: c.type === 'income' ? 'income' : 'expense',
icon: ICON_CHOICES.includes(c.icon) ? c.icon : 'sell', h: clamp(Number(c.h) || 0, 0, 360),
}));
const txns = arr(d.txns).filter((t) => t && isDateStr(t.date) && pos(t.amount) > 0).map((t) => ({
id: safeId(t.id) || uid(), type: t.type === 'income' ? 'income' : 'expense', amount: pos(t.amount),
cat: str(t.cat, 40) || 'other', mode: MODES.some((m) => m.id === t.mode) ? t.mode : 'upi',
date: t.date, note: str(t.note), ts: Number(t.ts) || 0, ...(t.by ? { by: str(t.by, 128) } : {}),
...(t.billId ? { billId: str(t.billId, 40) } : {}), ...(t.splitId ? { splitId: str(t.splitId, 40) } : {}),
}));
const b = d.budgets || {};
const cats = {};
Object.entries(b.cats || {}).forEach(([k, v]) => { if (pos(v)) cats[str(k, 40)] = pos(v); });
const goals = arr(d.goals).filter((g) => g && g.name).map((g) => ({
id: safeId(g.id) || uid(), name: str(g.name, 40), icon: GOAL_ICONS.includes(g.icon) ? g.icon : 'savings',
target: pos(g.target), saved: Math.max(0, round2(Number(g.saved) || 0)), deadline: isDateStr(g.deadline) ? g.deadline : '',
h: clamp(Number(g.h) || 145, 0, 360),
}));
const FREQ = ['monthly', 'quarterly', 'yearly', 'weekly'];
const bills = arr(d.bills).filter((x) => x && x.name && isDateStr(x.nextDue)).map((x) => ({
id: safeId(x.id) || uid(), name: str(x.name, 40), amount: pos(x.amount), cat: str(x.cat, 40) || 'bills',
freq: FREQ.includes(x.freq) ? x.freq : 'monthly', nextDue: x.nextDue, day: clamp(Number(x.day) || parseDate(x.nextDue).getDate(), 1, 31),
mode: MODES.some((m) => m.id === x.mode) ? x.mode : 'upi', lastPaid: isDateStr(x.lastPaid) ? x.lastPaid : '',
}));
// A share that has been partly paid back keeps how much came back so far (paid / myPaid);
// once it is all back it is simply settled.
const repaid = (share, settled, paid) => {
const v = clamp(round2(Number(paid) || 0), 0, share);
if (settled || (share > 0 && v >= share - 0.005)) return { settled: true, paid: 0 };
return { settled: false, paid: v };
};
const splits = arr(d.splits).filter((s) => s && s.title).map((s) => {
const myShare = Math.max(0, round2(Number(s.myShare) || 0));
const me = repaid(myShare, s.iSettled, s.myPaid);
return {
id: safeId(s.id) || uid(), title: str(s.title, 50), date: isDateStr(s.date) ? s.date : todayStr(), total: pos(s.total),
paidBy: str(s.paidBy || 'me', 30) || 'me', myShare, iSettled: me.settled, ...(me.paid ? { myPaid: me.paid } : {}),
people: arr(s.people).filter((p) => p && p.name).map((p) => {
const share = Math.max(0, round2(Number(p.share) || 0));
const r = repaid(share, p.settled, p.paid);
return { name: str(p.name, 30), share, settled: r.settled, ...(r.paid ? { paid: r.paid } : {}) };
}),
...(s.txnId ? { txnId: str(s.txnId, 40) } : {}),
// Category and payment method of the bill, and when it was added (for ordering in Activity).
...(s.cat ? { cat: str(s.cat, 40) } : {}), ...(MODES.some((m) => m.id === s.mode) ? { mode: s.mode } : {}),
...(Number(s.ts) > 0 ? { ts: Number(s.ts) } : {}),
};
});
const friends = [];
arr(d.friends).forEach((f) => {
const name = f && str(f.name, 30).trim();
if (name && !friends.some((x) => fkey(x.name) === fkey(name))) friends.push({ name, phone: cleanPhone(f.phone) });
});
return { settings, customCats, txns, budgets: { total: pos(b.total), cats }, goals, bills, splits, friends };
}
// ---------- Persisting (diffs each document against what was last stored) ----------
let lastSaved = {};
let saveTimer = null;
let writeChain = Promise.resolve();
let pendingWrites = 0;
let lastLoad = 0;
const FAILED = '\u0000failed';
const snapshotOf = (docs) => Object.fromEntries(Object.entries(docs).map(([k, v]) => [k, stableJson(v)]));
let loadFailed = false;
function persist() {
if (state.sample || loadFailed) return;
clearTimeout(saveTimer);
saveTimer = setTimeout(flush, 350);
}
function flush() {
clearTimeout(saveTimer);
saveTimer = null;
if (state.sample || loadFailed) return;
const docs = buildDocs();
const keys = new Set([...Object.keys(docs), ...Object.keys(lastSaved)]);
for (const k of keys) {
const json = docs[k] ? stableJson(docs[k]) : null;
if (json === (lastSaved[k] ?? null)) continue;
if (json === null) delete lastSaved[k]; else lastSaved[k] = json;
pendingWrites++;
const target = store;
const write = () => (json === null ? target.del(k) : target.set(k, JSON.parse(json)));
const fail = (e) => {
if (store === target) lastSaved[k] = FAILED;
toast(saveErrorText(e));
};
if (target.fireAndForget) Promise.resolve().then(write).catch(fail).finally(() => { pendingWrites--; });
else writeChain = writeChain.then(write).catch(fail).finally(() => { pendingWrites--; });
}
scheduleAutoBackup();
}
function saveErrorText(e) {
const code = (e && (e.code || e.name)) || '';
if (code === 'quota_exceeded' || code === 'QuotaExceededError' || code === 'resource-exhausted') return 'Storage is full. Export a backup and delete old entries.';
if (code === 'permission-denied') return 'You don’t have permission to change this book any more.';
return "Couldn't save your last change. It will retry on your next edit.";
}
async function refreshFromStore() {
if (!state.loaded || store.live || state.sample || pendingWrites || saveTimer || Date.now() - lastLoad < 15000) return;
if (Object.values(lastSaved).includes(FAILED)) { persist(); return; }
try {
const docs = await store.loadAll();
lastLoad = Date.now();
const snap = snapshotOf(docs);
if (stableJson(snap) === stableJson(lastSaved) || !hasBook(docs) || pendingWrites || saveTimer) return;
applyDocs(docs);
lastSaved = snap;
setCurrency(state.settings.currency);
applyTheme();
if (!sheets.length) render();
} catch { /* offline: keep what is on screen */ }
}
// A document changed somewhere else (another device, or someone sharing this book).
function applyRemote(changes) {
let touched = false;
for (const { key, data } of changes) {
const json = data ? stableJson(data) : null;
if (json === (lastSaved[key] ?? null)) continue; // our own write coming back
if (json === null) delete lastSaved[key]; else lastSaved[key] = json;
if (state.sample && !sampleStash) {
// First real data arrived while samples were showing: drop the samples.
const settings = state.settings;
Object.assign(state, emptyData(), { settings, sample: false, started: true });
}
applyDocTo(state.sample && sampleStash ? sampleStash : state, key, data);
touched = true;
}
if (touched) scheduleRender();
}
function applyDocTo(target, key, data) {
const slash = key.indexOf('/');
const col = key.slice(0, slash), id = key.slice(slash + 1);
if (col === 'meta') {
const clean = sanitizeData({ settings: data && data.settings, budgets: data && data.budgets, customCats: data && data.customCats, friends: data && data.friends });
if (target === state) { state.settings = clean.settings; setCurrency(clean.settings.currency); }
target.budgets = clean.budgets;
target.customCats = clean.customCats;
target.friends = clean.friends;
return;
}
if (!ITEM_COLS.includes(col)) return;
const rest = target[col].filter((x) => x.id !== id);
const item = data ? sanitizeData({ [col]: [{ ...data, id }] })[col][0] : null;
target[col] = item ? [...rest, item] : rest;
}
let renderTimer;
function scheduleRender() {
clearTimeout(renderTimer);
renderTimer = setTimeout(() => {
if (!state.loaded) return;
if (ui.tab === 'txns' && document.activeElement && document.activeElement.id === 'tx-q') renderTxList();
else render();
}, 120);
}
// Every change goes through here. While sample data is showing, the first real
// change clears the samples and starts the person's own book.
function commit(fn, { keepSample = false } = {}) {
let fresh = false;
if (state.sample && !keepSample) {
const settings = state.settings;
Object.assign(state, sampleStash || emptyData(), { settings, sample: false, started: true });
sampleStash = null;
fresh = true;
}
fn();
persist();
render();
return fresh;
}
const freshNote = (fresh) => (fresh ? ' Sample data cleared.' : '');
function upsert(list, item) {
const i = list.findIndex((x) => x.id === item.id);
if (i >= 0) list[i] = item; else list.push(item);
}
// ============================================================
// Sample data (shown on first open, never saved)
// ============================================================
function mulberry32(a) {
return () => {
a |= 0; a = (a + 0x6d2b79f5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function makeSample() {
const rnd = mulberry32(20261005);
const pick = (arr) => arr[Math.floor(rnd() * arr.length)];
const between = (a, b, step = 10) => Math.round((a + rnd() * (b - a)) / step) * step;
const mode = () => { const r = rnd(); return r < 0.58 ? 'upi' : r < 0.72 ? 'cash' : r < 0.82 ? 'debit' : r < 0.93 ? 'credit' : 'wallet'; };
const txns = [];
const add = (type, cat, amount, date, note, m) => txns.push({ id: uid() + txns.length, type, cat, amount, date, note, mode: m || mode(), ts: parseDate(date).getTime() + txns.length });
const now = new Date();
for (let back = 5; back >= 0; back--) {
const base = new Date(now.getFullYear(), now.getMonth() - back, 1);
const key = toDateStr(base).slice(0, 7);
const last = back === 0 ? now.getDate() : daysInMonth(key);
const ds = (d) => `${key}-${pad2(d)}`;
add('income', 'salary', 68000, ds(1), 'Monthly salary', 'netbanking');
if (back % 2 === 0 && last >= 15) add('income', 'freelance', between(8000, 16000, 500), ds(15), 'Website project', 'netbanking');
if (back === 2 && last >= 20) add('income', 'refund', 450, ds(20), 'Cashback', 'upi');
if (last >= 3) add('expense', 'rent', 16000, ds(3), 'House rent', 'netbanking');
if (last >= 5) add('expense', 'emi', 3200, ds(5), 'Bike EMI', 'netbanking');
if (last >= 6) add('expense', 'invest', 5000, ds(6), 'Mutual fund SIP', 'netbanking');
for (let d = 1; d <= last; d++) {
const date = ds(d);
const wd = parseDate(date).getDay();
const weekday = wd !== 0 && wd !== 6;
if (weekday && rnd() < 0.62) add('expense', 'food', between(80, 200, 5), date, pick(['Office canteen lunch', 'Lunch – thali', 'Lunch with team', 'Dosa & coffee']));
if (rnd() < 0.16) add('expense', 'food', between(260, 680), date, pick(['Swiggy dinner', 'Zomato order', 'Dinner out', 'Pizza night']));
if (rnd() < 0.3) add('expense', 'food', between(20, 90, 5), date, pick(['Chai & snacks', 'Coffee', 'Juice']), 'cash');
if (weekday && rnd() < 0.6) add('expense', 'transport', between(30, 140, 5), date, pick(['Metro', 'Auto to office', 'Bus pass top-up', 'Cab home']));
if (d % 5 === 2) add('expense', 'groceries', between(500, 2200), date, pick(['Weekly groceries', 'Vegetables & fruits', 'Milk & essentials', 'Supermarket run']));
if (d === 7 || d === 21) add('expense', 'fuel', between(1500, 2600, 50), date, pick(['Petrol – full tank', 'Petrol top-up']));
if (rnd() < 0.05) add('expense', 'shopping', between(450, 3200, 50), date, pick(['T-shirts', 'Shoes', 'Kitchen items', 'Amazon order']));
if (rnd() < 0.045) add('expense', 'entertainment', between(250, 900, 50), date, pick(['Movie tickets', 'Bowling', 'Concert entry']));
if (rnd() < 0.025) add('expense', 'health', between(150, 1200), date, pick(['Pharmacy', 'Doctor visit', 'Lab test']));
if (rnd() < 0.02) add('expense', 'personal', between(200, 700, 50), date, pick(['Haircut', 'Salon']));
if (rnd() < 0.012) add('expense', 'gifts', between(500, 2000, 100), date, pick(['Birthday gift', 'Wedding gift']));
}
if (last >= 12) add('expense', 'bills', between(1100, 1900), ds(12), 'Electricity bill');
if (last >= 8) add('expense', 'bills', 799, ds(8), 'Broadband');
if (last >= 18) add('expense', 'recharge', 299, ds(18), 'Mobile recharge');
if (last >= 22) add('expense', 'subs', 199, ds(22), 'Netflix');
if (back % 3 === 1 && last >= 16) add('expense', 'bike', between(900, 1800, 50), ds(16), 'Bike service');
if (back === 3 && last >= 14) add('expense', 'travel', 6400, ds(14), 'Train tickets – Goa trip', 'credit');
if (back === 1 && last >= 10) add('expense', 'education', 2499, ds(10), 'Online course', 'credit');
}
const t = todayStr();
const dueOn = (day, minAhead = 0) => {
const d = new Date(); d.setDate(d.getDate() + minAhead);
let c = new Date(d.getFullYear(), d.getMonth(), day);
if (toDateStr(c) < toDateStr(d)) c = new Date(d.getFullYear(), d.getMonth() + 1, day);
return toDateStr(c);
};
const bills = [
{ id: 's-b1', name: 'House rent', amount: 16000, cat: 'rent', freq: 'monthly', nextDue: dueOn(3), day: 3, mode: 'netbanking' },
{ id: 's-b2', name: 'Broadband', amount: 799, cat: 'bills', freq: 'monthly', nextDue: addDays(t, -2), day: parseDate(addDays(t, -2)).getDate(), mode: 'upi' },
{ id: 's-b3', name: 'Electricity', amount: 1600, cat: 'bills', freq: 'monthly', nextDue: addDays(t, 2), day: parseDate(addDays(t, 2)).getDate(), mode: 'upi' },
{ id: 's-b4', name: 'Mobile recharge', amount: 299, cat: 'recharge', freq: 'monthly', nextDue: dueOn(18), day: 18, mode: 'upi' },
{ id: 's-b5', name: 'Netflix', amount: 199, cat: 'subs', freq: 'monthly', nextDue: dueOn(22), day: 22, mode: 'credit' },
{ id: 's-b6', name: 'Bike insurance', amount: 2850, cat: 'bike', freq: 'yearly', nextDue: addDays(t, 41), day: parseDate(addDays(t, 41)).getDate(), mode: 'upi' },
];
const inMonths = (n) => { const d = new Date(); d.setMonth(d.getMonth() + n); return toDateStr(d); };
const goals = [
{ id: 's-g1', name: 'Emergency fund', icon: 'savings', target: 150000, saved: 62000, deadline: inMonths(10), h: 145 },
{ id: 's-g2', name: 'New phone', icon: 'smartphone', target: 45000, saved: 18500, deadline: inMonths(4), h: 210 },
{ id: 's-g3', name: 'Goa trip', icon: 'beach_access', target: 30000, saved: 9000, deadline: inMonths(6), h: 24 },
];
const splits = [
{ id: 's-s1', title: 'Team dinner', date: addDays(t, -3), total: 3200, paidBy: 'me', myShare: 800, iSettled: false,
people: [{ name: 'Rahul', share: 800, settled: false }, { name: 'Priya', share: 800, settled: false, paid: 300 }, { name: 'Arjun', share: 800, settled: true }] },
{ id: 's-s2', title: 'Weekend movie', date: addDays(t, -6), total: 900, paidBy: 'Priya', myShare: 300, iSettled: false,
people: [{ name: 'Priya', share: 300, settled: true }, { name: 'Neha', share: 300, settled: false }] },
{ id: 's-s3', title: 'Lunch at Meghana’s', date: addDays(t, -1), total: 1240, paidBy: 'me', myShare: 620, iSettled: false,
people: [{ name: 'Rahul', share: 620, settled: false }] },
{ id: 's-s4', title: 'Rahul’s bus ticket', date: addDays(t, -9), total: 450, paidBy: 'me', myShare: 0, iSettled: false,
people: [{ name: 'Rahul', share: 450, settled: false }] },
];
const budgets = { total: 42000, cats: { food: 9000, groceries: 6000, transport: 2500, fuel: 4500, shopping: 3000, entertainment: 1500, bills: 3500 } };
return { txns, bills, goals, splits, budgets, customCats: [], friends: [] };
}
function loadSample() {
Object.assign(state, makeSample(), { sample: true });
}
// ============================================================
// Derived numbers
// ============================================================
const sortTx = (list) => list.sort((a, b) => b.date.localeCompare(a.date) || (b.ts || 0) - (a.ts || 0));
const maxMonth = () => state.txns.reduce((m, t) => (t.date.slice(0, 7) > m ? t.date.slice(0, 7) : m), thisMonth());
const txIn = (key, type) => state.txns.filter((t) => t.date.startsWith(key) && (!type || t.type === type));
function totals(key) {
let inc = 0, exp = 0;
for (const t of state.txns) if (t.date.startsWith(key)) { if (t.type === 'income') inc += t.amount; else exp += t.amount; }
return { inc, exp, bal: inc - exp };
}
function byCat(list) {
const m = new Map();
for (const t of list) m.set(t.cat, (m.get(t.cat) || 0) + t.amount);
return [...m].map(([cat, amt]) => ({ cat, amt })).sort((a, b) => b.amt - a.amt);
}
const budgetLevel = (spent, limit) => (!limit ? 'none' : spent > limit ? 'over' : spent >= 0.8 * limit ? 'warn' : 'ok');
function daysElapsed(key) {
const nowKey = thisMonth();
if (key === nowKey) return new Date().getDate();
return key < nowKey ? daysInMonth(key) : 0;
}
const FREQS = { monthly: 'Monthly', quarterly: 'Every 3 months', yearly: 'Yearly', weekly: 'Weekly' };
function advanceDue(bill) {
if (bill.freq === 'weekly') return addDays(bill.nextDue, 7);
const d = parseDate(bill.nextDue);
const months = bill.freq === 'yearly' ? 12 : bill.freq === 'quarterly' ? 3 : 1;
const target = new Date(d.getFullYear(), d.getMonth() + months, 1);
const dim = new Date(target.getFullYear(), target.getMonth() + 1, 0).getDate();
target.setDate(Math.min(bill.day || d.getDate(), dim));
return toDateStr(target);
}
function billStatus(b) {
const n = diffDays(b.nextDue, todayStr());
if (n < 0) return { cls: 'err', icon: 'error', text: `Overdue ${plural(-n, 'day')}`, n };
if (n === 0) return { cls: 'warn', icon: 'schedule', text: 'Due today', n };
if (n === 1) return { cls: 'warn', icon: 'schedule', text: 'Due tomorrow', n };
if (n <= 3) return { cls: 'warn', icon: 'schedule', text: `Due in ${n} days`, n };
if (n <= 7) return { cls: 'info', icon: 'event', text: `Due in ${n} days`, n };
return { cls: '', icon: 'event', text: `Due ${dateLabel(b.nextDue)}`, n };
}
const monthlyEquiv = (b) => (b.freq === 'yearly' ? b.amount / 12 : b.freq === 'quarterly' ? b.amount / 3 : b.freq === 'weekly' ? (b.amount * 52) / 12 : b.amount);
// What is still to come back on one share, and on your own share of a bill someone else paid.
const shareLeft = (p) => (p.settled ? 0 : round2(Math.max(0, p.share - (p.paid || 0))));
const myLeft = (s) => (s.iSettled ? 0 : round2(Math.max(0, s.myShare - (s.myPaid || 0))));
// Everything between you and each friend. Items are oldest first; dir 1 = they owe you
// (you paid), dir -1 = you owe them (they paid). net > 0 means they owe you overall.
function friendLedger() {
const map = new Map();
const get = (name) => {
const k = fkey(name);
if (!map.has(k)) map.set(k, { key: k, name: String(name).trim(), phone: '', net: 0, items: [], last: '' });
return map.get(k);
};
for (const f of state.friends) Object.assign(get(f.name), { name: f.name, phone: f.phone });
for (const s of state.splits) {
if (s.paidBy === 'me') {
s.people.forEach((p, i) => {
if (!(p.share > 0)) return;
const f = get(p.name);
const left = shareLeft(p);
f.items.push({ s, i, dir: 1, share: p.share, left });
f.net += left;
if (s.date > f.last) f.last = s.date;
});
} else if (s.myShare > 0) {
const f = get(s.paidBy);
const left = myLeft(s);
f.items.push({ s, i: 'me', dir: -1, share: s.myShare, left });
f.net -= left;
if (s.date > f.last) f.last = s.date;
}
}
for (const f of map.values()) {
f.net = round2(f.net);
f.items.sort((a, b) => a.s.date.localeCompare(b.s.date) || a.s.id.localeCompare(b.s.id));
}
return map;
}
function splitBalances() {
const list = [...friendLedger().values()].filter((p) => Math.abs(p.net) > 0.009).sort((a, b) => b.net - a.net);
return { list, owed: sum(list.filter((p) => p.net > 0), (p) => p.net), owe: -sum(list.filter((p) => p.net < 0), (p) => p.net) };
}
// How a bill divides between you (index 0) and the people named. 'equal': everyone pays the
// same. 'others': whoever paid isn't part of it, the rest share it equally. Rounding paise go
// to the first person who has a share.
function divideBill(total, names, paidBy, how) {
const out = Array(names.length + 1).fill(0);
const payer = paidBy === 'me' ? 0 : names.indexOf(paidBy) + 1;
const takers = out.map((_, i) => i).filter((i) => how !== 'others' || i !== payer);
if (!takers.length || !(total > 0)) return out;
const each = round2(total / takers.length);
takers.forEach((i) => { out[i] = each; });
out[takers[0]] = round2(total - each * (takers.length - 1));
return out;
}
const namesList = (names) => (names.length <= 2 ? names.join(' and ') : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`);
function goalPlan(g) {
const left = Math.max(0, g.target - g.saved);
if (!g.deadline || left <= 0) return { left, perMonth: 0, months: 0 };
const d = parseDate(g.deadline), n = new Date();
const months = Math.max(1, (d.getFullYear() - n.getFullYear()) * 12 + (d.getMonth() - n.getMonth()));
return { left, perMonth: left / months, months };
}
const hueOf = (name) => HUES[[...String(name)].reduce((a, c) => a + c.charCodeAt(0), 0) % HUES.length];
const initial = (name) => esc(([...String(name).trim()][0] || '?').toUpperCase());
// ============================================================
// Theme
// ============================================================
function applyTheme() {
const t = ui.theme;
const root = document.documentElement;
if (t === 'light' || t === 'dark') root.setAttribute('data-app-theme', t); else root.removeAttribute('data-app-theme');
const meta = document.querySelector('meta[name="theme-color"]');
const bg = getComputedStyle(root).getPropertyValue('--bg').trim();
if (meta && bg) meta.setAttribute('content', bg);
const bar = nativePlugin('StatusBar');
if (bar && bg) {
const dark = t === 'dark' || (t === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches);
bar.setBackgroundColor({ color: bg }).catch(() => {});
bar.setStyle({ style: dark ? 'DARK' : 'LIGHT' }).catch(() => {});
}
}
try {
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { applyTheme(); drawCharts(); });
} catch { /* old browsers */ }
// ============================================================
// Rendering: shared bits
// ============================================================
const charts = {};
let chartSeq = 0;
function chartSlot(spec) {
const id = 'c' + ++chartSeq;
charts[id] = spec;
return `<div class="chart" data-chart="${id}" style="height:${spec.height}px" role="img" aria-label="${esc(spec.label)}"></div>`;
}
const monthBar = (opts = {}) => `
<div class="month-bar" role="group" aria-label="Month">
<button class="icon-btn sm" type="button" data-act="month-prev" aria-label="Previous month">${ic('chevron_left')}</button>
<span class="label">${monthLabel(ui.month)}${opts.note ? ` <span class="faint">· ${esc(opts.note)}</span>` : ''}</span>
<button class="icon-btn sm" type="button" data-act="month-next" aria-label="Next month" ${ui.month >= maxMonth() ? 'disabled style="opacity:.3"' : ''}>${ic('chevron_right')}</button>
</div>`;
const shortNames = (names) => (names.length <= 2 ? names.join(' & ') : `${names[0]} +${names.length - 1}`);
function txItem(t, { showDate = false } = {}) {
const c = getCat(t.cat);
const title = t.note || c.name;
const who = session.book && t.by ? memberName(t.by) : null;
const sp = t.splitId ? state.splits.find((s) => s.id === t.splitId) : null;
const mates = sp ? sp.people.map((p) => p.name) : [];
const sub = [t.note ? c.name : null, mates.length ? `with ${shortNames(mates)}` : null, modeOf(t.mode).name, who, showDate ? dayLabel(t.date) : null].filter(Boolean).join(' · ');
// A split bill shows your share, with the whole bill (or who paid it) underneath.
const whole = sp && sp.paidBy === 'me' && sp.total > t.amount + 0.005 ? `of ${money(sp.total)}` : sp && sp.paidBy !== 'me' ? `${sp.paidBy} paid` : '';
const isIn = t.type === 'income';
return `<button class="li" type="button" data-act="open-tx" data-id="${esc(t.id)}">
${catIco(c)}
<span class="li-main"><span class="li-title">${esc(title)}</span><span class="li-sub">${esc(sub)}</span></span>
<span class="li-end"><span class="amt ${isIn ? 'in' : ''}">${isIn ? '+' : ''}${esc(money(t.amount))}</span>${whole ? `<small class="faint">${esc(whole)}</small>` : ''}</span>
</button>`;
}
// Bills shared with friends that have no expense of yours attached: you paid only for them, or
// a friend paid and your share wasn't logged. They show in Activity so nothing goes missing,
// but they aren't your spending.
function looseSplits() {
const ids = new Set(state.txns.map((t) => t.id));
return state.splits.filter((s) => !(s.txnId && ids.has(s.txnId)));
}
const lentIn = (s) => (s.paidBy === 'me' ? round2(sum(s.people, (p) => p.share)) : 0);
function splitItem(s, { showDate = false } = {}) {
const mine = s.paidBy === 'me';
const c = s.cat ? getCat(s.cat) : null;
const names = s.people.map((p) => p.name);
const sub = [mine ? `Paid for ${shortNames(names)}` : `${s.paidBy} paid ${money(s.total)}`, showDate ? dayLabel(s.date) : null].filter(Boolean).join(' · ');
const open = mine ? sum(s.people, shareLeft) > 0 : myLeft(s) > 0;
const status = mine ? (open ? `${names.length === 1 ? 'owes' : 'owe'} you` : 'paid back') : open ? 'you owe' : 'settled';
return `<button class="li" type="button" data-act="open-split" data-id="${esc(s.id)}">
${c ? catIco(c) : `<span class="cat-ico" style="--h:268">${ic('group')}</span>`}
<span class="li-main"><span class="li-title">${esc(s.title)}</span><span class="li-sub">${esc(sub)}</span></span>
<span class="li-end"><span class="amt lent">${esc(money(mine ? lentIn(s) : s.myShare))}</span><small class="faint">${esc(status)}</small></span>
</button>`;
}
const emptyState = (icon, title, text, btn = '') => `<div class="empty">${ic(icon)}<b>${esc(title)}</b><span>${esc(text)}</span>${btn}</div>`;
function meterHtml(spent, limit, label, cls = '') {
const lvl = budgetLevel(spent, limit);
const p = limit ? Math.min(100, (spent / limit) * 100) : 0;
return `<div class="meter ${lvl === 'over' ? 'over' : lvl === 'warn' ? 'warn' : ''} ${cls}" role="progressbar" aria-label="${esc(label)}" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${Math.round(p)}"><i style="width:${p}%"></i></div>`;
}
const progressHtml = (p, label) => `<div class="meter" role="progressbar" aria-label="${esc(label)}" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${Math.round(p * 100)}"><i style="width:${clamp(p, 0, 1) * 100}%"></i></div>`;
function levelNote(spent, limit) {
const lvl = budgetLevel(spent, limit);
if (lvl === 'over') return `<span class="pill err">${ic('error')}Over by ${esc(money(spent - limit, { whole: true }))}</span>`;
if (lvl === 'warn') return `<span class="pill warn">${ic('warning')}${esc(money(limit - spent, { whole: true }))} left</span>`;
return `<span class="pill ok">${ic('check_circle')}${esc(money(limit - spent, { whole: true }))} left</span>`;
}
const BRAND = '<span class="brand-mark" aria-hidden="true">₹</span><span>Kharcha</span>';
const isWide = () => window.matchMedia('(min-width: 840px)').matches;
// A layout slot: on phones every slot stacks in its order number; on wide screens slots sit in two columns.
const slot = (html, n) => (html ? `<div class="slot o${n}">${html}</div>` : '');
function accountControls() {
if (session.mode === 'firebase' && session.user) {
const name = session.book ? session.book.name : 'My book';
return `<button class="book-chip" type="button" data-act="account" title="Switch book">${ic(session.book ? 'group' : 'person', 'sm')}<span>${esc(name)}</span>${ic('arrow_drop_down', 'sm')}</button>
<button class="avatar-btn" type="button" data-act="account" aria-label="Account and books">${avatarHtml(session.user)}</button>`;
}
return `<button class="icon-btn" type="button" data-act="settings" aria-label="Settings">${ic('settings')}</button>`;
}
function topbarHtml(title, extra = '') {
const head = ui.tab === 'home'
? `<div class="brand only-mobile">${BRAND}</div><h1 class="only-desktop">${esc(title)}</h1>`
: `<h1>${esc(title)}</h1>`;
return `<header class="topbar">${head}${extra}${accountControls()}</header>`;
}
const exportBtn = () => `<button class="icon-btn" type="button" data-act="export" aria-label="Export to CSV">${ic('download')}</button>`;
function renderBanner() {
const el = $('#banner');
if (loadFailed) {
el.innerHTML = `<div class="banner" role="alert">${ic('cloud_off')}<p>Couldn’t load your saved data, so nothing you change now will be saved.</p><button class="btn btn-text" type="button" data-act="retry-load">Try again</button></div>`;
return;
}
if (!state.sample) { el.innerHTML = ''; return; }
el.innerHTML = sampleStash
? `<div class="banner" role="note">${ic('science')}<p>You're looking at sample data. Your own book is safe and comes back when you add an entry.</p><button class="btn btn-text" type="button" data-act="exit-sample">Show my data</button></div>`
: `<div class="banner" role="note">${ic('science')}<p>You're looking at sample data. Your first entry clears it and starts your own book.</p><button class="btn btn-text" type="button" data-act="start-fresh">Start fresh</button></div>`;
}
function updateChrome() {
$$('.nav-item').forEach((b) => b.setAttribute('aria-current', b.dataset.tab === ui.tab ? 'page' : 'false'));
const fab = $('#fab');
let f = null;
if (ui.tab === 'home' || ui.tab === 'txns') f = { label: 'Add expense', icon: 'add', act: 'add' };
if (ui.tab === 'plan') {
f = { budgets: { label: 'Edit budgets', icon: 'edit', act: 'edit-budgets' }, goals: { label: 'New goal', icon: 'add', act: 'add-goal' }, bills: { label: 'Add bill', icon: 'add', act: 'add-bill' }, split: { label: 'Split a bill', icon: 'add', act: 'add-split' } }[ui.plan];
}
fab.hidden = !f || !state.loaded;
if (f) { fab.innerHTML = `${ic(f.icon)}<span>${f.label}</span>`; fab.dataset.act = f.act; }
$('#screen').classList.toggle('no-fab', !f);
}
let lastTab = null;
function render() {
if (!state.loaded) return;
Object.keys(charts).forEach((k) => delete charts[k]);
renderBanner();
const screen = $('#screen');
const html = { home: renderHome, txns: renderTxns, insights: renderInsights, plan: renderPlan, tools: renderTools }[ui.tab]();
screen.dataset.tab = ui.tab;
screen.innerHTML = html;
if (ui.tab === 'txns') renderTxList();
if (ui.tab === 'tools') updateCalc();
drawCharts(screen);
updateChrome();
if (lastTab !== ui.tab) { window.scrollTo(0, 0); lastTab = ui.tab; }
// Open pages that show live numbers (a friend's balance) redraw with the new data.
sheets.forEach((sh) => { if (sh.onData) sh.onData(); });
}
function setTab(tab) {
if (!['home', 'txns', 'insights', 'plan', 'tools'].includes(tab)) tab = 'home';
ui.tab = tab;
prefsSave();
render();
}
// ============================================================
// Home
// ============================================================
function renderHome() {
const key = ui.month;
const isNow = key === thisMonth();
const { inc, exp, bal } = totals(key);
const today = sum(state.txns.filter((t) => t.type === 'expense' && t.date === todayStr()), (t) => t.amount);
const budget = state.budgets.total;
const hr = new Date().getHours();
const hello = hr < 5 ? 'Good night' : hr < 12 ? 'Good morning' : hr < 17 ? 'Good afternoon' : 'Good evening';
const first = session.user ? session.user.name.split(' ')[0] : state.settings.name;
const name = first ? `, ${esc(first)}` : '';
const now = new Date();
let budgetHtml;
if (budget > 0) {
const left = budget - exp;
const daysLeft = isNow ? daysInMonth(key) - now.getDate() + 1 : 0;
const perDay = isNow && left > 0 ? Math.floor(left / daysLeft) : 0;
const p = Math.min(100, (exp / budget) * 100);
budgetHtml = `<div class="meter ${exp > budget ? 'over' : ''}" role="progressbar" aria-label="Monthly budget used" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${Math.round(p)}"><i style="width:${p}%"></i></div>
<p>${left >= 0 ? `<b>${esc(money(left, { whole: true }))}</b> left of ${esc(money(budget, { whole: true }))}` : `<b>${esc(money(-left, { whole: true }))}</b> over your ${esc(money(budget, { whole: true }))} budget`}${perDay ? ` · ${esc(money(perDay, { whole: true }))}/day for ${plural(daysLeft, 'day')}` : ''}</p>`;
} else {
budgetHtml = `<p>No monthly budget yet. <button class="hero-link" type="button" data-act="edit-budgets">Set one</button></p>`;
}
const amt = money(exp);
const amtHtml = esc(amt).replace(/(\.\d\d)$/, '<span class="dec">$1</span>');
const quick = ['food', 'transport', 'fuel', 'bike', 'groceries', 'shopping', 'bills', 'recharge', 'health'].map((id) => {
const c = getCat(id);
return `<button class="quick-tile" type="button" data-act="add" data-cat="${c.id}">${catIco(c, 'lg')}<span>${esc(c.short)}</span></button>`;
}).join('') + `<button class="quick-tile" type="button" data-act="add" data-type="income"><span class="cat-ico lg" style="--h:145">${ic('add_card')}</span><span>Income</span></button>`;
// Alerts
const alerts = [];
if (isNow) {
const spentBy = new Map(byCat(txIn(key, 'expense')).map((x) => [x.cat, x.amt]));
Object.entries(state.budgets.cats).forEach(([cat, lim]) => {
const s = spentBy.get(cat) || 0;
const lvl = budgetLevel(s, lim);
if (lvl === 'over') alerts.push({ w: 3, cls: 'err', icon: 'error', html: `<b>${esc(getCat(cat).name)}</b> is over budget by ${esc(money(s - lim, { whole: true }))}`, act: 'data-act="goto" data-tab="plan" data-plan="budgets"' });
else if (lvl === 'warn') alerts.push({ w: 2, cls: 'warn', icon: 'warning', html: `<b>${esc(getCat(cat).name)}</b>: ${pct(s / lim)} of budget used`, act: 'data-act="goto" data-tab="plan" data-plan="budgets"' });
});
}
state.bills.forEach((b) => {
const st = billStatus(b);
if (st.n < 0) alerts.push({ w: 4, cls: 'err', icon: 'event_busy', html: `<b>${esc(b.name)}</b> bill of ${esc(money(b.amount))} is overdue`, act: 'data-act="goto" data-tab="plan" data-plan="bills"' });