Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
2054 lines (1868 loc) · 109 KB
/
Copy pathscript.js
File metadata and controls
2054 lines (1868 loc) · 109 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
// ============================================================
// ACTIVITYPLUS - PRO JAVASCRIPT
// ============================================================
// --- LOADING: light splash + thin top progress bar --------------------------
// Splash (#loadingScreen) shows only until login/data are ready (no fixed delay).
const hideSplash = () => {
const screen = document.getElementById('loadingScreen');
if (screen) screen.classList.add('hidden');
};
setTimeout(hideSplash, 8000); // safety net
// Top bar (#topBar) runs while data loads or saves. It never blocks the screen.
let busyCount = 0;
function setBusy() {
busyCount++;
const el = document.getElementById('topBar');
if (el) el.classList.add('on');
}
function clearBusy() {
busyCount = Math.max(0, busyCount - 1);
if (busyCount > 0) return;
const el = document.getElementById('topBar');
if (el) el.classList.remove('on');
}
async function withBusy(message, fn) {
setBusy();
try { return await fn(); }
finally { clearBusy(); }
}
const nextPaint = () => new Promise(r => requestAnimationFrame(() => setTimeout(r, 0)));
// ============================================================
// PASSWORD EYE TOGGLE
// ============================================================
function setupEyeToggles() {
// Login eye
const loginEye = document.getElementById('loginEye');
const loginPassword = document.getElementById('loginPassword');
if (loginEye && loginPassword) {
loginEye.addEventListener('click', () => {
const isPassword = loginPassword.type === 'password';
loginPassword.type = isPassword ? 'text' : 'password';
const icon = loginEye.querySelector('i');
if (icon) {
icon.className = isPassword ? 'ph-bold ph-eye-slash' : 'ph-bold ph-eye';
}
});
}
// All other eye toggles (data-target)
document.querySelectorAll('.eye-toggle[data-target]').forEach(btn => {
btn.addEventListener('click', () => {
const target = document.getElementById(btn.dataset.target);
if (!target) return;
const isPassword = target.type === 'password';
target.type = isPassword ? 'text' : 'password';
const icon = btn.querySelector('i');
if (icon) {
icon.className = isPassword ? 'ph-bold ph-eye-slash' : 'ph-bold ph-eye';
}
});
});
}
// ============================================================
// MAIN APP DATA
// ============================================================
const KEY = "activityplus_v2";
const CATS = ["Salary", "Food", "Transport", "Shopping", "Bills", "Entertainment", "Business", "Other"];
const defaultData = {
transactions: [],
goals: [],
wallets: [
{ id: 1, name: "Cash", fullName: "", kind: "Personal", type: "Cash", currency: "USD" },
{ id: 2, name: "E-Wallet", fullName: "", kind: "Personal", type: "E-Wallet", currency: "SLSH" },
{ id: 3, name: "Bank", fullName: "", kind: "Personal", type: "Bank", currency: "ETB" }
],
budgets: [],
savingsTx: [],
rates: { USD_SLSH: 0, USD_ETB: 0 }
};
let data = JSON.parse(JSON.stringify(defaultData));
data.transactions = data.transactions || [];
data.goals = data.goals || [];
data.wallets = data.wallets || defaultData.wallets;
data.budgets = data.budgets || [];
let currentCurrency = "ALL";
document.body.dataset.section = "dashboard";
const $ = s => document.querySelector(s);
const $$ = s => document.querySelectorAll(s);
const normalizeWallet = w => ({
...w,
kind: w.kind === "Business" ? "Business" : "Personal", // older wallets default to Personal
fullName: w.fullName || "",
account: w.account || ""
});
const normalizeData = (value) => {
const x = value && typeof value === "object" ? value : {};
const wallets = Array.isArray(x.wallets) && x.wallets.length ? x.wallets : JSON.parse(JSON.stringify(defaultData.wallets));
return {
transactions: Array.isArray(x.transactions) ? x.transactions : [],
goals: Array.isArray(x.goals) ? x.goals : [],
wallets: wallets.map(normalizeWallet),
budgets: Array.isArray(x.budgets) ? x.budgets : [],
savingsTx: Array.isArray(x.savingsTx) ? x.savingsTx : [],
rates: {
USD_SLSH: Number(x.rates?.USD_SLSH) > 0 ? Number(x.rates.USD_SLSH) : 0,
USD_ETB: Number(x.rates?.USD_ETB) > 0 ? Number(x.rates.USD_ETB) : 0
}
};
};
let currentUser = null;
let serverStamp = null; // updated_at of the row we last loaded / saved (stops a stale device overwriting newer data)
let lastSaved = null; // last state the server confirmed (used to undo a save that failed)
let savingsInDb = false; // savings goals + savings transactions live in their own tables
let saveChain = Promise.resolve();
// The main row (wallets, transactions, budgets, rates). Savings are kept in their own tables.
const blobOf = d => {
const n = normalizeData(d);
return savingsInDb ? { ...n, goals: [], savingsTx: [] } : n;
};
function rollbackLocal() {
if (!lastSaved) return;
const keepGoals = data.goals, keepTx = data.savingsTx;
data = normalizeData(JSON.parse(lastSaved));
if (savingsInDb) { data.goals = keepGoals; data.savingsTx = keepTx; }
renderAll();
}
function applyRemote(row) {
const keepGoals = data.goals, keepTx = data.savingsTx;
data = normalizeData(row.data);
if (savingsInDb) { data.goals = keepGoals; data.savingsTx = keepTx; }
serverStamp = row.updated_at || null;
lastSaved = JSON.stringify(normalizeData(row.data));
}
async function handleConflict(showError) {
const { data: row, error } = await sb.from("activityplus_data").select("data, updated_at").eq("user_id", currentUser.id).maybeSingle();
if (error) {
rollbackLocal();
if (showError) toast("Could not save: " + error.message);
return false;
}
if (!row || row.updated_at === serverStamp) { // nothing newer exists: write normally
serverStamp = null;
return await persist(showError);
}
applyRemote(row); // another device saved first: load its data
renderAll();
if (showError) toast("Your data was changed on another device. It was reloaded - please repeat your last action.");
return false;
}
async function persist(showError) {
if (!sb || !currentUser) {
if (showError) toast("Please login first.");
return false;
}
renderAll(); // show the change instantly; saving happens in the background
setBusy();
try {
const payload = blobOf(data);
const stamp = new Date().toISOString();
let res;
if (serverStamp) {
res = await sb.from("activityplus_data")
.update({ data: payload, updated_at: stamp })
.eq("user_id", currentUser.id).eq("updated_at", serverStamp)
.select("updated_at");
if (!res.error && !(res.data && res.data.length)) return await handleConflict(showError);
} else {
res = await sb.from("activityplus_data")
.upsert({ user_id: currentUser.id, data: payload, updated_at: stamp }, { onConflict: "user_id" })
.select("updated_at");
}
if (res.error) {
console.error("ActivityPlus save error:", res.error);
rollbackLocal();
if (showError) toast("Could not save: " + res.error.message);
return false;
}
serverStamp = (res.data && res.data[0] && res.data[0].updated_at) || stamp;
lastSaved = JSON.stringify(payload);
return true;
} catch (err) {
console.error("ActivityPlus save error:", err);
rollbackLocal();
if (showError) toast("Could not save. Check your internet and try again.");
return false;
} finally {
clearBusy();
}
}
// Saves one after another, so two quick actions can never overwrite each other
const save = (showError = true) => {
const run = () => persist(showError);
saveChain = saveChain.then(run, run);
return saveChain;
};
// ---- Savings: goals + savings transactions have their own tables ----
const mapGoal = r => ({ id: Number(r.client_id), name: r.name, target: Number(r.target) || 0, saved: Number(r.saved) || 0, currency: r.currency, deadline: r.deadline || "" });
const mapSavTx = r => ({ id: Number(r.client_id), goalId: Number(r.goal_client_id), goalName: r.goal_name, type: r.type, amount: Number(r.amount) || 0, currency: r.currency, date: r.tx_date, note: r.note || "" });
async function migrateSavings(uid) {
try {
const today = new Date().toISOString().slice(0, 10);
const goals = (data.goals || []).filter(g => g && g.id != null);
const txs = (data.savingsTx || []).filter(t => t && Number(t.amount) > 0 && goals.some(g => g.id === t.goalId));
if (goals.length) {
const { error } = await sb.from("activityplus_goals").upsert(goals.map(g => ({
user_id: uid, client_id: g.id, name: g.name || "Goal", target: Number(g.target) || 0, saved: 0,
currency: g.currency || "USD", deadline: g.deadline || null
})), { onConflict: "user_id,client_id" });
if (error) throw error;
}
const rows = txs.map(t => ({
user_id: uid, client_id: t.id, goal_client_id: t.goalId, goal_name: t.goalName || "",
type: t.type === "withdraw" ? "withdraw" : "deposit", amount: Number(t.amount),
currency: t.currency, tx_date: t.date || today, note: t.note || null
}));
let n = 0; // opening balance, so each goal keeps exactly the amount it showed before
goals.forEach(g => {
const sum = txs.filter(t => t.goalId === g.id).reduce((a, t) => a + (t.type === "withdraw" ? -Number(t.amount) : Number(t.amount)), 0);
const diff = Math.round((Number(g.saved || 0) - sum) * 100) / 100;
if (diff !== 0) rows.push({
user_id: uid, client_id: Date.now() + (n++), goal_client_id: g.id, goal_name: g.name || "Goal",
type: diff > 0 ? "deposit" : "withdraw", amount: Math.abs(diff), currency: g.currency || "USD",
tx_date: today, note: "Opening balance"
});
});
if (rows.length) {
const { error } = await sb.from("activityplus_savings_tx").upsert(rows, { onConflict: "user_id,client_id" });
if (error) throw error;
}
return true;
} catch (e) {
console.error("Savings migration failed:", e);
return false;
}
}
async function loadSavings(allowMigrate = true) {
if (!sb || !currentUser) return;
const uid = currentUser.id;
const [g, t] = await Promise.all([
sb.from("activityplus_goals").select("client_id,name,target,saved,currency,deadline").eq("user_id", uid).not("client_id", "is", null),
sb.from("activityplus_savings_tx").select("client_id,goal_client_id,goal_name,type,amount,currency,tx_date,note").eq("user_id", uid)
]);
if (g.error || t.error) {
console.warn("Savings tables not reachable, using the backup copy:", (g.error || t.error).message);
savingsInDb = false;
return;
}
if (!g.data.length && !t.data.length && allowMigrate && (data.goals.length || data.savingsTx.length)) {
if (await migrateSavings(uid)) {
await loadSavings(false);
await save(false); // the main row no longer carries savings
} else {
savingsInDb = false;
}
return;
}
savingsInDb = true;
data.goals = g.data.map(mapGoal).sort((a, b) => a.id - b.id);
data.savingsTx = t.data.map(mapSavTx);
}
// Replace the savings tables with what is in memory (used by Import and Reset)
async function syncSavingsToDb() {
if (!savingsInDb || !sb || !currentUser) return true;
const del = await sb.from("activityplus_goals").delete().eq("user_id", currentUser.id); // transactions cascade
if (del.error) { console.error(del.error); return false; }
return await migrateSavings(currentUser.id);
}
// One savings change: update the screen now, write the table in the background, undo if it fails
async function savingsWrite({ op, undo, errMsg }) {
renderAll();
if (!savingsInDb) return save(true); // fallback: savings still inside the main row
if (!sb || !currentUser) { undo(); renderAll(); toast("Please login first."); return false; }
setBusy();
try {
const { error } = await op();
if (error) throw error;
return true;
} catch (e) {
console.error("ActivityPlus savings error:", e);
undo();
renderAll();
toast(errMsg + ": " + (e.message || "try again"));
return false;
} finally {
clearBusy();
}
}
const loadRemoteData = async () => {
if (!sb || !currentUser) return false;
serverStamp = null; lastSaved = null; savingsInDb = false;
const { data: row, error } = await sb.from("activityplus_data").select("data, updated_at").eq("user_id", currentUser.id).maybeSingle();
if (error) {
console.error("ActivityPlus load error:", error);
toast("Could not load your data: " + error.message);
return false;
}
if (row?.data) {
applyRemote(row);
} else {
const legacy = localStorage.getItem(KEY);
if (legacy) {
try {
data = normalizeData(JSON.parse(legacy));
const ok = await save(false);
if (ok) localStorage.removeItem(KEY);
} catch (e) {
console.warn("Legacy migration failed:", e);
}
} else {
data = normalizeData(defaultData);
await save(false);
}
}
await loadSavings();
renderAll();
return true;
};
// ============================================================
// UTILITIES
// ============================================================
const fmt = (n, c) => ({ USD: "$", SLSH: "SLSH ", ETB: "ETB " }[c] || "") + Number(n || 0).toLocaleString(undefined, { maximumFractionDigits: 2 });
const CURS = ["USD", "SLSH", "ETB"];
const CUR_NAMES = { USD: "US DOLLAR", SLSH: "SL SHILLING", ETB: "ET BIRR" };
const curName = c => CUR_NAMES[c] || c;
// Balance of every wallet in ONE pass over the transactions (cached until the next render).
// income/expense/transfer, plus both sides of an exchange.
let balCache = null;
function balances() {
if (balCache) return balCache;
const m = Object.create(null);
const add = (k, v) => { if (k != null && k !== '') m[k] = (m[k] || 0) + v; };
for (const t of data.transactions) {
const amt = Number(t.amount) || 0;
if (t.type === 'income') add(t.wallet, amt);
else if (t.type === 'expense') add(t.wallet, -amt);
else if (t.type === 'transfer') { add(t.from, -amt); add(t.to, amt); }
else if (t.type === 'exchange') { add(t.from, -amt); add(t.to, Number(t.toAmount) || 0); }
}
return (balCache = m);
}
function walletBal(w) { return balances()[w.name] || 0; }
const currencyBalance = c => data.wallets.filter(w => w.currency === c).reduce((a, w) => a + walletBal(w), 0);
const kindTotals = kind => {
const out = { USD: 0, SLSH: 0, ETB: 0 };
data.wallets.filter(w => (w.kind || 'Personal') === kind).forEach(w => { out[w.currency] = (out[w.currency] || 0) + walletBal(w); });
return out;
};
const esc = s => String(s ?? "").replace(/[&<>"']/g, m => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[m]));
const toast = msg => {
const t = $("#toast");
if (!t) return;
t.textContent = msg;
t.classList.add("show");
setTimeout(() => t.classList.remove("show"), 2400);
};
const txAmount = (type, c, cat) => data.transactions
.filter(t => t.type === type && t.currency === c && (!cat || t.category === cat))
.reduce((a, t) => a + Number(t.amount), 0);
// ============================================================
// RENDER FUNCTIONS
// ============================================================
// ---- Exchange rates (saved in Settings) ----
// Units of each currency per 1 USD; every other pair is derived from these two.
const perUsd = c => c === 'USD' ? 1 : Number(data.rates?.['USD_' + c]) || 0;
const savedRate = (from, to) => {
const a = perUsd(from), b = perUsd(to);
return a > 0 && b > 0 ? b / a : 0;
};
function renderRates() {
if (!$('#ratesTable')) return;
const active = document.activeElement && document.activeElement.id;
if (active !== 'rateUsdSlsh') $('#rateUsdSlsh').value = data.rates?.USD_SLSH || '';
if (active !== 'rateUsdEtb') $('#rateUsdEtb').value = data.rates?.USD_ETB || '';
const pairs = [['USD', 'SLSH'], ['SLSH', 'USD'], ['USD', 'ETB'], ['ETB', 'USD'], ['SLSH', 'ETB'], ['ETB', 'SLSH']];
$('#ratesTable').innerHTML = pairs.map(([f, t]) => {
const r = savedRate(f, t);
return `<div class="rate-row"><span>1 ${f}</span><i class="ph-bold ph-arrow-right"></i><strong>${r ? Number(r.toFixed(6)).toLocaleString(undefined, { maximumFractionDigits: 6 }) + ' ' + t : 'not set'}</strong></div>`;
}).join('');
}
// Only the screen you are looking at is drawn. The others draw when you open them.
const SECTION_RENDER = {
dashboard: () => renderDashboard(),
transactions: () => renderTransactions(),
analytics: () => renderAnalytics(),
budgets: () => renderBudgets(),
savings: () => renderGoals(),
wallets: () => renderWallets(),
walletSettings: () => renderWalletManage(),
settings: () => renderRates()
};
let activeSection = (document.querySelector('.section.active-section') || {}).id || 'dashboard';
const freshSections = new Set();
function renderSection(id) {
const fn = SECTION_RENDER[id];
if (!fn) return;
fn();
freshSections.add(id);
}
function renderChrome() {
const nm = (currentUser?.user_metadata?.full_name || currentUser?.user_metadata?.name || currentUser?.email || 'A').trim();
const el = $('#profileInitial');
if (el) el.textContent = nm.charAt(0).toUpperCase();
}
function renderAll() {
balCache = null;
freshSections.clear();
populateWallets();
populateCategories();
renderChrome();
renderSection(activeSection);
}
const BAL_KEY = 'activityplus_hide_balance';
const balHidden = () => localStorage.getItem(BAL_KEY) === '1';
const mask = t => balHidden() ? '••••••' : t;
function renderDashboard() {
const c = currentCurrency;
const all = !c || c === 'ALL';
const inc = data.transactions.filter(t => t.type === 'income' && (all || t.currency === c)).reduce((a, t) => a + Number(t.amount), 0);
const exp = data.transactions.filter(t => t.type === 'expense' && (all || t.currency === c)).reduce((a, t) => a + Number(t.amount), 0);
const name = (currentUser?.user_metadata?.full_name || currentUser?.user_metadata?.name || '').trim();
$("#heroGreeting").textContent = name ? "Welcome back, " + name.split(' ')[0] : "Welcome back";
$("#dashHero").classList.toggle('is-all', all);
const eye = $("#toggleBalance i");
if (eye) eye.className = balHidden() ? 'ph-bold ph-eye-slash' : 'ph-bold ph-eye';
$("#balanceValue").textContent = all ? "Multi-currency" : mask(fmt(currencyBalance(c), c));
$("#balanceLabel").textContent = all ? "Balance per currency is shown below" : curName(c);
$("#incomeValue").textContent = all ? "—" : mask(fmt(inc, c));
$("#expenseValue").textContent = all ? "—" : mask(fmt(exp, c));
$("#savingValue").textContent = all ? "—" : mask(fmt(data.goals.filter(g => g.currency === c).reduce((a, g) => a + Number(g.saved), 0), c));
syncCurrencyPickers(c);
renderBell();
const sym = { USD: '$', SLSH: 'Sh', ETB: 'Br' };
const num = n => Number(n || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
$("#currencyCards").innerHTML = CURS.map(cur => {
const ci = txAmount('income', cur), ce = txAmount('expense', cur);
return `<button type="button" class="cur-card ${cur === c ? 'selected' : ''}" data-pick="${cur}">
<div class="cur-top"><span class="cur-ico ${cur.toLowerCase()}">${sym[cur]}</span><b class="cur-code">${cur}</b><i class="ph-fill ph-chart-bar cur-trend"></i></div>
<strong>${mask(({ USD: '$', SLSH: 'SLSH ', ETB: 'ETB ' }[cur] || '') + num(currencyBalance(cur)))}</strong>
<div class="cur-foot"><span class="income-text"><i class="dot"></i>+${mask(num(ci))}</span><span class="cur-sep"></span><span class="expense-text"><i class="dot"></i>-${mask(num(ce))}</span></div>
</button>`;
}).join('');
$$('#currencyCards [data-pick]').forEach(b => b.onclick = () => selectDashCurrency(b.dataset.pick));
$("#walletSplit").innerHTML = ['Personal', 'Business'].map(kind => {
const list = data.wallets.filter(w => (w.kind || 'Personal') === kind);
const tot = kindTotals(kind);
return `<div class="split-card ${kind.toLowerCase()}">
<div class="split-head"><span class="split-ico"><i class="ph-fill ${kind === 'Business' ? 'ph-briefcase' : 'ph-user'}"></i></span>
<div><strong>${kind}</strong><small>${list.length} wallet${list.length === 1 ? '' : 's'}</small></div></div>
<div class="split-amts">${CURS.filter(cur => list.some(w => w.currency === cur)).map(cur => `<span>${mask(fmt(tot[cur], cur))}</span>`).join('') || '<span class="muted">No wallets yet</span>'}</div>
</div>`;
}).join('');
const recent = [...data.transactions].sort((a, b) => b.date.localeCompare(a.date) || b.id - a.id).slice(0, 6);
$("#recentTransactions").innerHTML = recent.length
? recent.map(txRow).join("")
: `<div class="empty">No transactions yet.</div>`;
$("#goalPreview").innerHTML = data.goals.length
? data.goals.slice(0, 4).map(g => {
const p = Math.min(100, 100 * g.saved / g.target || 0);
return `<div class="mini-goal"><strong>${esc(g.name)}</strong><div class="mini-progress"><span style="width:${p}%"></span></div><small class="muted">${p.toFixed(0)}% · ${fmt(g.saved, g.currency)} / ${fmt(g.target, g.currency)}</small></div>`;
}).join("")
: `<div class="empty">No savings goals yet.</div>`;
$("#budgetPreview").innerHTML = data.budgets.length
? data.budgets.slice(0, 4).map(b => budgetHTML(b, true)).join("")
: `<div class="empty">No budgets yet.</div>`;
}
$('#toggleBalance').onclick = () => {
localStorage.setItem(BAL_KEY, balHidden() ? '0' : '1');
renderDashboard();
};
function selectDashCurrency(cur) {
currentCurrency = cur;
renderDashboard();
}
// keeps the tab pills and the "Select Currency" dropdown in step with the chosen currency
function syncCurrencyPickers(cur) {
$$('.currency-tabs .currency').forEach(x => x.classList.toggle('active', x.dataset.currency === cur));
$$('#curDropMenu .cd-opt').forEach(x => {
const on = x.dataset.currency === cur;
x.classList.toggle('selected', on);
x.setAttribute('aria-selected', on ? 'true' : 'false');
});
const lbl = $('#curDropLabel'), ico = $('#curDropIco');
if (lbl) lbl.textContent = cur === 'ALL' ? 'All Currency' : cur;
if (ico) ico.innerHTML = cur === 'ALL' ? '<i class="ph-bold ph-globe-hemisphere-west"></i>' : ({ USD: '$', SLSH: 'Sh', ETB: 'Br' }[cur] || cur);
}
(function setupCurrencyDropdown() {
const btn = $('#curDropBtn'), menu = $('#curDropMenu'), box = $('#curDrop');
if (!btn || !menu) return;
const close = () => { menu.hidden = true; box.classList.remove('open'); btn.setAttribute('aria-expanded', 'false'); };
btn.onclick = e => {
e.stopPropagation();
const open = menu.hidden;
menu.hidden = !open;
box.classList.toggle('open', open);
btn.setAttribute('aria-expanded', open ? 'true' : 'false');
};
menu.querySelectorAll('.cd-opt').forEach(o => o.onclick = e => { e.stopPropagation(); close(); selectDashCurrency(o.dataset.currency); });
document.addEventListener('click', e => { if (!box.contains(e.target)) close(); });
document.addEventListener('keydown', e => { if (e.key === 'Escape') close(); });
})();
// bell: budgets that are at 80%+ of their limit
function budgetAlerts() {
return data.budgets.filter(b => b.limit > 0 && txAmount('expense', b.currency, b.category) / b.limit >= 0.8);
}
function renderBell() {
const n = budgetAlerts().length, el = $('#bellBadge');
if (!el) return;
el.hidden = n === 0;
el.textContent = n > 9 ? '9+' : String(n);
}
$('#bellBtn').onclick = () => {
const a = budgetAlerts();
toast(a.length
? a.map(b => `${b.category}: ${Math.round(100 * txAmount('expense', b.currency, b.category) / b.limit)}% of budget used`).join(' · ')
: 'No new notifications.');
};
// --- transaction display helpers (income / expense / transfer / exchange) ---
const TX_LABEL = { income: 'Income', expense: 'Expense', transfer: 'Transfer', exchange: 'Exchange' };
const TX_SIGN = { income: '+', expense: '−', transfer: '↔', exchange: '⇄' };
const TX_CLASS = { income: 'income-text', expense: 'expense-text', transfer: 'transfer-text', exchange: 'exchange-text' };
const txAmountText = tx => tx.type === 'exchange'
? `${fmt(tx.amount, tx.currency)} → ${fmt(tx.toAmount, tx.toCurrency)}`
: `${TX_SIGN[tx.type] || ''}${fmt(tx.amount, tx.currency)}`;
function txRow(tx) {
const ico = { income: 'ph-arrow-down', expense: 'ph-shopping-cart', transfer: 'ph-arrow-right', exchange: 'ph-arrows-clockwise' }[tx.type] || 'ph-arrow-right';
const where = tx.wallet || (tx.from + " → " + tx.to);
return `<div class="tx-item">
<div class="tx-icon ${esc(tx.type)}"><i class="ph-fill ${ico}"></i></div>
<div class="tx-info">
<strong>${esc(tx.description)}</strong>
<small>${esc(tx.category || TX_LABEL[tx.type])} · ${esc(where)}</small>
</div>
<div class="amount ${TX_CLASS[tx.type] || ''}">
${txAmountText(tx)}
<small class="tx-date">${esc(tx.date)}</small>
</div>
<span class="pill ${esc(tx.type)}">${TX_LABEL[tx.type] || esc(tx.type)}</span>
</div>`;
}
let txLimit = 60;
window.moreTx = () => { txLimit += 60; renderTransactions(); };
function renderTransactions() {
const q = $("#searchTransactions").value.toLowerCase();
const type = $("#typeFilter").value;
const cat = $("#categoryFilter").value;
const rows = data.transactions.filter(t =>
(type === 'all' || t.type === type) &&
(cat === 'all' || t.category === cat) &&
(`${t.description} ${t.category || ''} ${t.wallet || ''} ${t.from || ''} ${t.to || ''}`.toLowerCase().includes(q))
).sort((a, b) => b.date.localeCompare(a.date) || b.id - a.id);
const shown = rows.slice(0, txLimit);
const more = rows.length > shown.length
? `<tr><td colspan="7" class="empty"><button type="button" class="secondary-btn" onclick="moreTx()">Show more (${rows.length - shown.length} left)</button></td></tr>` : '';
$("#transactionTable").innerHTML = rows.length
? shown.map(t => `<tr>
<td><strong>${esc(t.description)}</strong></td>
<td>${esc(t.type)}</td>
<td>${esc(t.category || 'Transfer')}</td>
<td>${esc(t.wallet || `${t.from} → ${t.to}`)}</td>
<td>${t.date}</td>
<td class="${TX_CLASS[t.type] || ''}"><strong>${txAmountText(t)}</strong></td>
<td><div class="row-actions">
<button class="small-btn" onclick="editTx(${t.id})"><i class="ph-bold ph-pencil-simple"></i></button>
<button class="small-btn delete" onclick="deleteTx(${t.id})"><i class="ph-bold ph-trash"></i></button>
</div></td>
</tr>`).join("") + more
: `<tr><td colspan="7" class="empty">No transactions found.</td></tr>`;
}
function renderGoals() {
$("#goalsGrid").innerHTML = data.goals.length
? data.goals.map(g => goalHTML(g)).join("")
: `<div class="panel empty" style="grid-column:1/-1">Create your first savings goal.</div>`;
renderSavingsTx();
}
function goalHTML(g) {
const p = Math.min(100, 100 * g.saved / g.target || 0);
return `<div class="goal-card">
<div class="goal-top">
<div class="goal-icon"><i class="ph-fill ph-vault"></i></div>
<button class="small-btn delete" onclick="deleteGoal(${g.id})"><i class="ph-bold ph-trash"></i></button>
</div>
<h3>${esc(g.name)}</h3>
<div class="muted">${fmt(g.saved, g.currency)} saved of ${fmt(g.target, g.currency)}</div>
${g.deadline ? `<div class="muted">Deadline: ${esc(g.deadline)}</div>` : ''}
<div class="progress"><div class="progress-bar" style="width:${p}%"></div></div>
<div class="goal-foot"><span>${p.toFixed(0)}% complete</span><span>${fmt(Math.max(0, g.target - g.saved), g.currency)} left</span></div>
<button class="secondary-btn full" onclick="addToGoal(${g.id})"><i class="ph-bold ph-plus"></i> Add money</button>
</div>`;
}
// ---- Wallet providers (what gets created together, and its optional bank) ----
const PROVIDERS = [
{ id: 'CASH', name: 'CASH', country: 'On hand', sub: 'Physical cash', badge: 'Cash', cls: 'cash', pick: true,
groups: [{ key: 'CASH', currencies: ['USD', 'SLSH', 'ETB'], bank: null }] },
{ id: 'ZAAD', name: 'ZAAD SERVICE', country: 'Somaliland', badge: 'ZAAD', cls: 'zaad',
groups: [{ key: 'ZAAD', currencies: ['USD', 'SLSH'], bank: 'Darasalaam Bank' }] },
{ id: 'KAASHPLUS', name: 'KAASHPLUS', country: 'Somaliland', badge: 'K+', cls: 'kaashplus',
groups: [{ key: 'KAASHPLUS', currencies: ['USD', 'SLSH'], bank: 'Darasalaam Bank' }] },
{ id: 'EDAHAB', name: 'EDAHAB', country: 'Somaliland', badge: 'eD', cls: 'edahab',
groups: [{ key: 'EDAHAB', currencies: ['USD', 'SLSH'], bank: 'Dahabshiil Bank' }] },
{ id: 'EBIRR', name: 'EBIRR', country: 'Ethiopia', badge: 'e', cls: 'ebirr',
groups: [
{ key: 'EBIRR KAAFI', currencies: ['ETB'], bank: 'Kaafi MF Bank' },
{ key: 'EBIRR COOPAY', currencies: ['ETB'], bank: 'CBO Bank' }
] },
{ id: 'TELEBIRR', name: 'TELEBIRR', country: 'Ethiopia', badge: 'tB', cls: 'telebirr',
groups: [{ key: 'TELEBIRR', currencies: ['ETB'], bank: 'Tele Account' }] },
{ id: 'MPESA', name: 'M-PESA', country: 'Ethiopia', badge: 'M', cls: 'mpesa',
groups: [{ key: 'MPESA', currencies: ['ETB'], bank: 'MPESA Bank' }] }
];
const kindOf = w => w.kind || 'Personal';
const groupWallets = (pid, gkey, kind) => data.wallets.filter(w => w.provider === pid && w.group === gkey && kindOf(w) === kind);
function groupHTML(p, g, kind) {
const all = groupWallets(p.id, g.key, kind);
const wal = all.filter(w => !w.isBank), banks = all.filter(w => w.isBank);
const free = g.currencies.filter(c => !banks.some(b => b.currency === c));
const multi = p.groups.length > 1;
const hasBank = !!g.bank;
const tiles = wal.map(w => `<div class="pw-tile">
<div class="pw-tile-top"><i class="ph-fill ph-wallet"></i><small>${esc(w.currency)} Wallet</small></div>
<strong>${fmt(walletBal(w), w.currency)}</strong></div>`).join('');
const bankRows = banks.map(b => `<div class="pw-bank">
<div class="pw-bank-head"><span class="pw-bank-ico"><i class="ph-fill ph-bank"></i></span>
<div class="pw-bank-info"><strong>${esc(g.bank)}</strong><small>Bank Account · ${esc(b.currency)}${b.account ? ' · ····' + esc(String(b.account).slice(-4)) : ''}</small></div>
<strong class="pw-bank-bal">${fmt(walletBal(b), b.currency)}</strong></div></div>`).join('');
const note = (!hasBank || banks.length) ? '' : `<div class="pw-bank">
<div class="pw-bank-head"><span class="pw-bank-ico"><i class="ph-fill ph-bank"></i></span>
<div class="pw-bank-info"><strong>${esc(g.bank)}</strong><small>Bank Account</small></div>
<span class="pw-opt">Ikhtiyaari</span></div>
<div class="pw-note"><i class="ph ph-info"></i><span>Account number-ka waxaa lagu daraa marka la diyaariyo.</span></div></div>`;
const add = (hasBank && free.length) ? `<button class="pw-add" onclick="openBankModal('${p.id}','${kind}','${g.key}')"><i class="ph-bold ph-plus"></i> Add Bank Account</button>` : '';
return `<div class="pw-group">${multi ? `<div class="pw-gtitle">${esc(g.key)}</div>` : ''}
<div class="pw-tiles">${tiles}</div>${bankRows}${note}${add}</div>`;
}
function providerCardHTML(p, kind) {
return `<div class="panel pw-card">
<div class="pw-head"><span class="pw-logo ${p.cls}">${esc(p.badge)}</span>
<div class="pw-title"><strong>${esc(p.name)}</strong><small>${esc(p.sub || (p.country + ' · Mobile Money'))}</small></div>
<button class="pw-menu" onclick="showSection('walletSettings')" title="Wallet settings"><i class="ph-bold ph-dots-three-vertical"></i></button></div>
${p.groups.map(g => groupHTML(p, g, kind)).join('')}
</div>`;
}
function legacyCardHTML(list) {
return `<div class="panel pw-card">
<div class="pw-head"><span class="pw-logo other"><i class="ph-fill ph-wallet"></i></span>
<div class="pw-title"><strong>OTHER WALLETS</strong><small>Created before providers</small></div></div>
<div class="pw-group"><div class="pw-tiles">${list.map(w => `<div class="pw-tile">
<div class="pw-tile-top"><i class="ph-fill ph-wallet"></i><small>${esc(w.name)}</small></div>
<strong>${fmt(walletBal(w), w.currency)}</strong></div>`).join('')}</div></div>
</div>`;
}
let walletQuery = '';
const walletMatches = w => !walletQuery || [w.name, w.type, w.kind, w.provider || '', w.group || '', w.currency, curName(w.currency), w.account || '']
.join(' ').toLowerCase().includes(walletQuery);
function renderWallets() {
$("#walletGrid").innerHTML = ['Personal', 'Business'].map(kind => {
const all = data.wallets.filter(w => kindOf(w) === kind);
const tot = kindTotals(kind);
const chips = CURS.filter(c => all.some(w => w.currency === c)).map(c => `<span class="group-chip">${fmt(tot[c], c)}</span>`).join('');
const cards = PROVIDERS.filter(p => data.wallets.some(w => w.provider === p.id && kindOf(w) === kind) && (!walletQuery ||
p.name.toLowerCase().includes(walletQuery) || data.wallets.some(w => w.provider === p.id && kindOf(w) === kind && walletMatches(w))))
.map(p => providerCardHTML(p, kind));
const legacy = all.filter(w => !w.provider && walletMatches(w));
if (legacy.length) cards.push(legacyCardHTML(legacy));
return `<div class="wallet-group">
<div class="group-head ${kind.toLowerCase()}">
<span class="group-ico"><i class="ph-fill ${kind === 'Business' ? 'ph-briefcase' : 'ph-user'}"></i></span>
<div><h3>${kind} Wallets</h3><small>${all.length} wallet${all.length === 1 ? '' : 's'}</small></div>
<div class="group-chips">${chips}</div>
</div>
${cards.length ? `<div class="pw-grid">${cards.join('')}</div>` : `<div class="panel empty">${walletQuery ? `No ${kind} wallets match your search.` : `No ${kind} wallets yet. Tap Settings, then New Wallet.`}</div>`}
</div>`;
}).join('');
}
function renderBudgets() {
$("#budgetGrid").innerHTML = data.budgets.length
? data.budgets.map(b => budgetHTML(b)).join("")
: `<div class="panel empty" style="grid-column:1/-1">Create a monthly budget to control spending.</div>`;
}
function budgetHTML(b, compact = false) {
const spent = txAmount('expense', b.currency, b.category);
const p = Math.min(100, 100 * spent / b.limit || 0);
return `<div class="goal-card">
<div class="goal-top">
<div class="goal-icon"><i class="ph-fill ph-target"></i></div>
<button class="small-btn delete" onclick="deleteBudget(${b.id})"><i class="ph-bold ph-trash"></i></button>
</div>
<h3>${esc(b.category)}</h3>
<div class="muted">${fmt(spent, b.currency)} spent of ${fmt(b.limit, b.currency)}</div>
<div class="progress"><div class="progress-bar" style="width:${p}%"></div></div>
<div class="goal-foot"><span>${p.toFixed(0)}% used</span><span>${fmt(Math.max(0, b.limit - spent), b.currency)} left</span></div>
</div>`;
}
function renderAnalytics() {
const c = $("#analyticsCurrency").value || 'USD';
const inc = txAmount('income', c);
const exp = txAmount('expense', c);
$("#aIncome").textContent = fmt(inc, c);
$("#aExpense").textContent = fmt(exp, c);
$("#aNet").textContent = fmt(inc - exp, c);
const now = new Date();
const months = [];
for (let i = 5; i >= 0; i--) {
const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
months.push({ key: `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`, label: d.toLocaleString(undefined, { month: 'short' }) });
}
const vals = months.map(m => {
const its = data.transactions.filter(t => t.date.startsWith(m.key) && t.currency === c);
return {
...m,
inc: its.filter(t => t.type === 'income').reduce((a, t) => a + Number(t.amount), 0),
exp: its.filter(t => t.type === 'expense').reduce((a, t) => a + Number(t.amount), 0)
};
});
const max = Math.max(1, ...vals.flatMap(x => [x.inc, x.exp]));
$("#monthlyChart").innerHTML = vals.map(m => `
<div class="month-group">
<div class="bar" style="height:${Math.max(3, m.inc / max * 90)}%" title="Income ${fmt(m.inc, c)}"></div>
<div class="bar exp" style="height:${Math.max(3, m.exp / max * 90)}%" title="Expenses ${fmt(m.exp, c)}"></div>
<span class="month-label">${m.label}</span>
</div>
`).join('') + `<div class="chart-legend"><span><i class="legend-dot"></i>Income</span><span><i class="legend-dot exp"></i>Expenses</span></div>`;
const cats = CATS.map(cat => ({ cat, val: txAmount('expense', c, cat) }))
.filter(x => x.val > 0)
.sort((a, b) => b.val - a.val)
.slice(0, 7);
const mx = Math.max(1, ...cats.map(x => x.val));
$("#categoryChart").innerHTML = cats.length
? cats.map(x => `<div class="category-row"><span>${esc(x.cat)}</span><div class="cat-track"><div class="cat-fill" style="width:${x.val / mx * 100}%"></div></div><strong>${fmt(x.val, c)}</strong></div>`).join('')
: `<div class="empty">No expense data for ${c}.</div>`;
}
// A <select> is only rebuilt when its options really change, so what the person picked is never lost
function fillSelect(sel, html) {
if (!sel || sel._opts === html) return;
const keep = sel.value;
sel.innerHTML = html;
sel._opts = html;
if (keep && [...sel.options].some(o => o.value === keep)) sel.value = keep;
}
function walletOptionsForCurrency(currency) {
return data.wallets.filter(w => w.currency === currency).map(w => `<option value="${esc(w.name)}">${esc(w.name)}</option>`).join("");
}
function populateWallets() {
const tc = $("#txCurrency")?.value || "USD";
fillSelect($("#txWallet"), walletOptionsForCurrency(tc) || `<option value="">No ${esc(tc)} wallet yet</option>`);
const fc = $("#transferCurrency")?.value || "SLSH";
const html = walletOptionsForCurrency(fc) || `<option value="">No ${esc(fc)} wallet yet</option>`;
fillSelect($("#fromWallet"), html);
fillSelect($("#toWallet"), html);
}
function pickDefaultTransferWallets() {
const f = $("#fromWallet"), t = $("#toWallet");
if (f.value && f.value === t.value && t.options.length > 1) {
const i = (f.selectedIndex + 1) % t.options.length;
t.value = t.options[i].value;
}
}
function populateCategories() {
const cats = [...new Set([...CATS, ...data.transactions.map(t => t.category).filter(Boolean)])];
fillSelect($("#categoryFilter"), '<option value="all">All categories</option>' + cats.map(c => `<option value="${esc(c)}">${esc(c)}</option>`).join(''));
fillSelect($("#budgetCategory"), cats.filter(c => !['Salary', 'Transfer', 'Exchange'].includes(c)).map(c => `<option>${esc(c)}</option>`).join(''));
}
// ============================================================
// NAVIGATION
// ============================================================
function showSection(id) {
$$('.section').forEach(s => s.classList.remove('active-section'));
$('#' + id).classList.add('active-section');
$$('.nav-link').forEach(b => b.classList.toggle('active', b.dataset.section === (id === 'walletSettings' ? 'wallets' : id)));
$('#pageTitle').textContent = {
dashboard: 'Dashboard',
transactions: 'Transactions',
analytics: 'Analytics',
budgets: 'Budgets',
savings: 'Savings Goals',
wallets: 'Wallets',
walletSettings: 'Wallet Settings',
settings: 'Settings & Backup'
}[id];
activeSection = id;
document.body.dataset.section = id;
if (!freshSections.has(id)) renderSection(id);
}
$$('.nav-link').forEach(b => b.onclick = () => showSection(b.dataset.section));
$$('[data-go]').forEach(b => b.onclick = () => showSection(b.dataset.go));
$$('.currency-tabs .currency').forEach(b => b.onclick = () => {
if (!b.dataset.currency) return;
currentCurrency = b.dataset.currency;
renderDashboard();
});
// ============================================================
// TRANSACTION MODAL
// ============================================================
function openTx(type, id = null) {
const tx = id ? data.transactions.find(x => x.id === id) : null;
const wal = tx ? data.wallets.find(w => w.name === tx.wallet) : null;
const cur = wal?.currency || tx?.currency || (data.wallets.some(w => w.currency === 'USD') ? 'USD' : data.wallets[0]?.currency) || 'USD';
$('#txId').value = tx ? tx.id : '';
$('#txType').value = type;
$('#modalTitle').textContent = tx ? 'Edit Transaction' : type === 'income' ? 'Add Income' : 'Add Expense';
$('#txDescription').value = tx?.description || '';
$('#txAmount').value = tx?.amount || '';
$('#txCurrency').value = cur;
populateWallets(); // wallet list for this currency
if (tx?.wallet) $('#txWallet').value = tx.wallet;
$('#txCategory').value = tx?.category || (type === 'income' ? 'Salary' : 'Food');
$('#txDate').value = tx?.date || new Date().toISOString().slice(0, 10);
$('#modal').classList.add('show');
}
function closeModal(id) {
$('#' + id).classList.remove('show');
}
$('#addIncome').onclick = () => openTx('income');
$('#addExpense').onclick = () => openTx('expense');
$('#quickExpense').onclick = () => openTx('expense');
$('#closeModal').onclick = () => closeModal('modal');
$('#modal').onclick = e => { if (e.target.id === 'modal') closeModal('modal'); };
$$('[data-close]').forEach(b => b.onclick = () => closeModal(b.dataset.close));
window.editTx = id => {
const t = data.transactions.find(x => x.id === id);
if (t?.type === 'transfer') return toast('Transfers cannot be edited here. Delete and create a new transfer.');
if (t?.type === 'exchange') return toast('Exchanges cannot be edited here. Delete and create a new exchange.');
openTx(t.type, id);
};
$('#transactionForm').onsubmit = async e => {
e.preventDefault();
const id = Number($('#txId').value);
const w = data.wallets.find(x => x.name === $('#txWallet').value);
if (!w) return toast('Choose a wallet first.');
const amount = Number($('#txAmount').value);
if (!(amount > 0)) return toast('Enter a valid amount.');
const obj = {
id: id || Date.now(),
type: $('#txType').value,
description: $('#txDescription').value.trim(),
amount,
currency: w.currency, // always the wallet's own currency, so the balance and the totals agree
category: $('#txCategory').value,
wallet: w.name,
date: $('#txDate').value
};
if (id) {
const i = data.transactions.findIndex(x => x.id === id);
if (i < 0) return;
data.transactions[i] = obj;
} else data.transactions.push(obj);
closeModal('modal');
if (await save(true)) toast(id ? 'Transaction updated.' : 'Transaction saved.');
};
// ============================================================
// TRANSFER
// ============================================================
$('#addTransfer').onclick = () => {
$('#transferDate').value = new Date().toISOString().slice(0, 10);
const cur = $('#transferCurrency').value;
if (data.wallets.filter(w => w.currency === cur).length < 2) { // start with a currency that has two wallets
const alt = CURS.find(c => data.wallets.filter(w => w.currency === c).length >= 2);
if (alt) $('#transferCurrency').value = alt;
}
populateWallets();
pickDefaultTransferWallets();
$('#transferModal').classList.add('show');
};
$('#transferForm').onsubmit = async e => {
e.preventDefault();
const from = $('#fromWallet').value;
const to = $('#toWallet').value;
if (!from || !to) return toast('Choose the From and To wallets.');
if (from === to) return toast('Choose two different wallets.');
const fw = data.wallets.find(w => w.name === from);
const tw = data.wallets.find(w => w.name === to);
if (!fw || !tw || fw.currency !== tw.currency) return toast('From and To wallets must use the same currency.');
const currency = fw.currency;
const amount = Number($('#transferAmount').value);
if (!(amount > 0)) return toast('Enter a valid amount.');
data.transactions.push({
id: Date.now(),
type: 'transfer',
description: 'Wallet transfer',
amount,
currency,
category: 'Transfer',
from,
to,
date: $('#transferDate').value
});
closeModal('transferModal');
if (await save(true)) toast('Transfer recorded.');
};
// ============================================================
// WALLET SEARCH, MANAGEMENT (Settings) AND PROFILE BUTTON
// ============================================================
$('#walletSearch').addEventListener('input', e => {
walletQuery = e.target.value.trim().toLowerCase();
renderWallets();
});
function renderWalletManage() {
const list = $('#walletManageList');
if (!list) return;
list.innerHTML = data.wallets.map(w => {
const kind = w.kind || 'Personal';
return `<div class="wm-item">
<span class="wm-ico ${kind.toLowerCase()}"><i class="ph-fill ${kind === 'Business' ? 'ph-briefcase' : 'ph-user'}"></i></span>
<div class="wm-info">
<strong>${esc(w.fullName || 'No full name')}</strong>
<small>${esc(w.name)} · ${kind} · ${curName(w.currency)}${w.account ? ' · Acc ' + esc(w.account) : ''}</small>
</div>
<div class="wm-bal">${mask(fmt(walletBal(w), w.currency))}</div>