bep40 commited on
Commit
5640d7d
·
verified ·
1 Parent(s): ed0f682

Upload vai-excel-fix.js

Browse files
Files changed (1) hide show
  1. vai-excel-fix.js +175 -0
vai-excel-fix.js ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * V.AI STUDIO — Excel & PDF Export Ultimate Fix
3
+ * ===========================================
4
+ * Vấn đề:
5
+ * 1. exportExcel (modal Báo giá) - URL revoke sau 60s gây lỗi tải
6
+ * 2. exportDeliveryExcel (modal Đơn hàng) - dùng CSV thay vì .xlsx thật
7
+ *
8
+ * Giải pháp:
9
+ * - Delay revoke URL lâu hơn (5 phút thay vì 60s)
10
+ * - Tạo filename unique để tải nhiều lần
11
+ * - Sử dụng ExcelJS cho GH Excel để xuất file .xlsx thật
12
+ * - Thêm retry khi ExcelJS chưa load xong
13
+ */
14
+ (function() {
15
+ 'use strict';
16
+
17
+ // Lưu trữ URL blob đã tạo để tải lại nếu cần
18
+ window.__VAI_BLOB_CACHE = window.__VAI_BLOB_CACHE || {};
19
+
20
+ // Tạo tên file unique
21
+ function getUniqueFilename(prefix, ext) {
22
+ const now = new Date();
23
+ const ts = now.getTime();
24
+ const date = now.toLocaleDateString('vi-VN').replace(/\//g, '-');
25
+ return `${prefix}_${date}_${ts}.${ext}`;
26
+ }
27
+
28
+ // Hàm download blob - delay revoke 5 phút
29
+ function downloadBlob(blob, filename, cacheKey) {
30
+ const url = URL.createObjectURL(blob);
31
+ const a = document.createElement('a');
32
+ a.href = url;
33
+ a.download = filename;
34
+ a.style.cssText = 'position:fixed;top:-100px;left:-100px;width:1px;height:1px;';
35
+ document.body.appendChild(a);
36
+ a.click();
37
+
38
+ // Cache để tải lại nếu cần
39
+ if (cacheKey) {
40
+ window.__VAI_BLOB_CACHE[cacheKey] = { url, filename, blob };
41
+ }
42
+
43
+ // Xóa URL sau 5 phút (đủ thời gian user tải)
44
+ setTimeout(() => {
45
+ try { URL.revokeObjectURL(url); } catch (e) {}
46
+ }, 300000);
47
+
48
+ document.body.removeChild(a);
49
+ return url;
50
+ }
51
+
52
+ // Hàm chờ ExcelJS sẵn sàng
53
+ async function waitForExcelJS(timeout = 10000) {
54
+ let waited = 0;
55
+ while (typeof ExcelJS === 'undefined' && waited < timeout) {
56
+ await new Promise(r => setTimeout(r, 500));
57
+ waited += 500;
58
+ }
59
+ return typeof ExcelJS !== 'undefined';
60
+ }
61
+
62
+ // ===== FIX: exportExcel (modal Báo giá) =====
63
+ const origExportExcel = window.exportExcel;
64
+ window.exportExcel = async function() {
65
+ // Đảm bảo ExcelJS đã load
66
+ if (!await waitForExcelJS()) {
67
+ if (window.showToast) window.showToast('⚠️ Thư viện Excel chưa tải. Vui lòng chờ 2-3s rồi thử lại.');
68
+ return;
69
+ }
70
+
71
+ // Gọi hàm gốc
72
+ if (origExportExcel) {
73
+ try {
74
+ await origExportExcel.call(this);
75
+ // Toast đã có trong hàm gốc, không cần thêm
76
+ } catch (e) {
77
+ console.error('exportExcel error:', e);
78
+ if (window.showToast) window.showToast('❌ Lỗi: ' + e.message);
79
+ }
80
+ }
81
+ };
82
+
83
+ // ===== FIX: exportDeliveryExcel (modal Đơn hàng) - DÙNG EXCEL .XLSX =====
84
+ window.exportDeliveryExcel = async function() {
85
+ if (!window.cart || window.cart.length === 0) {
86
+ if (window.showToast) window.showToast('⚠️ Giỏ hàng trống!');
87
+ return;
88
+ }
89
+
90
+ // Đảm bảo ExcelJS
91
+ if (!await waitForExcelJS()) {
92
+ if (window.showToast) window.showToast('⚠️ Thư viện Excel chưa tải. Vui lòng chờ...');
93
+ return;
94
+ }
95
+
96
+ try {
97
+ const wb = new ExcelJS.Workbook();
98
+ wb.creator = 'V.AI STUDIO';
99
+ const ws = wb.addWorksheet('Phiếu Giao Hàng');
100
+
101
+ // Tiêu đề
102
+ ws.mergeCells('A1:E1');
103
+ ws.getCell('A1').value = 'PHIẾU GIAO HÀNG V.AI STUDIO';
104
+ ws.getCell('A1').font = { name: 'Arial', size: 14, bold: true, color: { argb: 'FF003F62' } };
105
+ ws.getCell('A1').alignment = { horizontal: 'center', vertical: 'middle' };
106
+ ws.getCell('A1').fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFF0F7FF' } };
107
+
108
+ const today = new Date().toLocaleDateString('vi-VN');
109
+ ws.getCell('A2').value = 'Ngày giao:';
110
+ ws.getCell('B2').value = today;
111
+
112
+ // Header
113
+ ws.getRow(4).values = ['STT', 'Mã SP', 'Tên sản phẩm', 'SL', 'Đơn giá', 'Thành tiền'];
114
+ ws.getRow(4).eachCell(cell => {
115
+ cell.font = { bold: true, color: { argb: 'FFFFFFFF' } };
116
+ cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF003F62' } };
117
+ });
118
+
119
+ let total = 0;
120
+ window.cart.forEach((item, idx) => {
121
+ const p = (window.D && D[item.idx]) ? D[item.idx] : null;
122
+ const name = p ? (p.name || p.n || '') : (item.name || '');
123
+ const model = p ? (p.sku || p.mod || '') : (item.sku || item.model || '');
124
+ const qty = item.qty || 1;
125
+ const price = item.priceNum || item.price || 0;
126
+ const lineTotal = qty * price;
127
+ total += lineTotal;
128
+
129
+ const row = ws.getRow(idx + 5);
130
+ row.values = [idx + 1, model, name.replace(/,/g, ' -'), qty, price, lineTotal];
131
+ row.getCell(5).numFmt = '#,##0"đ"';
132
+ row.getCell(6).numFmt = '#,##0"đ"';
133
+ });
134
+
135
+ // Tổng cộng
136
+ const totalRow = ws.addRow(['', '', '', '', 'TỔNG CỘNG:', total]);
137
+ totalRow.getCell(6).font = { bold: true, color: { argb: 'FF003F62' } };
138
+ totalRow.getCell(6).numFmt = '#,##0"đ"';
139
+
140
+ // Định dạng cột
141
+ ws.getColumn(4).numFmt = '#,##0';
142
+
143
+ const buffer = await wb.xlsx.writeBuffer();
144
+ const blob = new Blob([buffer], {
145
+ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
146
+ });
147
+ downloadBlob(blob, getUniqueFilename('Phieu_giao_hang', 'xlsx'));
148
+
149
+ if (window.showToast) window.showToast('✅ Đã tải file Excel (.xlsx) thành công! Có thể tải lại nhiều lần.');
150
+ } catch (e) {
151
+ console.error('exportDeliveryExcel error:', e);
152
+ if (window.showToast) window.showToast('❌ Lỗi xuất Excel: ' + e.message);
153
+ }
154
+ };
155
+
156
+ // ===== FIX: exportDeliveryPDF =====
157
+ const origExportDeliveryPDF = window.exportDeliveryPDF;
158
+ window.exportDeliveryPDF = async function() {
159
+ if (!window.cart || window.cart.length === 0) {
160
+ if (window.showToast) window.showToast('⚠️ Giỏ hàng trống!');
161
+ return;
162
+ }
163
+
164
+ if (origExportDeliveryPDF) {
165
+ try {
166
+ await origExportDeliveryPDF.call(this);
167
+ } catch (e) {
168
+ console.error('exportDeliveryPDF error:', e);
169
+ if (window.showToast) window.showToast('❌ Lỗi xuất PDF: ' + e.message);
170
+ }
171
+ }
172
+ };
173
+
174
+ console.log('[VAI Excel Fix Ultimate] Loaded - exportExcel & exportDeliveryExcel fixed');
175
+ })();