-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
507 lines (455 loc) · 25 KB
/
app.js
File metadata and controls
507 lines (455 loc) · 25 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
/**
* ValueCentric — app.js
* Auth + Notification + ChainEvents + Full Smart Contract Integration
*/
// ═══════════════════════════════════════════════
// AUTH MODULE
// ═══════════════════════════════════════════════
const Auth = {
get: function () {
try { return JSON.parse(sessionStorage.getItem('vc_auth')); } catch { return null; }
},
logout: function () {
sessionStorage.removeItem('vc_auth');
window.location.href = 'login.html';
}
};
// ═══════════════════════════════════════════════
// NOTIFICATION SYSTEM (localStorage — persists across role switches)
// ═══════════════════════════════════════════════
const Notif = {
KEY: 'vc_notifications',
add: function (to, type, message, extra = {}) {
const all = this._load();
all.unshift({ id: Date.now(), to, type, message, read: false, ts: new Date().toLocaleTimeString(), ...extra });
localStorage.setItem(this.KEY, JSON.stringify(all.slice(0, 100)));
this.refresh();
},
_load: function () {
try { return JSON.parse(localStorage.getItem(this.KEY)) || []; } catch { return []; }
},
getFor: function (role) {
return this._load().filter(n => n.to === role || n.to === 'all');
},
markAllRead: function (role) {
const all = this._load().map(n =>
(n.to === role || n.to === 'all') ? { ...n, read: true } : n
);
localStorage.setItem(this.KEY, JSON.stringify(all));
this.refresh();
},
refresh: function () {
const auth = Auth.get();
if (!auth) return;
const items = this.getFor(auth.role);
const unread = items.filter(n => !n.read).length;
const badge = document.getElementById('notif-badge');
const bell = document.getElementById('notif-bell');
if (!badge) return;
badge.innerText = unread;
if (unread > 0) {
badge.classList.remove('hidden');
bell.classList.add('notif-bell-active');
} else {
badge.classList.add('hidden');
bell.classList.remove('notif-bell-active');
}
const list = document.getElementById('notif-list');
if (!list) return;
if (items.length === 0) {
list.innerHTML = '<div class="notif-empty">No notifications yet</div>';
return;
}
const typeIcons = {
buy_req: '🛒', transfer: '📦', price: '💰', recall: '🚨', sale: '📉', info: 'ℹ️'
};
list.innerHTML = items.map(n => `
<div class="notif-item ${n.read ? 'notif-read' : 'notif-unread'}">
<div class="notif-item-icon">${typeIcons[n.type] || 'ℹ️'}</div>
<div class="notif-item-body">
<div class="notif-item-msg">${n.message}</div>
<div class="notif-item-time">${n.ts}</div>
</div>
</div>`).join('');
}
};
// ═══════════════════════════════════════════════
// CHAIN EVENTS LOG
// ═══════════════════════════════════════════════
const ChainEvents = {
lastBlock: 0,
polling: null,
start: function () {
this.poll();
this.polling = setInterval(() => this.poll(), 8000);
},
poll: async function () {
if (!App.contractInstance) return;
try {
const latest = await web3.eth.getBlockNumber();
if (latest < this.lastBlock) return;
const events = await App.contractInstance.getPastEvents('allEvents', {
fromBlock: this.lastBlock || 0,
toBlock: 'latest'
});
events.forEach(ev => this.append(ev));
this.lastBlock = parseInt(latest) + 1;
} catch (_) {}
},
append: function (ev) {
const log = document.getElementById('chainLog');
if (!log) return;
const icons = {
ProductRegistered: '⛏️',
OwnershipTransferred: '📦',
PriceUpdated: '💰',
ProductRecalled: '🚨',
QuantityReduced: '📉',
Transfer: '🔄'
};
const icon = icons[ev.event] || '⛓';
const vals = Object.entries(ev.returnValues)
.filter(([k]) => isNaN(k))
.map(([k, v]) => {
const sv = String(v);
return `<span class="ce-key">${k}</span>: <span class="ce-val">${sv.startsWith('0x') ? sv.substring(0,10)+'...' : sv}</span>`;
}).join(' | ');
const entry = document.createElement('div');
entry.className = 'log-entry log-info ce-entry';
entry.innerHTML = `
<span class="log-time">[Block ${ev.blockNumber}]</span> ${icon}
<span class="ce-name">${ev.event}</span><br>
<span class="ce-vals">${vals}</span>`;
log.prepend(entry);
while (log.children.length > 60) log.removeChild(log.lastChild);
}
};
// ═══════════════════════════════════════════════
// MAIN APP
// ═══════════════════════════════════════════════
const App = {
web3Provider: null,
accounts: [],
account: '0x0',
contractInstance: null,
currentRole: null,
// ── INIT ──────────────────────────────────────
init: async function () {
const auth = Auth.get();
if (!auth) { window.location.href = 'login.html'; return; }
App.currentRole = auth.role;
App.setRoleUI(auth);
await App.initWeb3();
await App.loadContract();
// Start notification polling (cross-tab via storage event)
Notif.refresh();
window.addEventListener('storage', e => {
if (e.key === 'vc_notifications') Notif.refresh();
});
// Start chain events polling
ChainEvents.start();
},
setRoleUI: function (auth) {
const roleIndex = auth.roleIndex;
const icons = ['⚖️','🏭','🚚','🏪'];
const colors = ['regulator','manufacturer','distributor','retailer'];
// Header badge
const badge = document.getElementById('roleBadge');
badge.className = `role-badge role-${colors[roleIndex]}`;
badge.innerText = auth.label;
// Sidebar user profile
const icon = document.getElementById('user-icon');
if (icon) { icon.innerText = icons[roleIndex]; icon.className = `user-icon uid-${colors[roleIndex]}`; }
const nameEl = document.getElementById('user-role-name');
if (nameEl) nameEl.innerText = auth.label;
// Show correct panel only
document.querySelectorAll('.role-panel').forEach(p => p.classList.add('hidden'));
const panel = document.getElementById(`panel-${auth.role}`);
if (panel) panel.classList.remove('hidden');
},
// ── WEB3 ──────────────────────────────────────
initWeb3: async function () {
try {
App.web3Provider = new Web3.providers.HttpProvider('http://127.0.0.1:8545');
web3 = new Web3(App.web3Provider);
App.accounts = await web3.eth.getAccounts();
if (!App.accounts || App.accounts.length < 4) {
App.updateStatus('Need at least 4 Ganache accounts!', 'error');
App.log('Start ganache with --accounts 10 --deterministic', 'error');
return;
}
const auth = Auth.get();
App.account = App.accounts[auth.roleIndex];
document.getElementById('activeAccount').innerText = App.account;
document.getElementById('user-account').innerText = App.account.substring(0,14)+'...';
App.updateStatus('Connected to Ganache ✓', 'success');
App.log(`Connected. Active wallet: ${App.account}`, 'info');
} catch (err) {
App.updateStatus('Ganache connection failed!', 'error');
App.log(`Web3 error: ${err.message}`, 'error');
}
},
loadContract: async function () {
try {
const res = await fetch('abi/ValueCentricSC.json?v=' + Date.now());
if (!res.ok) throw new Error('ABI not found. Run: truffle compile');
const artifact = await res.json();
const networkId = (await web3.eth.net.getId()).toString();
const net = artifact.networks[networkId];
if (!net) {
App.updateStatus('Contract not found on network!', 'error');
App.log(`No contract on network ${networkId}. Run: truffle migrate --reset then copy ABI.`, 'error');
return;
}
App.contractInstance = new web3.eth.Contract(artifact.abi, net.address);
App.updateStatus(`Contract Active @ ${net.address.substring(0,14)}...`, 'success');
App.log(`Contract loaded at: ${net.address}`, 'info');
} catch (err) {
App.updateStatus('Contract load failed!', 'error');
App.log(`Contract error: ${err.message}`, 'error');
}
},
// ── UTILITIES ────────────────────────────────
updateStatus: function (msg, type = 'info') {
const el = document.getElementById('status');
el.innerText = msg; el.className = `status-bar status-${type}`;
},
log: function (msg, type = 'success') {
const log = document.getElementById('txLog');
const t = new Date().toLocaleTimeString();
const icons = { success:'✅', error:'❌', info:'ℹ️', warning:'⚠️' };
const entry = document.createElement('div');
entry.className = `log-entry log-${type}`;
entry.innerHTML = `<span class="log-time">[${t}]</span> ${icons[type]||'ℹ️'} ${msg}`;
log.prepend(entry);
while (log.children.length > 80) log.removeChild(log.lastChild);
},
shortTx: h => `${h.substring(0,10)}...${h.substring(h.length-6)}`,
ok: function () { return !!App.contractInstance || (App.log('Contract not initialized.','error'), false); },
val: function (v, name) { if (!v && v!==0) { App.log(`${name} is required.`,'error'); return false; } return true; },
logout: function () { Auth.logout(); },
clearLog: function () { document.getElementById('txLog').innerHTML=''; App.log('Log cleared.','info'); },
switchLogTab: function (tab) {
const isTx = tab==='tx';
document.getElementById('txLog').classList.toggle('hidden', !isTx);
document.getElementById('chainLog').classList.toggle('hidden', isTx);
document.getElementById('tab-tx').classList.toggle('active', isTx);
document.getElementById('tab-chain').classList.toggle('active', !isTx);
},
toggleNotifications: function () {
const dd = document.getElementById('notif-dropdown');
dd.classList.toggle('hidden');
if (!dd.classList.contains('hidden')) {
const auth = Auth.get();
if (auth) { Notif.markAllRead(auth.role); }
}
},
markAllRead: function () {
const auth = Auth.get();
if (auth) { Notif.markAllRead(auth.role); }
},
// ── MANUFACTURER ─────────────────────────────
registerProduct: async function () {
const serial = document.getElementById('reg-serial').value.trim();
const batch = document.getElementById('reg-batch').value.trim();
const name = document.getElementById('reg-name').value.trim();
const qty = parseInt(document.getElementById('reg-qty').value);
const price = parseInt(document.getElementById('reg-price').value);
const origin = document.getElementById('reg-origin').value.trim();
if (!serial||!batch||!name||!qty||!price||!origin) return App.log('All fields required.','error');
if (!App.ok()) return;
const mfgDate = Math.floor(Date.now()/1000);
try {
App.log(`Registering [${serial}] "${name}" | Qty:${qty} Price:${price}...`,'info');
const r = await App.contractInstance.methods
.registerProduct(serial,{batchID:batch,productName:name,quantity:qty,pricePerUnit:price,manufacturingDate:mfgDate,expiryDate:mfgDate+31536000,origin})
.send({from:App.account,gas:500000});
App.log(`[${serial}] registered & NFT minted! Batch:${batch} Qty:${qty} Price:${price}/unit | TX:${App.shortTx(r.transactionHash)}`,'success');
} catch(e){ App.log(`Register failed: ${e.message}`,'error'); }
},
transferToDistributor: async function () {
const s = document.getElementById('mfr-serial').value.trim();
if (!s||!App.ok()) return App.log('Enter serial number.','error');
try {
App.log(`Transferring [${s}] → Distributor...`,'info');
const r = await App.contractInstance.methods.transferToDistributor(s).send({from:App.account,gas:300000});
App.log(`[${s}] NFT transferred to Distributor. Stage: Distribution | TX:${App.shortTx(r.transactionHash)}`,'success');
Notif.add('distributor','transfer',`Product [${s}] has been transferred to you by Manufacturer. Set your markup price next.`,{serial:s});
} catch(e){ App.log(`Transfer failed: ${e.message}`,'error'); }
},
// ── DISTRIBUTOR ──────────────────────────────
distributorRequest: async function () {
const s = document.getElementById('distr-req-serial').value.trim();
if (!s||!App.ok()) return App.log('Enter serial number.','error');
try {
App.log(`Submitting buy request for [${s}] to Manufacturer...`,'info');
const r = await App.contractInstance.methods.distributorBuyRequest(s).send({from:App.account,gas:200000});
App.log(`Buy request for [${s}] submitted. Awaiting Manufacturer approval. TX:${App.shortTx(r.transactionHash)}`,'success');
Notif.add('manufacturer','buy_req',`🛒 Distributor has requested product [${s}]. Please review and transfer.`,{serial:s});
} catch(e){ App.log(`Request failed: ${e.message}`,'error'); }
},
updatePrice: async function () {
const s = document.getElementById('distr-price-serial').value.trim();
const p = parseInt(document.getElementById('markup-price').value);
if (!s||isNaN(p)||p<=0) return App.log('Enter serial number and valid price.','error');
if (!App.ok()) return;
try {
App.log(`Setting markup price for [${s}] to ${p} units...`,'info');
const r = await App.contractInstance.methods.updateSalePrice(s,p).send({from:App.account,gas:200000});
App.log(`Markup price for [${s}] set to ${p} units. TX:${App.shortTx(r.transactionHash)}`,'success');
Notif.add('regulator','price',`Distributor set markup price for [${s}] to ${p} units.`,{serial:s});
} catch(e){ App.log(`Price update failed: ${e.message}`,'error'); }
},
transferToRetailer: async function () {
const s = document.getElementById('distr-transfer-serial').value.trim();
if (!s||!App.ok()) return App.log('Enter serial number.','error');
try {
App.log(`Transferring [${s}] → Retailer...`,'info');
const r = await App.contractInstance.methods.transferToRetailer(s).send({from:App.account,gas:300000});
App.log(`[${s}] NFT transferred to Retailer. Stage: Retail | TX:${App.shortTx(r.transactionHash)}`,'success');
Notif.add('retailer','transfer',`Product [${s}] has been transferred to you by Distributor. You may now sell.`,{serial:s});
} catch(e){ App.log(`Transfer failed: ${e.message}`,'error'); }
},
// ── RETAILER ─────────────────────────────────
retailerRequest: async function () {
const s = document.getElementById('ret-req-serial').value.trim();
if (!s||!App.ok()) return App.log('Enter serial number.','error');
try {
App.log(`Submitting buy request for [${s}] to Distributor...`,'info');
const r = await App.contractInstance.methods.retailerBuyRequest(s).send({from:App.account,gas:200000});
App.log(`Buy request for [${s}] submitted. Awaiting Distributor. TX:${App.shortTx(r.transactionHash)}`,'success');
Notif.add('distributor','buy_req',`🛒 Retailer has requested product [${s}]. Please review and transfer.`,{serial:s});
} catch(e){ App.log(`Request failed: ${e.message}`,'error'); }
},
reduceQuantity: async function () {
const s = document.getElementById('ret-reduce-serial').value.trim();
const a = parseInt(document.getElementById('reduce-amount').value);
if (!s||isNaN(a)||a<=0) return App.log('Enter serial number and valid amount.','error');
if (!App.ok()) return;
try {
App.log(`Recording sale of ${a} units of [${s}]...`,'info');
const r = await App.contractInstance.methods.reduceQuantity(s,a).send({from:App.account,gas:200000});
App.log(`${a} units of [${s}] sold and recorded. TX:${App.shortTx(r.transactionHash)}`,'success');
const remaining = await App.contractInstance.methods.getStock(s).call();
App.log(`[${s}] Remaining stock: ${remaining} units.`,'info');
Notif.add('regulator','sale',`Retailer sold ${a} units of [${s}]. Remaining stock: ${remaining}.`,{serial:s});
} catch(e){ App.log(`Reduce failed: ${e.message}`,'error'); }
},
// ── REGULATOR ────────────────────────────────
smartRecall: async function () {
const s = document.getElementById('reg-recall-serial').value.trim();
if (!s||!App.ok()) return App.log('Enter serial number.','error');
try {
App.log(`⚠️ Issuing Smart Recall for [${s}]...`,'warning');
const r = await App.contractInstance.methods.smartRecall(s).send({from:App.account,gas:200000});
App.log(`🚨 RECALL ISSUED: [${s}] flagged RECALLED. All transfers BLOCKED. TX:${App.shortTx(r.transactionHash)}`,'error');
Notif.add('all','recall',`🚨 RECALL: Regulator has recalled product [${s}]. All transfers are now permanently blocked.`,{serial:s});
} catch(e){ App.log(`Recall failed: ${e.message}`,'error'); }
},
// ── REGULATOR AUDIT (full details) ───────────
regulatorAudit: async function () {
const s = document.getElementById('reg-audit-serial').value.trim();
if (!s||!App.ok()) return App.log('Enter a serial number.','error');
try {
App.log(`Running full audit on [${s}]...`,'info');
const d = await App.contractInstance.methods.getRegulatorDetails(s).call({from:App.account});
// d: [0]batchID [1]productName [2]initialQty [3]currentQty [4]oldPrice [5]newPrice
// [6]currentOwner [7]currentStage [8]isRecalled [9]mfgDate [10]expDate
const recalled = d[8];
const fields = [
{icon:'🔑', label:'Serial Number', value: s},
{icon:'📦', label:'Batch ID', value: d[0]},
{icon:'💊', label:'Product Name', value: d[1]},
{icon:'🏭', label:'Initial Quantity', value: `${d[2]} units`},
{icon:'📊', label:'Current Stock', value: `${d[3]} units`},
{icon:'💰', label:'Manufacturer Price', value: `${d[4]} units/unit`},
{icon:'💸', label:'Distributor Markup', value: d[5]==0 ? 'Not set yet' : `${d[5]} units/unit`},
{icon:'👤', label:'Current Owner', value: d[6]},
{icon:'🚚', label:'Supply Chain Stage', value: d[7]},
{icon:'🚨', label:'Recall Status', value: recalled ? '⛔ RECALLED — All transfers blocked' : '✅ Not recalled'},
{icon:'📅', label:'Manufacturing Date', value: new Date(parseInt(d[9])*1000).toLocaleDateString()},
{icon:'⏳', label:'Expiry Date', value: new Date(parseInt(d[10])*1000).toLocaleDateString()},
];
const grid = document.getElementById('reg-audit-grid');
grid.innerHTML = fields.map(f => `
<div class="audit-field ${f.label==='Recall Status' && recalled ? 'audit-field-danger' : ''}">
<div class="audit-field-icon">${f.icon}</div>
<div class="audit-field-label">${f.label}</div>
<div class="audit-field-value">${f.value}</div>
</div>`).join('');
document.getElementById('reg-audit-result').classList.remove('hidden');
App.log(`Full audit complete for [${s}]. Stage: ${d[7]} | Recalled: ${recalled ? 'YES ⛔' : 'No ✅'}`,'success');
} catch(e){ App.log(`Audit failed: ${e.message}`,'error'); }
},
regulatorStockCheck: async function () {
const s = document.getElementById('reg-audit-serial').value.trim();
if (!s||!App.ok()) return App.log('Enter a serial number first.','error');
try {
const [stock, owner] = await Promise.all([
App.contractInstance.methods.getStock(s).call(),
App.contractInstance.methods.ownerOf(s).call()
]);
App.log(`[${s}] — Current Stock: ${stock} units | NFT Owner: ${owner}`,'info');
} catch(e){ App.log(`Stock check failed: ${e.message}`,'error'); }
},
regulatorBalanceCheck: async function () {
if (!App.ok()) return;
try {
const [b0,b1,b2,b3] = await Promise.all([
App.contractInstance.methods.balanceOf(App.accounts[0]).call(),
App.contractInstance.methods.balanceOf(App.accounts[1]).call(),
App.contractInstance.methods.balanceOf(App.accounts[2]).call(),
App.contractInstance.methods.balanceOf(App.accounts[3]).call(),
]);
App.log(`NFT Balances — Regulator:${b0} | Manufacturer:${b1} | Distributor:${b2} | Retailer:${b3}`,'info');
} catch(e){ App.log(`Balance check failed: ${e.message}`,'error'); }
},
// ── QUERY ─────────────────────────────────────
getDetails: async function () {
const s = document.getElementById('audit-serial').value.trim();
if (!s||!App.ok()) return App.log('Enter a serial number.','error');
const auth = Auth.get();
const role = auth ? auth.role : '';
try {
App.log(`Querying [${s}] as ${auth.label}...`,'info');
let d, html='';
if (role==='regulator'){
d = await App.contractInstance.methods.getRegulatorDetails(s).call({from:App.account});
html=`Batch ID : ${d[0]}\nProduct : ${d[1]}\nInitial Qty : ${d[2]}\nCurrent Qty : ${d[3]}\nMfr Price : ${d[4]} units\nDistr Markup : ${d[5]==0?'Not set':d[5]+' units'}\nCurrent Owner : ${d[6]}\nStage : ${d[7]}\nRecalled : ${d[8]?'⛔ YES':'✅ No'}\nMfg Date : ${new Date(d[9]*1000).toLocaleDateString()}\nExpiry : ${new Date(d[10]*1000).toLocaleDateString()}`;
} else if (role==='manufacturer'){
d = await App.contractInstance.methods.getMfrDetails(s).call({from:App.account});
html=`Batch ID : ${d[0]}\nProduct : ${d[1]}\nQty Transferred: ${d[2]==0?'Not yet':d[2]}\nSale Price : ${d[3]} units\nSold To : ${d[4]==='0x0000000000000000000000000000000000000000'?'Not transferred':d[4]}\nRecalled : ${d[5]?'⛔ YES':'✅ No'}\nMfg Date : ${new Date(d[6]*1000).toLocaleDateString()}\nExpiry : ${new Date(d[7]*1000).toLocaleDateString()}`;
} else if (role==='distributor'){
d = await App.contractInstance.methods.getDistrDetails(s).call({from:App.account});
html=`Batch ID : ${d[0]}\nProduct : ${d[1]}\nReceived Qty : ${d[2]==0?'Not received':d[2]}\nPurchase Price : ${d[3]} units\nMarkup Price : ${d[4]==0?'Not set':d[4]+' units'}\nBought From : ${d[5]==='0x0000000000000000000000000000000000000000'?'N/A':d[5]}\nSold To : ${d[6]==='0x0000000000000000000000000000000000000000'?'Not yet':d[6]}\nRecalled : ${d[7]?'⛔ YES':'✅ No'}\nMfg Date : ${new Date(d[8]*1000).toLocaleDateString()}\nExpiry : ${new Date(d[9]*1000).toLocaleDateString()}`;
} else if (role==='retailer'){
d = await App.contractInstance.methods.getRetailerDetails(s).call({from:App.account});
html=`Batch ID : ${d[0]}\nProduct : ${d[1]}\nCurrent Stock : ${d[2]} units\nAcq. Price : ${d[3]==0?'Not received':d[3]+' units'}\nBought From : ${d[4]==='0x0000000000000000000000000000000000000000'?'N/A':d[4]}\nRecalled : ${d[5]?'⛔ YES':'✅ No'}\nMfg Date : ${new Date(d[6]*1000).toLocaleDateString()}\nExpiry : ${new Date(d[7]*1000).toLocaleDateString()}`;
}
document.getElementById('auditResult').innerHTML=`<pre class="audit-output">${html}</pre>`;
App.log(`Audit data for [${s}] fetched (${auth.label}).`,'success');
} catch(e){ App.log(`Query failed: ${e.message}`,'error'); }
},
checkStock: async function () {
const s = document.getElementById('audit-serial').value.trim();
if (!s||!App.ok()) return App.log('Enter a serial number.','error');
try {
const [stock, owner] = await Promise.all([
App.contractInstance.methods.getStock(s).call(),
App.contractInstance.methods.ownerOf(s).call()
]);
App.log(`[${s}] Stock: ${stock} units | Owner: ${owner}`,'info');
document.getElementById('auditResult').innerHTML=`<pre class="audit-output">Serial : ${s}\nStock : ${stock} units\nOwner : ${owner}</pre>`;
} catch(e){ App.log(`Stock check failed: ${e.message}`,'error'); }
}
};
window.app = App;
window.addEventListener('load', App.init);
// Close notification dropdown when clicking outside
document.addEventListener('click', e => {
const wrapper = document.querySelector('.notif-wrapper');
if (wrapper && !wrapper.contains(e.target)) {
const dd = document.getElementById('notif-dropdown');
if (dd) dd.classList.add('hidden');
}
});