-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
425 lines (346 loc) · 10.8 KB
/
Copy pathscript.js
File metadata and controls
425 lines (346 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
// ================= SUPABASE SETUP =================
const SUPABASE_URL = "https://gunkkbepdlsdwgxgpcxj.supabase.co";
const SUPABASE_ANON_KEY = "sb_publishable__peI72hPciL0iaBVn0odIg_Uv6D1OTz";
const supabaseClient = window.supabase.createClient(
SUPABASE_URL,
SUPABASE_ANON_KEY
);
let currentUserId = null;
let html5QrCode = null;
let scannedCode = null;
let userMap = {};
// ================= 🔔 CUSTOM NOTIFICATION =================
function showNotify(message) {
const overlay = document.getElementById("notifyOverlay");
const text = document.getElementById("notifyMessage");
if (!overlay || !text) return;
text.textContent = message;
overlay.classList.remove("hidden");
}
function closeNotify() {
document.getElementById("notifyOverlay").classList.add("hidden");
}
// ================= 👤 PROFILE =================
async function ensureProfile(user) {
const username = user.user_metadata?.username || "unknown";
const { data } = await supabaseClient
.from("profiles")
.select("id")
.eq("id", user.id)
.single();
if (!data) {
await supabaseClient.from("profiles").insert({
id: user.id,
username
});
}
}
async function loadUsernames() {
const { data } = await supabaseClient
.from("profiles")
.select("id, username");
userMap = {};
data?.forEach(u => userMap[u.id] = u.username);
}
// ================= SELECT ALL (MY BARCODES) =================
function toggleSelectAll(master) {
document
.querySelectorAll(".row-check")
.forEach(cb => cb.checked = master.checked);
}
function syncSelectAll() {
const all = document.querySelectorAll(".row-check");
const checked = document.querySelectorAll(".row-check:checked");
const master = document.getElementById("selectAll");
if (master) {
master.checked = all.length && all.length === checked.length;
}
}
// ================= LOAD USER =================
async function loadUser() {
const { data } = await supabaseClient.auth.getUser();
if (!data.user) {
window.location.href = "../login-UI/signin.html";
return;
}
currentUserId = data.user.id;
await ensureProfile(data.user);
await loadUsernames();
document.getElementById("dashboard-title").textContent =
`${userMap[currentUserId]} Dashboard`;
closeScanner(true);
loadMyBarcodes();
loadCommonSummary();
}
// ================= TABS =================
function showTab(tabName) {
document.getElementById("my").classList.add("hidden");
document.getElementById("common").classList.add("hidden");
document.querySelectorAll(".tab").forEach(b => b.classList.remove("active"));
document.getElementById(tabName).classList.remove("hidden");
event.target.classList.add("active");
}
// ================= SAVE BARCODE =================
async function saveBarcode() {
const input = document.getElementById("barcode-input");
const barcode = input.value.trim();
if (!barcode) {
showNotify("Please enter a barcode");
return;
}
const { data: existing } = await supabaseClient
.from("user_scans")
.select("*")
.eq("user_id", currentUserId)
.eq("barcode", barcode)
.single();
if (existing) {
await supabaseClient
.from("user_scans")
.update({ quantity: existing.quantity + 1 })
.eq("id", existing.id);
} else {
await supabaseClient
.from("user_scans")
.insert({ user_id: currentUserId, barcode, quantity: 1 });
}
input.value = "";
loadMyBarcodes();
loadCommonSummary();
}
// ================= DELETE SINGLE (MY) =================
async function deleteBarcode(barcode) {
const { error } = await supabaseClient
.from("user_scans")
.delete()
.eq("user_id", currentUserId)
.eq("barcode", barcode);
if (error) {
showNotify("Delete failed");
return;
}
loadMyBarcodes();
loadCommonSummary();
}
// ================= BULK DELETE (MY) =================
async function deleteSelected() {
const checked = document.querySelectorAll(".row-check:checked");
if (!checked.length) {
showNotify("No barcodes selected");
return;
}
const barcodes = Array.from(checked).map(cb => cb.dataset.barcode);
const { error } = await supabaseClient
.from("user_scans")
.delete()
.eq("user_id", currentUserId)
.in("barcode", barcodes);
if (error) {
showNotify("Failed to delete selected");
return;
}
showNotify("Selected barcodes deleted");
loadMyBarcodes();
loadCommonSummary();
}
// ================= LOAD MY BARCODES =================
async function loadMyBarcodes() {
const tbody = document.getElementById("myBarcodesBody");
tbody.innerHTML = "";
const { data } = await supabaseClient
.from("user_scans")
.select("*")
.eq("user_id", currentUserId)
.order("created_at", { ascending: false });
data.forEach(row => {
const tr = document.createElement("tr");
tr.innerHTML = `
<td>
<input type="checkbox"
class="row-check"
data-barcode="${row.barcode}"
onchange="syncSelectAll()">
${row.barcode}
</td>
<td>${row.quantity}</td>
<td>${new Date(row.created_at).toLocaleDateString()}</td>
<td>
<span class="delete" onclick="deleteBarcode('${row.barcode}')">🗑</span>
</td>
`;
tbody.appendChild(tr);
});
syncSelectAll();
}
// ================= COMMON SUMMARY =================
async function loadCommonSummary() {
const tbody = document.getElementById("commonSummaryBody");
tbody.innerHTML = "";
const { data } = await supabaseClient
.from("user_scans")
.select("barcode, quantity, user_id");
const summary = {};
data.forEach(row => {
if (!summary[row.barcode]) {
summary[row.barcode] = { total: 0, users: {} };
}
summary[row.barcode].total += row.quantity;
summary[row.barcode].users[row.user_id] =
(summary[row.barcode].users[row.user_id] || 0) + row.quantity;
});
Object.entries(summary).forEach(([barcode, info]) => {
const usersHtml = Object.entries(info.users)
.map(([uid, count]) => {
const name = uid === currentUserId ? "you" : userMap[uid] || "unknown";
return `<span class="chip">${name}: ${count}</span>`;
}).join(" ");
const tr = document.createElement("tr");
tr.innerHTML = `
<td>
<input type="checkbox" class="common-check" data-barcode="${barcode}">
${barcode}
</td>
<td>${usersHtml}</td>
<td>${info.total}</td>
<td>
<span class="delete" onclick="deleteCommonBarcode('${barcode}')">🗑</span>
</td>
`;
tbody.appendChild(tr);
});
}
// ================= DELETE COMMON (SINGLE) =================
async function deleteCommonBarcode(barcode) {
const { error } = await supabaseClient
.from("user_scans")
.delete()
.eq("barcode", barcode);
if (error) {
showNotify("Delete failed");
return;
}
loadMyBarcodes();
loadCommonSummary();
}
// ================= DELETE COMMON (BULK) =================
async function deleteCommonSelected() {
const checked = document.querySelectorAll(".common-check:checked");
if (!checked.length) {
showNotify("No barcodes selected");
return;
}
const barcodes = Array.from(checked).map(cb => cb.dataset.barcode);
const { error } = await supabaseClient
.from("user_scans")
.delete()
.in("barcode", barcodes);
if (error) {
showNotify("Failed to delete selected");
return;
}
showNotify("Selected barcodes deleted");
loadMyBarcodes();
loadCommonSummary();
}
// ================= CAMERA =================
function openScanner() {
document.getElementById("scannerOverlay").classList.remove("hidden");
scannedCode = null;
html5QrCode = new Html5Qrcode("reader");
html5QrCode.start(
{ facingMode: "environment" },
{ fps: 10, qrbox: { width: 250, height: 150 } },
text => scannedCode = text
);
}
function tryAgain() {
closeScanner();
openScanner();
}
function saveScanned() {
if (!scannedCode) {
showNotify("No barcode detected yet");
return;
}
document.getElementById("barcode-input").value = scannedCode;
saveBarcode();
closeScanner();
}
function closeScanner(force = false) {
if (html5QrCode) {
html5QrCode.stop().catch(() => {});
html5QrCode = null;
}
document.getElementById("scannerOverlay").classList.add("hidden");
}
//excel my barcode//
async function downloadMyBarcodesExcel() {
const { data, error } = await supabaseClient
.from("user_scans")
.select("barcode, quantity, created_at")
.eq("user_id", currentUserId)
.order("created_at", { ascending: false });
if (error || !data.length) {
showNotify("No data to export");
return;
}
const formatted = data.map(row => ({
Barcode: row.barcode,
Quantity: row.quantity,
"Last Scanned": new Date(row.created_at).toLocaleDateString()
}));
const worksheet = XLSX.utils.json_to_sheet(formatted);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, "My Barcodes");
XLSX.writeFile(workbook, "my-barcodes.xlsx");
}
//excel common summary//
async function downloadCommonSummaryExcel() {
const { data, error } = await supabaseClient
.from("user_scans")
.select("barcode, quantity, user_id");
if (error || !data.length) {
showNotify("No data to export");
return;
}
const summary = {};
data.forEach(row => {
if (!summary[row.barcode]) {
summary[row.barcode] = {
users: {},
total: 0
};
}
const username =
row.user_id === currentUserId
? "you"
: userMap[row.user_id] || "unknown";
summary[row.barcode].users[username] =
(summary[row.barcode].users[username] || 0) + row.quantity;
summary[row.barcode].total += row.quantity;
});
const rows = Object.entries(summary).map(([barcode, info]) => {
const userCounts = Object.entries(info.users)
.map(([name, count]) => `${name}: ${count}`)
.join(", ");
return {
Barcode: barcode,
"User Counts": userCounts,
Total: info.total
};
});
const worksheet = XLSX.utils.json_to_sheet(rows);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, "Common Summary");
XLSX.writeFile(workbook, "common-summary.xlsx");
}
//logout//
async function logout() {
await supabaseClient.auth.signOut();
// force-clear browser state
localStorage.clear();
sessionStorage.clear();
window.location.href = "../login-UI/signin.html";
}
// ================= INIT =================
loadUser();