Upload qr-payment-v1038.js
Browse files- qr-payment-v1038.js +140 -0
qr-payment-v1038.js
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* V.AI STUDIO — QR Payment / Quote Data v1038
|
| 2 |
+
* FIX TRIỆT ĐỐI: Multi-download Excel - removed URL.revokeObjectURL timeout
|
| 3 |
+
* Thay thế v1037 - xóa 2 dòng setTimeout revoke URL gây lỗi tải 2 lần
|
| 4 |
+
*/
|
| 5 |
+
(function(){'use strict';var excelBlobRegistry=[],isUnloading=!1;
|
| 6 |
+
|
| 7 |
+
// Cleanup khi tab đóng
|
| 8 |
+
function cleanupBlobs(){isUnloading=!0,excelBlobRegistry.forEach(function(e){e.url&&URL.revokeObjectURL(e.url),e.revoked=!0}),excelBlobRegistry=[];}
|
| 9 |
+
window.addEventListener('pagehide',cleanupBlobs);
|
| 10 |
+
window.addEventListener('beforeunload',cleanupBlobs);
|
| 11 |
+
window.addEventListener('unload',cleanupBlobs);
|
| 12 |
+
|
| 13 |
+
// Patch URL.revokeObjectURL - không revoke blob URLs ngay
|
| 14 |
+
(function(){var e=URL.revokeObjectURL;URL.revokeObjectURL=function(t){if(!isUnloading&&t&&t.startsWith('blob:')){var n=excelBlobRegistry.find(function(e){return e.url===t});n||excelBlobRegistry.push({url:t,revoked:!1,created:Date.now()});return;}e.call(this,t);})();
|
| 15 |
+
|
| 16 |
+
var BANK_ID='vib',BANK_ACCOUNT='918258385',BANK_NAME='TRAN QUOC VUONG',BANK_NAME_VN='Trần Quốc Vương';
|
| 17 |
+
function stripDiacritics(s){return s.normalize('NFD').replace(/[\u0300-\u036f]/g,'').replace(/[Đđ]/g,'D');}
|
| 18 |
+
function generateOrderCode(name){var now=new Date(),dd=String(now.getDate()).padStart(2,'0'),mm=String(now.getMonth()+1).padStart(2,'0'),yy=String(now.getFullYear()).slice(-2),ini='';if(name&&name.trim()){name.trim().split(/\s+/).forEach(function(w){if(w){var ch=stripDiacritics(w.charAt(0)).toUpperCase();if(/[A-Z]/.test(ch))ini+=ch;}});}return 'VAS'+(ini||'X')+dd+mm+yy;}
|
| 19 |
+
function getCustomerName(){var sels=['#quoteName','#quoteCustomerName','#checkoutName','.quote-field input:first-of-type'];for(var i=0;i<sels.length;i++){var el=document.querySelector(sels[i]);if(el&&el.value&&el.value.trim().length>1)return el.value.trim();}return '';}
|
| 20 |
+
function getEffectiveOrderCode(){var n=getCustomerName();if(n)return generateOrderCode(n);var h=window.location.hash;if(h&&h.length>1){var c=h.substring(1);if(/^VAS[A-Z0-9]{3,}$/.test(c))return c;}return generateOrderCode('');}
|
| 21 |
+
function getQRUrl(a,c){return'https://img.vietqr.io/image/'+BANK_ID+'-'+BANK_ACCOUNT+'-compact2.png?amount='+(Math.round(a)||0)+'&addInfo='+encodeURIComponent(c||'VAISTUDIO')+'&accountName='+encodeURIComponent(BANK_NAME);}
|
| 22 |
+
function fmt(n){if(!n||isNaN(n))return'0đ';return Number(n).toLocaleString('vi-VN')+'đ';}
|
| 23 |
+
function compactKey(s){return stripDiacritics(String(s||'')).toLowerCase().replace(/[^a-z0-9]/g,'');}
|
| 24 |
+
function itemKeys(it){var arr=[];['model','sku','code','ma','name'].forEach(function(k){if(it&&it[k])arr.push(compactKey(it[k]));});if(it&&it.name){String(it.name).split('|').forEach(function(x){arr.push(compactKey(x));});}return arr.filter(function(x){return x&&x.length>=3;});}
|
| 25 |
+
function matchItemDiscount(it,itemDiscounts){itemDiscounts=itemDiscounts||{};var keys=itemKeys(it);for(var i=0;i<keys.length;i++){var k=keys[i];if(itemDiscounts[k])return itemDiscounts[k];}for(var code in itemDiscounts){for(var j=0;j<keys.length;j++){var kk=keys[j];if(code.length>=3&&kk.length>=3&&(kk.indexOf(code)!==-1||code.indexOf(kk)!==-1))return itemDiscounts[code];}}return 0;}
|
| 26 |
+
function parseItemDiscountLine(line,map){var lo=stripDiacritics(String(line||'')).toLowerCase();var re1=/\b([a-z]{1,8}[a-z0-9._\-\/]{1,30}\d[a-z0-9._\-\/]*)\\b\s*(?:[:=\-]|\s+)?\s*(?:ck|chiet\s*khau|giam|discount)\s*([\d.,]+)\s*%?/gi;var re2=/(?:ck|chiet\s*khau|giam|discount)\s*\b([a-z]{1,8}[a-z0-9._\-\/]{1,30}\d[a-z0-9._\-\/]*)\\b\s*([\d.,]+)\s*%?/gi;var m;while((m=re1.exec(lo))!==null){var v=parseFloat(m[2].replace(/\./g,'').replace(',','.'));if(v>0&&v<=100)map[compactKey(m[1])]=v;}while((m=re2.exec(lo))!==null){var v2=parseFloat(m[2].replace(/\./g,'').replace(',','.'));if(v2>0&&v<=100)map[compactKey(m[1])]=v2;}}
|
| 27 |
+
function applyPromptDiscounts(qd,parsed){if(!qd||!qd.items)return qd;var productTotal=0;var itemDiscounts=(parsed&&parsed.itemDiscounts)||{};var globalPct=Number((parsed&&parsed.discountPercent)||0);qd.items.forEach(function(it){var base=Number(it.price||0),qty=Number(it.qty||1);var pct=matchItemDiscount(it,itemDiscounts);if(pct>0){it.discPrice=Math.round(base*(1-pct/100));it.discountPercent=pct;}else if(globalPct>0&&globalPct<=100){it.discPrice=Math.round(base*(1-globalPct/100));it.discountPercent=globalPct;}else if(!it.discPrice){it.discPrice=base;}it.total=Number(it.discPrice||base)*qty;productTotal+=Number(it.total||0);});qd.grandTotal=productTotal;return qd;}
|
| 28 |
+
function parsePrompt(text){var fees=[],notes=[],discount=null,deposit=0,discountPercent=0,itemDiscounts={};if(!text)return{fees:fees,notes:notes,discount:discount,deposit:deposit,discountPercent:discountPercent,itemDiscounts:itemDiscounts};text.split(/[,;\n]+/).forEach(function(line){line=line.trim();if(!line)return;parseItemDiscountLine(line,itemDiscounts);if(Object.keys(itemDiscounts).length&&line.match(/\b[A-Za-z]{1,8}[A-Za-z0-9._\-\/]{1,30}\d[A-Za-z0-9._\-\/]*\b/i)&&line.match(/\b(ck|chiết khấu|chiet khau|giảm|giam|discount)\b/i))return;if(line.match(/^(ck|chiết khấu|chiet khau|giảm|giam|discount)/i)){discount=line;var ckm=line.match(/([\d.,]+)\s*(%)?/);if(ckm){var v=parseFloat(ckm[1].replace(/\./g,'').replace(',','.'));if(v>0&&v<=100)discountPercent=v;}}return;if(line.match(/cọc|coc|deposit/i)){var dm=line.match(/([\d.,]+)\s*(k|K|nghìn|nghin|triệu|tr|đ|d|vnd)?/);if(dm){var da=parseFloat(dm[1].replace(/\./g,'').replace(',','.'));var du=(dm[2]||'').toLowerCase();if(du==='k'||du==='nghìn'||du==='nghin')da*=1000;if(du==='triệu'||du==='tr')da*=1000000;deposit=da;}}return;var m=line.match(/([\d.,]+)\s*(k|K|nghìn|nghin|triệu|tr|đ|d|vnd)?/);if(m){var amt=parseFloat(m[1].replace(/\./g,'').replace(',','.'));var u=(m[2]||'').toLowerCase();if(u==='k'||u==='nghìn'||u==='nghin')amt*=1000;if(u==='triệu'||u==='tr')amt*=1000000;if(amt<=0)return;var lb=line.replace(m[0],'').trim();if(lb.match(/giao|ship|vận chuyển|delivery/i))lb='Phí giao hàng';else if(lb.match(/lắp|lap|install/i))lb='Phí lắp đặt';else if(lb.match(/bốc|boc|xếp|xep|vác/i))lb='Phí bốc xếp';else if(!lb||lb.length<2)lb='Phụ phí';fees.push({label:lb,amount:amt});}else{notes.push(line);}});return{fees:fees,notes:notes,discount:discount,deposit:deposit,discountPercent:discountPercent,itemDiscounts:itemDiscounts};}
|
| 29 |
+
|
| 30 |
+
var _lastPromptText='';
|
| 31 |
+
function getPromptText(){var direct=document.getElementById('qcAiPrompt');if(direct){var dv=(direct.value||'').trim();if(dv&&dv.toUpperCase().replace(/[\s.]/g,'')!=='VAISTUDIO'){_lastPromptText=dv;return dv;}}var inputs=document.querySelectorAll('input,textarea');for(var j=0;j<inputs.length;j++){var ph=(inputs[j].placeholder||'').toLowerCase();if(ph.includes('yêu cầu')||ph.includes('chiết khấu')||ph.includes('yeu cau')||ph.includes('chiet khau')||ph.includes('ck')||ph.includes('giao hàng')){var val=(inputs[j].value||'').trim();if(!val||val.toUpperCase().replace(/[\s.]/g,'')==='VAISTUDIO')continue;_lastPromptText=val;return val;}}return _lastPromptText;}
|
| 32 |
+
|
| 33 |
+
function getData(){var qd=window._origGetQuoteData?window._origGetQuoteData():getQuoteData();var parsed=parsePrompt(getPromptText());qd=applyPromptDiscounts(qd,parsed);var surcharge=0;parsed.fees.forEach(function(f){surcharge+=f.amount;});var grandTotal=(qd.grandTotal||0)+surcharge;var remaining=grandTotal-parsed.deposit;return{qd:qd,fees:parsed.fees,notes:parsed.notes,discount:parsed.discount,discountPercent:parsed.discountPercent,itemDiscounts:parsed.itemDiscounts||{},deposit:parsed.deposit,productTotal:qd.grandTotal||0,grandTotal:grandTotal,remaining:remaining>0?remaining:0};}
|
| 34 |
+
|
| 35 |
+
function orderToVAIData(order){return{qd:{customer:{name:order.customer||'',phone:order.phone||'',email:order.email||'',addr:order.addr||'',date:order.date||''},items:(order.items||[]).map(function(it,i){return{stt:i+1,image:it.image||'',name:it.name||'',model:it.model||'',specs:it.specs||it.info||'',qty:it.qty||1,price:it.price||it.listPrice||it.discPrice||0,discPrice:it.discPrice||it.price||0,total:it.total||0,note:it.note||''};}),grandTotal:order.grandTotal||0},fees:order.fees||[],deposit:order.deposit||0,remaining:order.remaining||0};}
|
| 36 |
+
|
| 37 |
+
function setExportButtonState(btn,exporting){if(!btn)return;if(exporting){btn.disabled=!0,btn.dataset.vaiExporting='1',btn.dataset.vaiOrigText=btn.innerHTML,btn.innerHTML='<span style="opacity:0.7">⏳</span';}else{btn.disabled=!1,btn.dataset.vaiExporting='0',btn.dataset.vaiOrigText&&(btn.innerHTML=btn.dataset.vaiOrigText);}}
|
| 38 |
+
|
| 39 |
+
function injectToModal(){var modal=document.querySelector('.quote-overlay.open,.quote-modal.open,.quote-overlay[style*="block"],.quote-modal[style*="block"],[class*="quote"][class*="open"],[class*="quote"][style*="block"]');if(!modal)return;var old=modal.querySelector('.vai-extra-section');old&&old.remove();var parsed=parsePrompt(getPromptText());if(!parsed.fees.length&&!parsed.deposit)return;var surcharge=0;parsed.fees.forEach(function(f){surcharge+=f.amount;});var qd=window._origGetQuoteData?window._origGetQuoteData():(typeof getQuoteData==='function'?getQuoteData():{grandTotal:0});var grandTotal=(qd.grandTotal||0)+surcharge;var sec=document.createElement('div');sec.className='vai-extra-section';sec.style.cssText='margin:10px 0;padding:0 16px;font-size:13px';var html='';if(parsed.fees.length){html+='<div style="padding:8px 12px;background:#fffbeb;border-radius:6px;border:1px solid #fde68a;margin-bottom:8px"><div style="font-weight:700;color:#92400e;font-size:12px;margin-bottom:4px">PHỤ PHÍ</div>';parsed.fees.forEach(function(f){html+='<div style="display:flex;justify-content:space-between;padding:2px 0"><span>'+f.label+'</span><span style="font-weight:700">'+fmt(f.amount)+'</span></div>';});html+='</div>';}html+='<div style="padding:8px 12px;background:#003f62;border-radius:6px;display:flex;justify-content:space-between;align-items:center"><span style="color:#fff;font-weight:800">TỔNG CỘNG</span><span style="color:#f0b840;font-weight:900;font-size:16px">'+fmt(grandTotal)+'</span></div>';sec.innerHTML=html;var actions=modal.querySelector('.quote-actions,[class*="actions"],[class*="button"]');if(actions&&actions.parentNode)actions.parentNode.insertBefore(sec,actions);else modal.appendChild(sec);}
|
| 40 |
+
|
| 41 |
+
function toCanvas(html,w){var div=document.createElement('div');div.style.cssText='position:absolute;left:-10000px;top:0;width:'+(w||1000)+'px;background:#fff;padding:28px;font-family:Inter,Arial,DejaVu Sans,sans-serif;z-index:-1;box-sizing:border-box';div.innerHTML=html;document.body.appendChild(div);try{if(document.fonts&&document.fonts.ready)await document.fonts.ready;}catch(e){}var imgs=Array.from(div.querySelectorAll('img'));await Promise.all(imgs.map(function(img){return new Promise(function(res){if(img.complete)return res();img.onload=img.onerror=function(){res();};setTimeout(res,2500);});}));await new Promise(function(r){setTimeout(r,500);});var h=Math.max(div.scrollHeight,div.offsetHeight);var cv=await html2canvas(div,{scale:2,useCORS:true,allowTaint:false,backgroundColor:'#fff',width:w||1000,height:h,windowWidth:w||1000,windowHeight:h,scrollX:0,scrollY:0});div.remove();return cv;}
|
| 42 |
+
|
| 43 |
+
function buildQuoteHTML(d,code,qrUrl){var qd=d.qd;var rows=qd.items.map(function(it){return '<tr style="border-bottom:1px solid #e2e8f0"><td style="padding:6px 4px;text-align:center;font-size:11px">'+(it.stt||'')+'</td><td style="padding:6px 4px"><img src="'+(it.image||'')+'" style="width:50px;height:50px;object-fit:contain;border-radius:4px" onerror="this.style.display=\'none\'"></td><td style="padding:6px 4px;font-size:11px;font-weight:600">'+(it.name||'')+'</td><td style="padding:6px 4px;text-align:center;font-size:10px">'+(it.model||'')+'</td><td style="padding:6px 4px;font-size:9px;color:#64748b">'+(it.specs||'')+'</td><td style="padding:6px 4px;text-align:center">'+(it.qty||'')+'</td><td style="padding:6px 4px;text-align:right;font-size:11px">'+(it.price?fmt(it.price):'')+'</td><td style="padding:6px 4px;text-align:right;font-size:11px">'+(it.discPrice?fmt(it.discPrice):'')+'</td><td style="padding:6px 4px;text-align:right;font-size:11px;font-weight:700">'+(it.total?fmt(it.total):'')+'</td><td style="padding:6px 4px;font-size:9px">'+(it.note||'')+'</td></tr>';}).join('');var feeRows='';if(d.fees&&d.fees.length){d.fees.forEach(function(f){feeRows+='<tr style="background:#fffbeb"><td colspan="8" style="padding:5px 10px;font-size:11px;color:#92400e">⊕ '+f.label+'</td><td style="padding:5px 4px;text-align:right;font-size:11px;font-weight:700">'+fmt(f.amount)+'</td></tr>';});}var totalQty=(qd.items||[]).reduce(function(s,it){return s+Number(it.qty||1);},0);return '<div style="display:flex;align-items:center;gap:10px"><img src="https://huggingface.co/spaces/bep40/V.AISTUDIO/resolve/main/logo/logo_200.png" style="width:40px"></div><div style="text-align:center;margin-bottom:12px"><div style="font-size:20px;font-weight:900;color:#db9815">BẢNG BÁO GIÁ</div></div><div style="display:flex;justify-content:space-between;margin-bottom:12px;font-size:11px"><div><b>Khách hàng:</b> '+(qd.customer.name||'')+'<br><b>SĐT:</b> '+(qd.customer.phone||'')+'</div><div><b>Mã đơn:</b> '+code+'<br><b>Ngày:</b> '+(qd.customer.date||'')+'</div></div><table style="width:100%;border-collapse:collapse"><thead><tr style="background:#003f62;color:#fff"><th>STT</th><th>Hình</th><th>Tên SP</th><th>Mã</th><th>Thông tin</th><th>SL</th><th>Đơn giá</th><th>Giá CK</th><th>Thành tiền</th><th>Ghi chú</th></tr></thead><tbody>'+rows+feeRows+'</tbody></table><div style="padding:10px 14px;background:#003f62"><span style="color:#fff;font-weight:800">TỔNG CỘNG</span><span style="color:#f0b840;font-weight:900;margin-left:10px">'+fmt(d.grandTotal)+'</span></div>'+(d.deposit>0?'<div style="margin-top:6px;padding:6px 12px;background:#f0fdf4;font-size:12px"><span>Cọc: <b>'+fmt(d.deposit)+'</b></span> | <span>Còn lại: <b style="color:#dc2626">'+fmt(d.remaining)+'</b></span></div>':'');}
|
| 44 |
+
|
| 45 |
+
function buildDeliveryHTML(qd,code){var rows=(qd.items||[]).map(function(it,i){return '<tr style="border-bottom:1px solid #e2e8f0"><td style="padding:8px 4px;text-align:center;font-size:12px">'+(it.stt||(i+1))+'</td><td style="padding:8px 4px;font-weight:600;font-size:12px">'+(it.name||'')+'</td><td style="padding:8px 4px;text-align:center;font-size:11px">'+(it.model||'')+'</td><td style="padding:8px 4px;text-align:center;font-weight:700;font-size:13px">'+(it.qty||1)+'</td><td style="padding:8px 4px;font-size:11px">'+(it.note||'')+'</td></tr>';}).join('');return '<div style="text-align:center;margin-bottom:14px"><div style="font-size:20px;font-weight:900;color:#003f62">PHIẾU GIAO HÀNG</div></div><div style="margin-bottom:12px;font-size:11px;line-height:1.6"><b>Khách hàng:</b> '+(qd.customer?qd.customer.name:'')+' | <b>SĐT:</b> '+(qd.customer?qd.customer.phone:'')+'<br><b>Địa chỉ:</b> '+(qd.customer?qd.customer.addr||'':'')+'<br><b>Mã đơn:</b> '+code+' | <b>Ngày:</b> '+(qd.customer?qd.customer.date||'':'')+'</div><table style="width:100%;border-collapse:collapse;font-size:12px"><thead><tr style="background:#003f62;color:#fff"><th style="padding:8px 4px;width:35px">STT</th><th style="padding:8px 4px;text-align:left">Tên sản phẩm</th><th style="padding:8px 4px;width:90px">Mã SP</th><th style="padding:8px 4px;width:40px">SL</th><th style="padding:8px 4px;text-align:left;width:120px">Ghi chú</th></tr></thead><tbody>'+rows+'</tbody></table><div style="margin-top:60px;display:flex;justify-content:space-around;font-size:12px"><div style="text-align:center"><b>Bên giao</b><br>(Ký, họ tên)<div style="margin-top:30px">_______________</div></div><div style="text-align:center"><b>Bên nhận</b><br>(Ký, họ tên)<div style="margin-top:30px">_______________</div></div></div>';}
|
| 46 |
+
|
| 47 |
+
function doOverride(){if(typeof getQuoteData!=='function'||typeof html2canvas!=='function')return false;window._origGetQuoteData=getQuoteData;window.shareQuoteImage=async function(){var d=getData(),code=getEffectiveOrderCode(),qr=getQRUrl(d.deposit>0?d.remaining:d.grandTotal,code);try{var cv=await toCanvas(buildQuoteHTML(d,code,qr),1000);var blob=await new Promise(function(r){cv.toBlob(r,'image/png');});var f=new File([blob],code+'.png',{type:'image/png'});if(navigator.share&&navigator.canShare&&navigator.canShare({files:[f]})){await navigator.share({title:code,files:[f]});}else{var url=URL.createObjectURL(blob);var p=document.createElement('div');p.style.cssText='position:fixed;inset:0;background:rgba(0,0,0,.7);z-index:999';p.innerHTML='<div style="background:#fff;border-radius:16px;max-width:90vw;max-height:85vh"><img src="'+url+'" style="max-width:100%"><a href="'+url+'" download="'+code+'.png" style="padding:10px 20px;background:#003f62;color:#fff;border-radius:8px">⬇ Tải</a></div>';document.body.appendChild(p);}}catch(e){console.error(e);}};window.exportPDF=async function(){var d=getData(),code=getEffectiveOrderCode(),qr=getQRUrl(d.deposit>0?d.remaining:d.grandTotal,code);try{await _doExportPDF(d,code);}catch(e){console.error(e);alert('Không xuất được PDF: '+(e&&e.message?e.message:e));}};window.exportDeliveryExcel=async function(order,opt){if(typeof ExcelJS==='undefined')return;var qd=order&&order.items?orderToVAIData(order).qd:window._origGetQuoteData();var code=order&&order.code?order.code:getEffectiveOrderCode();var activeBtn=document.activeElement;if(activeBtn&&activeBtn.dataset.vaiExporting==='1')return;if(activeBtn)setExportButtonState(activeBtn,!0);try{await _doExportDeliveryExcel(qd,code);}finally{if(activeBtn)setExportButtonState(activeBtn,!1);}};window.exportDeliveryPDF=async function(order,opt){var qd=order&&order.items?orderToVAIData(order).qd:window._origGetQuoteData();var code=order&&order.code?order.code:getEffectiveOrderCode();var activeBtn=document.activeElement;if(activeBtn&&activeBtn.dataset.vaiExporting==='1')return;if(activeBtn)setExportButtonState(activeBtn,!0);try{await _doExportDeliveryPDF(qd,code);}finally{if(activeBtn)setExportButtonState(activeBtn,!1);}};window.exportExcel=async function(){if(typeof ExcelJS==='undefined')return;var d=getData(),qd=d.qd,code=getEffectiveOrderCode(),qr=getQRUrl(d.deposit>0?d.remaining:d.grandTotal,code);await _doExportExcel(d,qd,code,qr);};window.getQuoteData=function(){var qd=window._origGetQuoteData.apply(this,arguments);if(qd.customer)qd.customer.orderCode=getEffectiveOrderCode();return qd;};console.log('✅ QR Payment v1038 — Multi-download Excel fixed');return true;}
|
| 48 |
+
|
| 49 |
+
async function _doExportPDF(d,code){var qr=getQRUrl(d.deposit>0?d.remaining:d.grandTotal,code);var cv=await toCanvas(buildQuoteHTML(d,code,qr),1000);var img=cv.toDataURL('image/jpeg',0.92);var pageW=595,pageH=842,imgW=pageW,imgH=cv.height*imgW/cv.width;var pdf=new jspdf.jsPDF({orientation:'p',unit:'pt',format:'a4'});if(imgH<=pageH){pdf.addImage(img,'JPEG',0,0,imgW,imgH);}else{var y=0,rem=imgH,page=0;while(rem>0){if(page>0)pdf.addPage();pdf.addImage(img,'JPEG',0,-y,imgW,imgH);y+=pageH;rem-=pageH;page++;}}pdf.save(code+'.pdf');}
|
| 50 |
+
|
| 51 |
+
async function _doExportDeliveryPDF(qd,code){var cv=await toCanvas(buildDeliveryHTML({qd:qd},code),700);var img=cv.toDataURL('image/png');var pdf=new jspdf.jsPDF({orientation:'p',unit:'pt',format:'a4'});var margin=25,usableW=595-margin*2,ratio=cv.height/cv.width,imgH=usableW*ratio;if(imgH>842-margin*2){imgH=842-margin*2;usableW=imgH/ratio;}pdf.addImage(img,'PNG',margin,margin,usableW,imgH);pdf.save('GH-'+code+'.pdf');}
|
| 52 |
+
|
| 53 |
+
async function _doExportExcel(d,qd,code,qrUrl){
|
| 54 |
+
var MONEY_FMT='#,##0"đ"',NUM_FMT='#,##0';var WHITE={argb:'FFFFFFFF'};var WB={top:{style:'thin',color:WHITE},bottom:{style:'thin',color:WHITE},left:{style:'thin',color:WHITE},right:{style:'thin',color:WHITE}};
|
| 55 |
+
var wb=new ExcelJS.Workbook(),ws=wb.addWorksheet('Báo giá');
|
| 56 |
+
ws.views=[{showGridLines:false}];ws.columns=[{width:5},{width:11},{width:28},{width:13},{width:20},{width:6},{width:13},{width:13},{width:15},{width:14}];
|
| 57 |
+
ws.mergeCells('A3:J3');ws.getCell('A3').value='BẢNG BÁO GIÁ';ws.getCell('A3').font={bold:true,size:18,color:{argb:'FFDB9815'}};ws.getCell('A3').alignment={horizontal:'center'};
|
| 58 |
+
ws.getCell('A5').value='Khách hàng:';ws.mergeCells('B5:E5');ws.getCell('B5').value=qd.customer?qd.customer.name:'';
|
| 59 |
+
ws.getCell('H5').value='Mã đơn:';ws.mergeCells('I5:J5');ws.getCell('I5').value=code;
|
| 60 |
+
ws.getCell('A6').value='SĐT:';ws.mergeCells('B6:E6');ws.getCell('B6').value=qd.customer?qd.customer.phone:'';
|
| 61 |
+
ws.getCell('H6').value='Ngày:';ws.mergeCells('I6:J6');ws.getCell('I6').value=qd.customer?qd.customer.date:'';
|
| 62 |
+
ws.getCell('A7').value='Email:';ws.mergeCells('B7:E7');ws.getCell('B7').value=qd.customer?qd.customer.email:'';
|
| 63 |
+
ws.getCell('A8').value='Địa chỉ:';ws.mergeCells('B8:J8');ws.getCell('B8').value=qd.customer?qd.customer.addr:'';
|
| 64 |
+
var hr=ws.getRow(10);['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){var c=hr.getCell(i+1);c.value=h;c.font={bold:true,color:{argb:'FFFFFFFF'}};c.fill={type:'pattern',pattern:'solid',fgColor:{argb:'FF003F62'}};});
|
| 65 |
+
var cr=11,firstItemRow=cr,ckPct=Number((d.discountPercent||0));
|
| 66 |
+
for(var i=0;i<qd.items.length;i++){
|
| 67 |
+
var it=qd.items[i],row=ws.getRow(cr);row.height=50;
|
| 68 |
+
var bgColor=i%2===0?'FFF8FAFC':'FFFFFFFF';
|
| 69 |
+
var RB={top:{style:'thin',color:{argb:bgColor}},bottom:{style:'thin',color:{argb:bgColor}},left:{style:'thin',color:{argb:bgColor}},right:{style:'thin',color:{argb:bgColor}}};
|
| 70 |
+
row.getCell(1).value=it.stt||i+1;row.getCell(3).value=it.name||'';
|
| 71 |
+
row.getCell(3).font={bold:true,size:9};row.getCell(4).value=it.model||'';
|
| 72 |
+
row.getCell(5).value=it.specs||'';row.getCell(5).font={size:8,color:{argb:'FF64748B'}};
|
| 73 |
+
row.getCell(6).value=Number(it.qty||1);row.getCell(6).numFmt=NUM_FMT;
|
| 74 |
+
row.getCell(7).value=Number(it.price||0);row.getCell(7).numFmt=MONEY_FMT;
|
| 75 |
+
row.getCell(8).value=Number(it.discPrice||it.price||0);row.getCell(8).numFmt=MONEY_FMT;
|
| 76 |
+
if((it.discPrice||0)&&(it.price||0)&&it.discPrice<it.price)row.getCell(8).font={bold:true,color:{argb:'FFDC3545'}};
|
| 77 |
+
row.getCell(9).value=Number(it.total||0);row.getCell(9).numFmt=MONEY_FMT;row.getCell(9).font={bold:true};
|
| 78 |
+
row.getCell(10).value=it.note||'';
|
| 79 |
+
for(var ci=1;ci<=10;ci++){row.getCell(ci).fill={type:'pattern',pattern:'solid',fgColor:{argb:bgColor}};row.getCell(ci).border=RB;}
|
| 80 |
+
cr++;
|
| 81 |
+
}
|
| 82 |
+
ws.getRow(cr).height=28;
|
| 83 |
+
ws.mergeCells(cr,1,cr,5);ws.getCell('A'+cr).value='TỔNG CỘNG';ws.getCell('A'+cr).font={bold:true,size:13,color:{argb:'FFFFFFFF'}};ws.getCell('A'+cr).fill={type:'pattern',pattern:'solid',fgColor:{argb:'FF003F62'}};
|
| 84 |
+
ws.getCell('E'+cr).value={formula:'SUM(I'+firstItemRow+':I'+(cr-1)+')',result:Number(d.grandTotal||0)};ws.getCell('E'+cr).numFmt=MONEY_FMT;ws.getCell('E'+cr).font={bold:true,size:14,color:{argb:'FFF0B840'}};
|
| 85 |
+
wb.calcProperties.fullCalcOnLoad=true;
|
| 86 |
+
var buf=await wb.xlsx.writeBuffer();
|
| 87 |
+
var blob=new Blob([buf],{type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
|
| 88 |
+
var url=URL.createObjectURL(blob);
|
| 89 |
+
var a=document.createElement('a');
|
| 90 |
+
a.href=url;a.download=code+'.xlsx';
|
| 91 |
+
document.body.appendChild(a);a.click();
|
| 92 |
+
document.body.removeChild(a);
|
| 93 |
+
// FIX v1038: KHÔNG REVOKE URL - để blob tự giải phóng khi unload
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
async function _doExportDeliveryExcel(qd,code){
|
| 97 |
+
var WHITE={argb:'FFFFFFFF'};var WB={top:{style:'thin',color:WHITE},bottom:{style:'thin',color:WHITE},left:{style:'thin',color:WHITE},right:{style:'thin',color:WHITE}};
|
| 98 |
+
var wb=new ExcelJS.Workbook(),ws=wb.addWorksheet('Giao hàng');
|
| 99 |
+
ws.views=[{showGridLines:false}];ws.columns=[{width:5},{width:34},{width:14},{width:8},{width:20}];
|
| 100 |
+
ws.mergeCells('A1:E1');ws.getCell('A1').value='PHIẾU GIAO HÀNG';ws.getCell('A1').font={bold:true,size:16,color:{argb:'FF003F62'}};ws.getCell('A1').alignment={horizontal:'center'};
|
| 101 |
+
ws.getCell('A2').value='KH: '+(qd.customer?qd.customer.name:'');
|
| 102 |
+
ws.getCell('D2').value='Mã: '+code;
|
| 103 |
+
ws.getCell('A3').value='SĐT: '+(qd.customer?qd.customer.phone:'');
|
| 104 |
+
ws.getCell('D3').value='Ngày: '+(qd.customer?qd.customer.date||'':'');
|
| 105 |
+
ws.getCell('A4').value='Địa chỉ: '+(qd.customer?qd.customer.addr||'':'');
|
| 106 |
+
var hr=ws.getRow(6);['STT','Tên sản phẩm','Mã SP','SL','Ghi chú'].forEach(function(h,i){var c=hr.getCell(i+1);c.value=h;c.font={bold:true,color:{argb:'FFFFFFFF'}};c.fill={type:'pattern',pattern:'solid',fgColor:{argb:'FF003F62'}};});
|
| 107 |
+
var cr=7,items=qd.items||[],totalQty=0;
|
| 108 |
+
for(var i=0;i<items.length;i++){
|
| 109 |
+
var it=items[i],row=ws.getRow(cr);row.height=20;
|
| 110 |
+
row.getCell(1).value=it.stt||i+1;row.getCell(2).value=it.name||'';
|
| 111 |
+
row.getCell(3).value=it.model||'';row.getCell(4).value=it.qty||1;
|
| 112 |
+
row.getCell(5).value=it.note||'';
|
| 113 |
+
totalQty+=Number(it.qty||1);cr++;
|
| 114 |
+
}
|
| 115 |
+
var totalQtyRow=cr;ws.mergeCells(totalQtyRow,1,totalQtyRow,3);ws.getCell('A'+totalQtyRow).value='TỔNG CỘNG SỐ LƯỢNG';ws.getCell('D'+totalQtyRow).value=totalQty;
|
| 116 |
+
var buf=await wb.xlsx.writeBuffer();
|
| 117 |
+
var blob=new Blob([buf],{type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
|
| 118 |
+
var url=URL.createObjectURL(blob);
|
| 119 |
+
var a=document.createElement('a');
|
| 120 |
+
a.href=url;a.download='GH-'+code+'.xlsx';
|
| 121 |
+
document.body.appendChild(a);a.click();
|
| 122 |
+
document.body.removeChild(a);
|
| 123 |
+
// FIX v1038: KHÔNG REVOKE URL - để blob tự giải phóng khi unload
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
var att=0,t=setInterval(function(){if(doOverride()||att>120)clearInterval(t);att++;},500);
|
| 127 |
+
|
| 128 |
+
document.addEventListener('click',function(e){
|
| 129 |
+
var btn=e.target.closest&&e.target.closest('button,a');if(!btn)return;
|
| 130 |
+
var txt=(btn.textContent||'').toLowerCase();if(!window._origGetQuoteData)return;
|
| 131 |
+
if(txt.includes('excel')&&txt.includes('xuất')){e.preventDefault();e.stopPropagation();if(btn.dataset.vaiExporting==='1')return;setExportButtonState(btn,!0);window.exportExcel().finally(function(){setExportButtonState(btn,!1);});return!1;}
|
| 132 |
+
if((txt.includes('pdf')&&txt.includes('xuất'))||(txt.includes('pdf')&&!txt.includes('giao hàng'))){e.preventDefault();e.stopPropagation();if(btn.dataset.vaiExporting==='1')return;setExportButtonState(btn,!0);window.exportPDF().finally(function(){setExportButtonState(btn,!1);});return!1;}
|
| 133 |
+
if(txt.includes('chia sẻ')&&txt.includes('ảnh')){e.preventDefault();e.stopPropagation();if(btn.dataset.vaiExporting==='1')return;setExportButtonState(btn,!0);window.shareQuoteImage().finally(function(){setExportButtonState(btn,!1);});return!1;}
|
| 134 |
+
if((txt.includes('gh')||txt.includes('giao hàng'))&&txt.includes('excel')){e.preventDefault();e.stopPropagation();if(btn.dataset.vaiExporting==='1')return;setExportButtonState(btn,!0);window.exportDeliveryExcel().finally(function(){setExportButtonState(btn,!1);});return!1;}
|
| 135 |
+
if((txt.includes('gh')||txt.includes('giao hàng'))&&txt.includes('pdf')){e.preventDefault();e.stopPropagation();if(btn.dataset.vaiExporting==='1')return;setExportButtonState(btn,!0);window.exportDeliveryPDF().finally(function(){setExportButtonState(btn,!1);});return!1;}
|
| 136 |
+
},!0);
|
| 137 |
+
|
| 138 |
+
window.VAI_QR={getEffectiveOrderCode:getEffectiveOrderCode,getQRUrl:getQRUrl,generateOrderCode:generateOrderCode,parsePrompt:parsePrompt,getPromptText:getPromptText,injectToModal:injectToModal,getData:getData,buildQuoteHTML:buildQuoteHTML,buildDeliveryHTML:buildDeliveryHTML,toCanvas:toCanvas,exportPDF:_doExportPDF,exportExcel:_doExportExcel,exportDeliveryPDF:_doExportDeliveryPDF,exportDeliveryExcel:_doExportDeliveryExcel,fmt:fmt,compactKey:compactKey,matchItemDiscount:matchItemDiscount,parseItemDiscountLine:parseItemDiscountLine,applyPromptDiscounts:applyPromptDiscounts,setExportButtonState:setExportButtonState,orderToVAIData:orderToVAIData};
|
| 139 |
+
console.log('[VAI QR v1038] Loaded - Multi-download Excel fix');
|
| 140 |
+
})();
|