bep40 commited on
Commit
aa35bbc
·
verified ·
1 Parent(s): 4fce37e

Upload vai-excel-images-fix-v2.js

Browse files
Files changed (1) hide show
  1. vai-excel-images-fix-v2.js +526 -0
vai-excel-images-fix-v2.js ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * V.AI STUDIO - Excel Export WITH Product Images
3
+ * Phiên bản hoàn chỉnh - Thay thế cho vai-quote-excel-order-fix-v1050.js
4
+ *
5
+ * TÍNH NĂNG:
6
+ * ✅ Xuất Excel có hình ảnh sản phẩm (cột "Hình")
7
+ * ✅ Download nhiều lần không lỗi (dựa trên fix v1050)
8
+ * ✅ Hỗ trợ cả Quote và Order modal
9
+ * ✅ Toast thông báo
10
+ */
11
+
12
+ (function() {
13
+ 'use strict';
14
+
15
+ // ========== GLOBAL BLOB REGISTRY ==========
16
+ window.__VAI_BLOB_REGISTRY = window.__VAI_BLOB_REGISTRY || {
17
+ blobs: [],
18
+ registry: [],
19
+ isUnloading: false
20
+ };
21
+ var globalRegistry = window.__VAI_BLOB_REGISTRY;
22
+
23
+ function cleanupAllBlobs() {
24
+ globalRegistry.isUnloading = true;
25
+ globalRegistry.blobs.forEach(function(blob) {
26
+ if (!blob.revoked) {
27
+ try { URL.revokeObjectURL(blob.url); blob.revoked = true; } catch(err) {}
28
+ }
29
+ });
30
+ globalRegistry.registry.forEach(function(entry) {
31
+ if (!entry.revoked) {
32
+ try { URL.revokeObjectURL(entry.url); entry.revoked = true; } catch(err) {}
33
+ }
34
+ });
35
+ }
36
+
37
+ window.addEventListener('pagehide', cleanupAllBlobs);
38
+ window.addEventListener('beforeunload', cleanupAllBlobs);
39
+ window.addEventListener('unload', cleanupAllBlobs);
40
+
41
+ if (!window.__VAI_REVOKE_PATCHED) {
42
+ var originalRevoke = URL.revokeObjectURL;
43
+ URL.revokeObjectURL = function(url) {
44
+ if (globalRegistry.isUnloading || !url || typeof url !== 'string' || !url.startsWith('blob:')) {
45
+ return originalRevoke.apply(this, arguments);
46
+ }
47
+ var found = globalRegistry.registry.find(function(e) { return e.url === url; });
48
+ if (!found) {
49
+ globalRegistry.registry.push({ url: url, revoked: false, created: Date.now() });
50
+ }
51
+ return undefined;
52
+ };
53
+ window.__VAI_REVOKE_PATCHED = true;
54
+ }
55
+
56
+ // ========== HELPER FUNCTIONS ==========
57
+ function stripDiacritics(s) {
58
+ if (!s) return '';
59
+ return s.normalize('NFD').replace(/[\u0300-\u36f]/g, '').replace(/[Đđ]/g, 'D');
60
+ }
61
+
62
+ function generateOrderCode(name) {
63
+ var now = new Date();
64
+ var dd = String(now.getDate()).padStart(2, '0');
65
+ var mm = String(now.getMonth() + 1).padStart(2, '0');
66
+ var yy = String(now.getFullYear()).slice(-2);
67
+ var ini = '';
68
+ if (name && name.trim()) {
69
+ name.trim().split(/\s+/).forEach(function(w) {
70
+ if (w) {
71
+ var ch = stripDiacritics(w.charAt(0)).toUpperCase();
72
+ if (/[A-Z]/.test(ch)) ini += ch;
73
+ }
74
+ });
75
+ }
76
+ return 'VAS' + (ini || 'X') + dd + mm + yy;
77
+ }
78
+
79
+ // ========== FETCH IMAGE AS BASE64 ==========
80
+ async function fetchImageAsBase64(url) {
81
+ if (!url || !url.trim()) return null;
82
+ try {
83
+ const response = await fetch(url, { mode: 'cors', credentials: 'omit' });
84
+ if (!response.ok) return null;
85
+ const blob = await response.blob();
86
+ return new Promise((resolve) => {
87
+ const reader = new FileReader();
88
+ reader.onloadend = () => resolve(reader.result);
89
+ reader.readAsDataURL(blob);
90
+ });
91
+ } catch (err) {
92
+ return await loadImageCanvasFallback(url);
93
+ }
94
+ }
95
+
96
+ function loadImageCanvasFallback(url) {
97
+ return new Promise((resolve) => {
98
+ const img = new Image();
99
+ img.crossOrigin = 'anonymous';
100
+ img.referrerPolicy = 'no-referrer';
101
+ img.onload = function() {
102
+ try {
103
+ const canvas = document.createElement('canvas');
104
+ const ctx = canvas.getContext('2d');
105
+ if (!ctx) { resolve(null); return; }
106
+ canvas.width = 80;
107
+ canvas.height = 80;
108
+ ctx.fillStyle = '#ffffff';
109
+ ctx.fillRect(0, 0, 80, 80);
110
+ ctx.drawImage(img, 0, 0, 80, 80);
111
+ resolve(canvas.toDataURL('image/jpeg', 0.7));
112
+ } catch (e) { resolve(null); }
113
+ };
114
+ img.onerror = () => resolve(null);
115
+ img.src = url;
116
+ });
117
+ }
118
+
119
+ // ========== CLICK PROTECTION ==========
120
+ function setExportButtonState(btn, exporting) {
121
+ if (!btn) return;
122
+ if (exporting) {
123
+ btn.disabled = true;
124
+ btn.dataset.vaiExporting = '1';
125
+ btn.dataset.vaiOrigText = btn.innerHTML;
126
+ btn.style.opacity = '0.7';
127
+ btn.innerHTML = '<span>⏳ Đang xuất...</span>';
128
+ } else {
129
+ btn.disabled = false;
130
+ btn.dataset.vaiExporting = '0';
131
+ btn.style.opacity = '';
132
+ if (btn.dataset.vaiOrigText) btn.innerHTML = btn.dataset.vaiOrigText;
133
+ }
134
+ }
135
+
136
+ // ========== GET DATA FROM CART ==========
137
+ function getQuoteData() {
138
+ var items = [];
139
+ var total = 0;
140
+
141
+ if (window.cart && window.cart.length > 0) {
142
+ window.cart.forEach(function(item, idx) {
143
+ var p = (window.D && window.D[item.idx]) ? window.D[item.idx] : null;
144
+ var price = item.priceNum || item.price || (p ? p.price : 0) || 0;
145
+ var qty = item.qty || 1;
146
+ var img = p ? (p.img || p.image || '') : (item.image || '');
147
+
148
+ items.push({
149
+ stt: idx + 1,
150
+ image: img,
151
+ name: p ? (p.name || p.n || '') : (item.name || ''),
152
+ model: p ? (p.sku || p.mod || '') : (item.sku || item.model || ''),
153
+ specs: p ? (p.info || p.desc || '') : '',
154
+ qty: qty,
155
+ price: price,
156
+ discPrice: price,
157
+ total: qty * price,
158
+ note: ''
159
+ });
160
+ total += qty * price;
161
+ });
162
+ }
163
+
164
+ return {
165
+ customer: {
166
+ name: getCustomerName(),
167
+ phone: getPhone(),
168
+ email: getEmail(),
169
+ addr: getAddress(),
170
+ date: new Date().toLocaleDateString('vi-VN')
171
+ },
172
+ items: items,
173
+ grandTotal: total
174
+ };
175
+ }
176
+
177
+ function getCustomerName() {
178
+ var selectors = ['#quoteName', '#quoteCustomerName', '#checkoutName'];
179
+ for (var i = 0; i < selectors.length; i++) {
180
+ var el = document.querySelector(selectors[i]);
181
+ if (el && el.value && el.value.trim().length > 1) return el.value.trim();
182
+ }
183
+ return '';
184
+ }
185
+
186
+ function getPhone() {
187
+ var el = document.querySelector('#quotePhone, #checkoutPhone');
188
+ return el ? el.value : '';
189
+ }
190
+
191
+ function getEmail() {
192
+ var el = document.querySelector('#quoteEmail');
193
+ return el ? el.value : '';
194
+ }
195
+
196
+ function getAddress() {
197
+ var el = document.querySelector('#quoteAddr, #checkoutAddr');
198
+ return el ? el.value : '';
199
+ }
200
+
201
+ // ========== DOWNLOAD HELPER ==========
202
+ function downloadBlob(blob, filename) {
203
+ var url = URL.createObjectURL(blob);
204
+ globalRegistry.blobs.push({ url: url, revoked: false });
205
+
206
+ var a = document.createElement('a');
207
+ a.href = url;
208
+ a.download = filename;
209
+ document.body.appendChild(a);
210
+ a.click();
211
+
212
+ setTimeout(function() {
213
+ try { document.body.removeChild(a); } catch(e) {}
214
+ }, 100);
215
+ }
216
+
217
+ // ========== EXPORT EXCEL WITH IMAGES ==========
218
+ async function exportQuoteExcel(qd, code) {
219
+ if (typeof ExcelJS === 'undefined') {
220
+ if (typeof showToast === 'function') showToast('⚠️ Chưa có thư viện ExcelJS');
221
+ return;
222
+ }
223
+
224
+ var wb = new ExcelJS.Workbook();
225
+ var ws = wb.addWorksheet('Báo giá');
226
+ ws.views = [{ showGridLines: false }];
227
+ ws.columns = [
228
+ { width: 5 }, { width: 11 }, { width: 28 },
229
+ { width: 13 }, { width: 20 }, { width: 6 },
230
+ { width: 13 }, { width: 13 }, { width: 15 }, { width: 14 }
231
+ ];
232
+
233
+ // Header
234
+ ws.mergeCells('A3:J3');
235
+ ws.getCell('A3').value = 'BẢNG BÁO GIÁ';
236
+ ws.getCell('A3').font = { bold: true, size: 18, color: { argb: 'FFDB9815' } };
237
+ ws.getCell('A3').alignment = { horizontal: 'center' };
238
+
239
+ // Customer info
240
+ ws.getCell('A5').value = 'Khách hàng:';
241
+ ws.mergeCells('B5:E5');
242
+ ws.getCell('B5').value = qd.customer?.name || '';
243
+ ws.getCell('H5').value = 'Mã đơn:';
244
+ ws.mergeCells('I5:J5');
245
+ ws.getCell('I5').value = code;
246
+ ws.getCell('A6').value = 'SĐT:';
247
+ ws.mergeCells('B6:E6');
248
+ ws.getCell('B6').value = qd.customer?.phone || '';
249
+ ws.getCell('H6').value = 'Ngày:';
250
+ ws.mergeCells('I6:J6');
251
+ ws.getCell('I6').value = qd.customer?.date || '';
252
+ ws.getCell('A7').value = 'Email:';
253
+ ws.mergeCells('B7:E7');
254
+ ws.getCell('B7').value = qd.customer?.email || '';
255
+ ws.getCell('A8').value = 'Địa chỉ:';
256
+ ws.mergeCells('B8:J8');
257
+ ws.getCell('B8').value = qd.customer?.addr || '';
258
+
259
+ // Column headers
260
+ var hr = ws.getRow(10);
261
+ ['STT', 'Hình', 'Tên sản phẩm', 'Mã SP', 'Thông tin', 'SL', 'Đơn giá', 'Giá CK', 'Thành tiền', 'Ghi chú'].forEach(function(h, i) {
262
+ var c = hr.getCell(i + 1);
263
+ c.value = h;
264
+ c.font = { bold: true, color: { argb: 'FFFFFFFF' } };
265
+ c.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF003F62' } };
266
+ c.alignment = { horizontal: 'center', vertical: 'middle' };
267
+ });
268
+
269
+ // Add product rows with images
270
+ var cr = 11;
271
+ var imagePromises = [];
272
+
273
+ for (var i = 0; i < (qd.items || []).length; i++) {
274
+ var it = qd.items[i], row = ws.getRow(cr + i);
275
+ row.height = 50;
276
+
277
+ row.getCell(1).value = it.stt || i + 1;
278
+ row.getCell(1).alignment = { horizontal: 'center' };
279
+
280
+ // ADD IMAGE TO COLUMN B (index 2)
281
+ if (it.image) {
282
+ imagePromises.push(
283
+ fetchImageAsBase64(it.image).then(function(base64, rowNum) {
284
+ return function() {
285
+ if (base64) {
286
+ ws.addImage({
287
+ source: base64,
288
+ range: {
289
+ tl: { col: 1, row: cr}, // top-left: cột B, hàng hiện tại
290
+ br: { col: 2, row: cr + 1 } // bottom-right: ô tiếp theo
291
+ }
292
+ });
293
+ }
294
+ };
295
+ }.bind(null, it.image)())
296
+ );
297
+ }
298
+
299
+ row.getCell(3).value = it.name || '';
300
+ row.getCell(3).font = { bold: true, size: 9 };
301
+ row.getCell(4).value = it.model || '';
302
+ row.getCell(5).value = it.specs || '';
303
+ row.getCell(5).font = { size: 8, color: { argb: 'FF64748B' } };
304
+ row.getCell(6).value = Number(it.qty || 1);
305
+ row.getCell(6).numFmt = '#,##0';
306
+ row.getCell(6).alignment = { horizontal: 'center' };
307
+ row.getCell(7).value = Number(it.price || 0);
308
+ row.getCell(7).numFmt = '#,##0"đ"';
309
+ row.getCell(8).value = Number(it.discPrice || it.price || 0);
310
+ row.getCell(8).numFmt = '#,##0"đ"';
311
+ row.getCell(9).value = Number(it.total || 0);
312
+ row.getCell(9).numFmt = '#,##0"đ"';
313
+ row.getCell(9).font = { bold: true };
314
+ row.getCell(10).value = it.note || '';
315
+ row.getCell(10).alignment = { wrapText: true };
316
+ }
317
+
318
+ // Wait for all images to load
319
+ await Promise.all(imagePromises);
320
+
321
+ // Total row
322
+ var totalRowNum = cr + (qd.items || []).length;
323
+ ws.getRow(totalRowNum).height = 28;
324
+ ws.mergeCells(totalRowNum, 1, totalRowNum, 5);
325
+ ws.getCell('A' + totalRowNum).value = 'TỔNG CỘNG';
326
+ ws.getCell('A' + totalRowNum).font = { bold: true, size: 13, color: { argb: 'FFFFFFFF' } };
327
+ ws.getCell('A' + totalRowNum).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF003F62' } };
328
+ ws.getCell('E' + totalRowNum).value = Number(qd.grandTotal || 0);
329
+ ws.getCell('E' + totalRowNum).numFmt = '#,##0"đ"';
330
+ ws.getCell('E' + totalRowNum).font = { bold: true, size: 14, color: { argb: 'FFF0B840' } };
331
+
332
+ wb.calcProperties.fullCalcOnLoad = true;
333
+
334
+ var buf = await wb.xlsx.writeBuffer();
335
+ downloadBlob(new Blob([buf], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }), code + '.xlsx');
336
+ }
337
+
338
+ // ========== EXPORT DELIVERY EXCEL ==========
339
+ async function exportDeliveryExcel(qd, code) {
340
+ if (typeof ExcelJS === 'undefined') {
341
+ if (typeof showToast === 'function') showToast('⚠️ Chưa có thư viện ExcelJS');
342
+ return;
343
+ }
344
+
345
+ var wb = new ExcelJS.Workbook();
346
+ var ws = wb.addWorksheet('Giao hàng');
347
+ ws.views = [{ showGridLines: false }];
348
+ ws.columns = [
349
+ { width: 5 }, { width: 34 }, { width: 14 }, { width: 8 }, { width: 20 }
350
+ ];
351
+
352
+ ws.mergeCells('A1:E1');
353
+ ws.getCell('A1').value = 'PHIẾU GIAO HÀNG';
354
+ ws.getCell('A1').font = { bold: true, size: 16, color: { argb: 'FF003F62' } };
355
+ ws.getCell('A1').alignment = { horizontal: 'center' };
356
+
357
+ ws.getCell('A2').value = 'KH: ' + (qd.customer?.name || '');
358
+ ws.getCell('D2').value = 'Mã: ' + code;
359
+ ws.getCell('A3').value = 'SĐT: ' + (qd.customer?.phone || '');
360
+ ws.getCell('D3').value = 'Ngày: ' + (qd.customer?.date || '');
361
+ ws.getCell('A4').value = 'Địa chỉ: ' + (qd.customer?.addr || '');
362
+
363
+ var hr = ws.getRow(6);
364
+ ['STT', 'Tên sản phẩm', 'Mã SP', 'SL', 'Ghi chú'].forEach(function(h, i) {
365
+ var c = hr.getCell(i + 1);
366
+ c.value = h;
367
+ c.font = { bold: true, color: { argb: 'FFFFFFFF' } };
368
+ c.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF003F62' } };
369
+ });
370
+
371
+ var cr = 7, totalQty = 0;
372
+ var imagePromises = [];
373
+
374
+ for (var i = 0; i < (qd.items || []).length; i++) {
375
+ var it = qd.items[i], row = ws.getRow(cr + i);
376
+ row.height = 50;
377
+
378
+ row.getCell(1).value = it.stt || i + 1;
379
+ row.getCell(2).value = it.name || '';
380
+ row.getCell(3).value = it.model || '';
381
+ row.getCell(4).value = it.qty || 1;
382
+ totalQty += Number(it.qty || 1);
383
+ row.getCell(5).value = it.note || '';
384
+
385
+ // ADD IMAGE (column 2 = B)
386
+ if (it.image) {
387
+ imagePromises.push(
388
+ fetchImageAsBase64(it.image).then(function(base64) {
389
+ if (base64) {
390
+ ws.addImage({
391
+ source: base64,
392
+ range: {
393
+ tl: { col: 1, row: cr},
394
+ br: { col: 2, row: cr + 1 }
395
+ }
396
+ });
397
+ }
398
+ })
399
+ );
400
+ }
401
+ }
402
+
403
+ await Promise.all(imagePromises);
404
+
405
+ var totalRowNum = cr + (qd.items || []).length;
406
+ ws.mergeCells(totalRowNum, 1, totalRowNum, 3);
407
+ ws.getCell('A' + totalRowNum).value = 'TỔNG SỐ LƯỢNG';
408
+ ws.getCell('A' + totalRowNum).font = { bold: true };
409
+ ws.getCell('D' + totalRowNum).value = totalQty;
410
+ ws.getCell('D' + totalRowNum).font = { bold: true };
411
+
412
+ wb.calcProperties.fullCalcOnLoad = true;
413
+
414
+ var buf = await wb.xlsx.writeBuffer();
415
+ downloadBlob(new Blob([buf], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }), 'GH-' + code + '.xlsx');
416
+ }
417
+
418
+ // ========== PATCH EXPORT FUNCTIONS ==========
419
+ function patchExportFunctions() {
420
+ var origExportExcel = window.exportExcel;
421
+ window.exportExcel = async function() {
422
+ var btn = document.activeElement;
423
+ if (btn && btn.dataset.vaiExporting === '1') return;
424
+ if (btn) setExportButtonState(btn, true);
425
+
426
+ try {
427
+ var qd = getQuoteData();
428
+ var code = generateOrderCode(qd.customer?.name || '');
429
+ await exportQuoteExcel(qd, code);
430
+ if (typeof showToast === 'function') showToast('✅ Excel báo giá (có hình) tải thành công!');
431
+ } catch (e) {
432
+ console.error('exportExcel error:', e);
433
+ if (typeof showToast === 'function') showToast('❌ Lỗi: ' + e.message);
434
+ } finally {
435
+ if (btn) setTimeout(function() { setExportButtonState(btn, false); }, 500);
436
+ }
437
+ };
438
+
439
+ var origExportDeliveryExcel = window.exportDeliveryExcel;
440
+ window.exportDeliveryExcel = async function(order, opt) {
441
+ var btn = document.activeElement;
442
+ if (btn && btn.dataset.vaiExporting === '1') return;
443
+ if (btn) setExportButtonState(btn, true);
444
+
445
+ try {
446
+ var qd = order && order.items ? {
447
+ customer: {
448
+ name: order.customer || '',
449
+ phone: order.phone || '',
450
+ email: order.email || '',
451
+ addr: order.addr || '',
452
+ date: order.date || ''
453
+ },
454
+ items: (order.items || []).map(function(it, i) {
455
+ return {
456
+ stt: i + 1,
457
+ image: it.image || it.img || '',
458
+ name: it.name || '',
459
+ model: it.model || '',
460
+ qty: it.qty || 1,
461
+ price: it.price || 0,
462
+ discPrice: it.discPrice || it.price || 0,
463
+ total: it.total || 0,
464
+ note: it.note || '',
465
+ specs: it.specs || ''
466
+ };
467
+ }),
468
+ grandTotal: order.grandTotal || 0
469
+ } : getQuoteData();
470
+
471
+ var code = (order && order.code) ? order.code : generateOrderCode(qd.customer?.name || '');
472
+ await exportDeliveryExcel(qd, code);
473
+ if (typeof showToast === 'function') showToast('✅ Excel giao hàng (có hình) tải thành công!');
474
+ } catch (e) {
475
+ console.error('exportDeliveryExcel error:', e);
476
+ if (typeof showToast === 'function') showToast('❌ Lỗi: ' + e.message);
477
+ } finally {
478
+ if (btn) setTimeout(function() { setExportButtonState(btn, false); }, 500);
479
+ }
480
+ };
481
+ }
482
+
483
+ // ========== CLICK HANDLERS ==========
484
+ function handleClickProtection(e) {
485
+ var btn = e.target.closest('button, a');
486
+ if (!btn) return;
487
+
488
+ var txt = (btn.textContent || '').toLowerCase();
489
+
490
+ if (txt.includes('excel') && !txt.includes('giao hàng') && !txt.includes('gh')) {
491
+ e.preventDefault();
492
+ e.stopPropagation();
493
+ if (btn.dataset.vaiExporting === '1') return;
494
+ setExportButtonState(btn, true);
495
+ window.exportExcel().finally(function() { setExportButtonState(btn, false); });
496
+ return false;
497
+ }
498
+
499
+ if ((txt.includes('gh') || txt.includes('giao')) && txt.includes('excel')) {
500
+ e.preventDefault();
501
+ e.stopPropagation();
502
+ if (btn.dataset.vaiExporting === '1') return;
503
+ setExportButtonState(btn, true);
504
+ window.exportDeliveryExcel().finally(function() { setExportButtonState(btn, false); });
505
+ return false;
506
+ }
507
+ }
508
+
509
+ // ========== INIT ==========
510
+ function init() {
511
+ patchExportFunctions();
512
+ document.removeEventListener('click', handleClickProtection);
513
+ document.addEventListener('click', handleClickProtection, true);
514
+ console.log('[VAI Excel Images v2] Loaded');
515
+ }
516
+
517
+ if (document.readyState === 'loading') {
518
+ document.addEventListener('DOMContentLoaded', init);
519
+ } else {
520
+ init();
521
+ }
522
+
523
+ setTimeout(init, 2000);
524
+ setTimeout(init, 5000);
525
+
526
+ })();