-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderer.js
More file actions
1580 lines (1211 loc) · 41.7 KB
/
Copy pathrenderer.js
File metadata and controls
1580 lines (1211 loc) · 41.7 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
/* =============================================================
renderer.js — IronStar Salon | Frontend Logic
Handles: UI interactions, customer lookup, service management,
visit tracking, WhatsApp messaging, reports & data ops
============================================================= */
/* =============================================================
SECTION 1: GLOBAL STATE
These variables are shared across functions to track the
current billing session's services and running total.
============================================================= */
let total = 0; // Running total for the current visit (₹)
let services = []; // List of service names added in current visit
let allCustomers = []; // Full customer list loaded for the CRM tab
let serviceMap = {}; // Maps service name → price for quick lookups (used in repeatLastVisit)
const appState = {
staff: "Senior",
payment: "UPI"
};
/* =============================================================
SECTION 2: DOM REFERENCES
Cached references to frequently used input elements.
============================================================= */
const phoneInput = document.getElementById("phone");
const nameInput = document.getElementById("name");
document.addEventListener("DOMContentLoaded", () => {
// STAFF
document.querySelectorAll(".staff-btn").forEach(btn => {
btn.addEventListener("click", () => {
document.querySelectorAll(".staff-btn").forEach(b => b.classList.remove("active"));
btn.classList.add("active");
appState.staff = btn.dataset.staff;
});
});
// PAYMENT
document.querySelectorAll(".payment-btn").forEach(btn => {
btn.addEventListener("click", () => {
document.querySelectorAll(".payment-btn").forEach(b => b.classList.remove("active"));
btn.classList.add("active");
appState.payment = btn.dataset.mode;
});
});
});
/* =============================================================
SECTION 3: PHONE INPUT — VALIDATION & AUTOCOMPLETE
- Strips non-numeric characters as the user types
- Shows a live dropdown of matching customers based on phone
- Clicking a suggestion auto-fills both phone and name fields
============================================================= */
// -----------------------------
// SECTION 3: PHONE INPUT + AUTOCOMPLETE (ENHANCED)
// -----------------------------
let selectedIndex = -1;
let currentSuggestions = [];
// Keep only digits in phone input
phoneInput.addEventListener("input", () => {
phoneInput.value = phoneInput.value.replace(/\D/g, "");
});
// Show autocomplete suggestions
phoneInput.addEventListener("input", async () => {
const phone = phoneInput.value;
const box = document.getElementById("suggestionsBox");
if (phone.length < 2) {
box.style.display = "none";
return;
}
const customers = await window.api.getCustomers("all");
currentSuggestions = customers.filter(c => c.phone.includes(phone));
selectedIndex = -1;
box.innerHTML = "";
if (currentSuggestions.length === 0) {
box.style.display = "none";
return;
}
renderSuggestions();
});
// Render suggestions (reusable)
function renderSuggestions() {
const box = document.getElementById("suggestionsBox");
box.innerHTML = "";
currentSuggestions.forEach((c, index) => {
const item = document.createElement("div");
item.innerText = `${c.name} (${c.phone})`;
item.style.padding = "6px";
item.style.cursor = "pointer";
// Highlight selected item
if (index === selectedIndex) {
item.style.background = "#333";
item.style.color = "#fff";
}
// Mouse select
item.onmousedown = () => selectCustomer(index);
// Hover effect
item.onmouseover = () => {
selectedIndex = index;
renderSuggestions();
};
item.onmouseout = () => {
item.style.background = "";
item.style.color = "";
};
box.appendChild(item);
});
box.style.display = "block";
}
// Select customer
function selectCustomer(index) {
const c = currentSuggestions[index];
if (!c) return;
const box = document.getElementById("suggestionsBox");
phoneInput.value = c.phone;
nameInput.value = c.name;
clearCart();
box.style.display = "none";
phoneInput.dispatchEvent(new Event("blur"));
}
// Keyboard navigation
phoneInput.addEventListener("keydown", (e) => {
if (!currentSuggestions.length) return;
if (e.key === "ArrowDown") {
e.preventDefault();
selectedIndex = (selectedIndex + 1) % currentSuggestions.length;
renderSuggestions();
}
if (e.key === "ArrowUp") {
e.preventDefault();
selectedIndex =
(selectedIndex - 1 + currentSuggestions.length) %
currentSuggestions.length;
renderSuggestions();
}
if (e.key === "Enter") {
e.preventDefault();
selectCustomer(selectedIndex);
}
});
// Close suggestions on outside click
document.addEventListener("click", (e) => {
const box = document.getElementById("suggestionsBox");
if (!phoneInput.contains(e.target)) {
box.style.display = "none";
}
});
/* =============================================================
SECTION 4: CUSTOMER AUTO-DETECTION ON PHONE BLUR
When the user leaves the phone field:
- Auto-fills the name if the customer exists
- Shows their last visit summary (services + total)
============================================================= */
phoneInput.addEventListener("blur", async () => {
const phone = phoneInput.value;
if (!phone) return;
const el = document.getElementById("lastVisitInfo");
const customer = await window.api.findCustomer(phone);
if (customer) {
// Auto-fill the name field for existing customers
nameInput.value = customer.name;
// Fetch and display the most recent visit details
const visit = await window.api.getLastVisit(phone);
if (visit) {
el.style.display = "block";
el.innerText =
`Last Visit: ${visit.services} | ₹${visit.total} (Click Repeat to reuse)`;
} else {
// Customer exists but has no recorded visits
el.style.display = "none";
el.innerText = "";
}
} else {
// Unknown customer — clear name and hide last visit info
nameInput.value = "";
el.style.display = "none";
el.innerText = "";
}
});
/* =============================================================
SECTION 5: WHATSAPP MESSAGING
Sends a formatted visit summary to the customer via WhatsApp Web.
Opens in a new tab using the wa.me API link.
============================================================= */
function sendWhatsApp() {
const phone = phoneInput.value.trim();
const name = nameInput.value.trim();
if (!phone || !name) {
document.getElementById("status").innerText = "Enter customer details first";
return;
}
// Build the visit summary message with services and total
let message =
`Hey ${name}, thanks for visiting IronStar Salon ✂️
Here's your visit summary:
💇 Services:
${services.map(s => `• ${s}`).join("\n")}
💰 Total: ₹${total}
📅 ${new Date().toLocaleString("en-IN")}
We hope to serve you again soon 🙌
⭐ Loved the experience? Please leave us a quick review:
https://maps.app.goo.gl/8kTAqnhdbhQsWP6x7`;
// Normalize unicode and line endings to prevent encoding issues
message = message
.trim()
.normalize("NFC")
.replace(/\uFFFD/g, "") // Remove replacement characters
.replace(/\r?\n/g, "\n"); // Standardize newlines
const encodedMessage = encodeURIComponent(message);
// Open WhatsApp chat with the pre-filled message
const url = `https://api.whatsapp.com/send?phone=91${phone}&text=${encodedMessage}`;
window.open(url, "_blank");
}
/* =============================================================
SECTION 6: BILLING — ADD SERVICE TO CURRENT VISIT
Adds a service to the session's list and updates the running total.
============================================================= */
// Add a service to the current billing session
function addService(name, price) {
services.push(name);
total += price;
document.getElementById("total").innerText = total;
renderCart();
}
/* =============================================================
SECTION 7: INCOME DASHBOARD
Loads and displays today's, this week's, and this month's income.
============================================================= */
async function loadIncome() {
const data = await window.api.getIncome();
console.log("Income Data:", data); // Debug log for income API response
document.getElementById("todayIncome").innerText = data.today;
document.getElementById("weekIncome").innerText = data.week;
document.getElementById("monthIncome").innerText = data.month;
}
/* =============================================================
SECTION 8: SERVICE BUTTONS
Dynamically renders clickable service buttons on the billing screen.
Also rebuilds the serviceMap (name → price) for repeat-visit lookups.
============================================================= */
async function loadServices() {
const services = await window.api.getServices();
const container = document.getElementById("servicesContainer");
container.innerHTML = "";
serviceMap = {}; // Reset the map before repopulating
services.forEach(service => {
// Store price in map so repeatLastVisit can recalculate totals
serviceMap[service.name] = service.price;
// Create a button for each service
const btn = document.createElement("button");
btn.innerText = `${service.name} ₹${service.price}`;
btn.onclick = () => addService(service.name, service.price);
container.appendChild(btn);
});
}
/* =============================================================
SECTION 9: SERVICE MANAGEMENT (ADMIN)
Functions to add, update, delete, and list services from the
admin panel.
============================================================= */
// Add a new service using the name/price inputs in the admin panel
async function addNewService() {
const name = document.getElementById("serviceName").value;
const price = document.getElementById("servicePrice").value;
if (!name || !price) {
document.getElementById("status").innerText = "Enter service details";
return;
}
await window.api.addService({ name, price });
// Refresh both the billing buttons and the admin list
loadServices();
loadServiceList();
}
// Render the admin service list with inline price editing and delete controls
async function loadServiceList() {
const services = await window.api.getServices();
const container = document.getElementById("serviceList");
container.innerHTML = "";
services.forEach(s => {
const row = document.createElement("div");
row.style.marginBottom = "6px";
// Each row shows the service name, an editable price field, Update & Delete buttons
row.innerHTML = `
${s.name} - ₹
<input
type="number"
value="${s.price}"
id="price-${s.id}"
style="width:60px"
onkeypress="if(event.key==='Enter') updateServicePrice(${s.id})"
/>
<button class="btn btn-secondary" onclick="updateServicePrice(${s.id})">
Update
</button>
<button class="btn btn-danger" onclick="deleteService(${s.id})">
Delete
</button>
`;
container.appendChild(row);
});
}
// Update the price of a specific service by its ID
async function updateServicePrice(id) {
const price = document.getElementById(`price-${id}`).value;
if (!price) {
document.getElementById("status").innerText = "Enter valid price";
return;
}
await window.api.updateService({ id, price });
document.getElementById("status").innerText = "Price updated!";
// Refresh billing buttons and admin list to reflect new price
loadServices();
loadServiceList();
}
// Delete a service permanently and refresh both views
async function deleteService(id) {
await window.api.deleteService(id);
loadServices();
loadServiceList();
}
/* =============================================================
SECTION 10: VISIT HISTORY
Displays a customer's full visit history or a filtered date-range
subset inside the history panel.
============================================================= */
// Load and display all visits for the current customer
async function viewHistory() {
const phone = phoneInput.value;
if (!phone) {
showStatus(
"Enter customer phone first"
);
return;
}
const visits =
await window.api.getVisitHistory(phone);
const box = document.querySelector(
".svc-scroll #historyBox"
);
box.style.display = "flex";
box.innerHTML = "<h4>Visit History</h4>";
if (visits.length === 0) {
box.innerHTML += `
<p style='color:gray'>
No history found
</p>
`;
return;
}
visits.forEach(v => {
const div = document.createElement("div");
const servicesArr = v.services.split(",");
const uniqueServices =
[...new Set(servicesArr)];
const formattedServices =
uniqueServices
.map(s =>
s
.replace(/^\[.\]\s*/, "")
)
.join(" • ");
div.innerHTML = `
<div style="
display:flex;
justify-content:space-between;
align-items:flex-start;
gap:12px;
">
<div>
<div style="
font-size:13px;
font-weight:600;
color:var(--txt);
line-height:1.5;
">
${formattedServices}
</div>
<div style="
margin-top:6px;
font-size:11px;
color:var(--txt-muted);
">
${v.paymentMode || "N/A"}
•
${v.staff || "N/A"}
•
${new Date(v.date).toLocaleDateString()}
</div>
</div>
<div style="
font-weight:700;
color:var(--acc);
white-space:nowrap;
font-size:14px;
">
₹${v.total}
</div>
</div>
`;
box.appendChild(div);
});
}
// Filter a customer's visit history between two dates and display results
async function filterByDate() {
const from = document.getElementById("fromDate").value;
const to = document.getElementById("toDate").value;
const phone = phoneInput.value;
if (!phone) {
document.getElementById("status").innerText = "Enter phone first";
return;
}
const data = await window.api.filterByDate({ from, to, phone });
const box = document.getElementById("historyBox");
box.innerHTML = "<h4>Filtered History</h4>";
if (data.length === 0) {
box.innerHTML += "<p style='color:gray'>No history found</p>";
return;
}
data.forEach(v => {
const div = document.createElement("div");
div.innerText = `${v.services} | ₹${v.total} | ${new Date(v.date).toLocaleDateString()}`;
box.appendChild(div);
});
}
/* =============================================================
SECTION 11: REPEAT LAST VISIT
Reloads the services and total from the customer's most recent
visit so the same billing can be quickly reused.
============================================================= */
async function repeatLastVisit() {
const phone = phoneInput.value;
if (!phone) {
document.getElementById("status").innerText = "Enter phone first";
return;
}
const visit = await window.api.getLastVisit(phone);
if (!visit) {
document.getElementById("status").innerText = "No previous visit found";
return;
}
// Reset billing session before loading previous visit
total = 0;
services = [];
// Re-add each service from the last visit using serviceMap for pricing
const prevServices = visit.services.split(",");
prevServices.forEach(service => {
services.push(service);
total += serviceMap[service] || 0; // Default to 0 if price not found in map
});
// Update the total display
document.getElementById("total").innerText = total;
// Update the last visit info banner to indicate it was reused
const el = document.getElementById("lastVisitInfo");
el.style.display = "block";
el.innerText = `Last Visit: ${visit.services} | ₹${visit.total} (reused)`;
document.getElementById("status").innerText = "Loaded last visit!";
renderCart();
renderSvcGrid();
}
/* =============================================================
SECTION 12: CRM — CUSTOMER LIST & BULK WHATSAPP OFFERS
Loads customers filtered by type (all / inactive / VIP),
supports search filtering, and enables sending bulk WhatsApp
offers to individual customers.
============================================================= */
// Load customers based on the selected filter (all / inactive / VIP)
async function loadCustomers() {
const filter = document.getElementById("filterType").value;
allCustomers = await window.api.getCustomers(filter);
displayCustomers(allCustomers);
}
// Render the customer list with Send buttons for WhatsApp offers
function displayCustomers(customers) {
const container = document.getElementById("customerList");
container.innerHTML = "";
const filter = document.getElementById("filterType").value;
customers.forEach(cust => {
const row = document.createElement("div");
row.classList.add("customer-row");
// Apply visual class based on customer status
if (filter === "inactive") {
row.classList.add("inactive");
} else if (cust.visit_count && cust.visit_count >= 5) {
row.classList.add("vip"); // VIP: 5+ visits
}
row.innerHTML = `
<span id="cust-${cust.phone}">
${cust.name} (${cust.phone})
</span>
<button class="btn btn-secondary"
onclick="sendToCustomer('${cust.phone}', '${cust.name}')">
Send
</button>
`;
container.appendChild(row);
});
}
// Filter the already-loaded customer list by name or phone (client-side)
function filterCustomers() {
const search = document.getElementById("searchInput").value.toLowerCase();
const filtered = allCustomers.filter(cust =>
cust.name.toLowerCase().includes(search) ||
cust.phone.includes(search)
);
displayCustomers(filtered);
}
// Enable/disable Send buttons depending on whether an offer message has been typed
function toggleSendButtons() {
const message = document.getElementById("offerMessage").value;
const buttons = document.querySelectorAll("#customerList button");
buttons.forEach(btn => {
btn.disabled = !message;
});
}
// Send a custom offer message to a specific customer via WhatsApp
function sendToCustomer(phone, name) {
let message = document.getElementById("offerMessage").value;
if (!message.trim()) {
document.getElementById("status").innerText = "Enter offer message";
return;
}
// Normalize unicode and line endings to prevent encoding issues
message = message
.trim()
.normalize("NFC")
.replace(/\uFFFD/g, "") // Remove replacement characters
.replace(/\r?\n/g, "\n"); // Standardize newlines
const encodedMessage = encodeURIComponent(message);
const url = `https://api.whatsapp.com/send?phone=91${phone}&text=${encodedMessage}`;
window.open(url, "_blank");
// Mark this customer as "sent" with a checkmark in the UI
const el = document.getElementById(`cust-${phone}`);
if (el && !el.innerText.includes("✅")) {
el.innerText += " ✅";
}
}
/* =============================================================
SECTION 13: TOP CUSTOMERS
Fetches and logs the top customers by visit count or spend.
(Currently logs to console — UI rendering can be added here)
============================================================= */
async function loadTopCustomers() {
const data = await window.api.topCustomers();
console.log(data);
}
/* =============================================================
SECTION 14: SAVE VISIT
Validates inputs, saves the customer record and visit to the
database, optionally sends a WhatsApp summary, then resets
the billing session.
============================================================= */
async function saveVisit() {
const phone = phoneInput.value;
const name = nameInput.value;
// Validate: phone must be exactly 10 digits
if (!/^\d{10}$/.test(phone)) {
document.getElementById("status").innerText = "Enter valid 10-digit phone number";
return;
}
if (!name) {
document.getElementById("status").innerText = "Enter customer name";
return;
}
// Upsert customer record (creates if new, updates if existing)
await window.api.saveCustomer({ name, phone });
// Save the visit with services list and total
const res = await window.api.saveVisit({
phone,
services,
total,
paymentMode: appState.payment || "UPI",
staff: appState.staff || "Senior"
});
if (res.success) {
document.getElementById("status").innerText = "Saved successfully!";
// Refresh income summary on the dashboard
loadIncome();
// Optionally auto-send a WhatsApp summary if the toggle is checked
const auto = document.getElementById("autoWhatsapp").checked;
if (auto) {
sendWhatsApp();
}
// Clear the status message after 2 seconds
setTimeout(() => {
document.getElementById("status").innerText = "";
}, 2000);
// Reset all billing session state and inputs
phoneInput.value = "";
nameInput.value = "";
total = 0;
services = [];
document.getElementById("total").innerText = 0;
// Return focus to phone field for the next customer
setTimeout(() => {
phoneInput.focus();
}, 100);
}
clearCart();
}
/* =============================================================
SECTION 15: DATA MANAGEMENT — BACKUP, RESTORE, CLEAR, EXPORT
Admin-level operations for data safety and reporting.
============================================================= */
// Trigger a backup of all salon data to a user-chosen location
async function backupData() {
const res = await window.api.backupData();
if (res.success) {
document.getElementById("status").innerText = "Backup saved successfully!";
} else {
document.getElementById("status").innerText = "Backup canceled";
}
}
// Restore data from a previously saved backup (overwrites current data)
async function restoreData() {
const confirmRestore = confirm("This will overwrite current data. Continue?");
if (!confirmRestore) return;
const res = await window.api.restoreData();
if (res.success) {
document.getElementById("status").innerText = "Data restored! Restart app.";
} else {
document.getElementById("status").innerText = "Restore canceled or failed";
}
}
// Permanently delete all data (customers, visits, services) after confirmation
async function clearData() {
const confirmClear = confirm("Delete all data?");
if (!confirmClear) return;
const res = await window.api.clearData();
if (res.success) {
document.getElementById("status").innerText = "Data cleared!";
// Refresh UI to reflect empty state
loadCustomers();
loadIncome();
}
}
/*
exportData() — disabled/reserved for future use
async function exportData() {
const res = await window.api.exportData();
if (res.success) {
document.getElementById("status").innerText = "Export successful!";
} else {
document.getElementById("status").innerText = "Export canceled or failed";
}
}
*/
// Export all visit records to a spreadsheet file
async function exportVisits() {
const res = await window.api.exportVisits();
if (res.success) {
document.getElementById("status").innerText = "Visits exported!";
} else {
document.getElementById("status").innerText = "Export canceled or failed";
}
}
/* =============================================================
SECTION 16: REPORTS MODAL
Handles the report download modal — allows selecting a date
range (today / week / month / custom) and exporting data.
============================================================= */
// Open the report download modal
function openReportModal() {
document.getElementById("reportModal").classList.add("open");
}
// Close the report download modal
function closeReportModal() {
document.getElementById("reportModal").classList.remove("open");
}
// Show or hide custom date fields based on selected report type
function handleReportType() {
const type = document.getElementById("reportType").value;
const custom = document.getElementById("customDates");
if (type === "custom") {
custom.style.display = "block";
} else {
custom.style.display = "none";
}
}
// Calculate the date range and trigger the report download
async function downloadReport() {
const type = document.getElementById("reportType").value;
let from = null;
let to = null;
const today = new Date();
// Calculate from/to dates based on selected report period
if (type === "today") {
from = to = today.toISOString().split("T")[0];
}
if (type === "week") {
const past = new Date();
past.setDate(today.getDate() - 7);
from = past.toISOString().split("T")[0];
to = today.toISOString().split("T")[0];
}
if (type === "month") {
from = today.toISOString().slice(0, 7) + "-01"; // First day of current month
to = today.toISOString().split("T")[0];
}
if (type === "custom") {
from = document.getElementById("reportFrom").value;
to = document.getElementById("reportTo").value;
}
await window.api.exportReport({ from, to });
alert("Report downloaded!");
closeReportModal();
}
const adminPanel = document.getElementById("adminPanel");
document.getElementById("adminBtn").onclick = () => {
adminPanel.classList.remove("hidden");
loadDashboard(); // load stats when opened
};
document.getElementById("closeAdmin").onclick = () => {
adminPanel.classList.add("hidden");
};
document.querySelectorAll(".tab").forEach(btn => {
btn.addEventListener("click", () => {
document.querySelectorAll(".tab").forEach(b => b.classList.remove("active"));
btn.classList.add("active");
document.querySelectorAll(".tab-content").forEach(c => c.classList.add("hidden"));
document.getElementById(btn.dataset.tab + "Tab").classList.remove("hidden");
});
});
let paymentChart;
function renderPaymentChart(upi, cash) {
const ctx = document.getElementById("paymentChart");
if (paymentChart) {
paymentChart.destroy(); // avoid duplicate chart
}
paymentChart = new Chart(ctx, {
type: "bar",
data: {
labels: ["UPI", "Cash"],
datasets: [{
label: "Amount ₹",
data: [upi, cash]
}]
},
options: {
plugins: {
legend: { display: false }
}
}
});
}
function renderStaffLeaderboard(stats) {
const container = document.getElementById("staffLeaderboard");
container.innerHTML = "";
const sorted = Object.entries(stats)
.filter(([name]) => name !== "Unknown")
.sort((a, b) => b[1] - a[1]);
sorted.forEach(([name, amount], index) => {
const row = document.createElement("div");
row.className = "staff-row";
row.innerHTML = `
<span class="rank">#${index + 1}</span>
<span class="name">${name}</span>
<span class="amount">₹${amount}</span>
`;
container.appendChild(row);
});
}
function animateValue(id, value) {
const el = document.getElementById(id);
const duration = 1200;
const startTime = performance.now();
const easeOut = t => 1 - Math.pow(1 - t, 3); // smooth finish
function update(currentTime) {
const raw = Math.min((currentTime - startTime) / duration, 1);
const progress = easeOut(raw);
const current = Math.floor(progress * value);
el.innerText = `₹${current}`;