');w.document.close()}else alert('Trình duyệt chặn cửa sổ xem ảnh. Hãy cho phép mở cửa sổ mới.')} function deletePhoto(i){if(!confirm('Xóa ảnh này khỏi máy?'))return;let m=db.machines.find(x=>x.id===photoMachineId);m.photos.splice(i,1);save();drawPhotos()} function compressPhoto(file){return new Promise((resolve,reject)=>{ if(!file||!file.size)return reject(Error('Tệp ảnh trống hoặc không thể truy cập.')); if(file.size>25*1024*1024)return reject(Error('Ảnh lớn hơn 25 MB. Hãy chọn ảnh khác.')); if(file.type&&!file.type.startsWith('image/'))return reject(Error('Tệp không phải ảnh.')); const reader=new FileReader();let done=false; const timer=setTimeout(()=>fail('Xử lý ảnh quá lâu. Hãy thử ảnh JPG/PNG.'),30000); function finish(v){if(done)return;done=true;clearTimeout(timer);resolve(v)} function fail(v){if(done)return;done=true;clearTimeout(timer);reject(Error(v))} reader.onerror=()=>fail('Không đọc được ảnh từ thiết bị.'); reader.onload=()=>{ const im=new Image(); im.onerror=()=>fail('Không đọc được định dạng ảnh. Hãy dùng JPG hoặc PNG.'); im.onload=()=>{try{ let maxSide=1280,scale=Math.min(1,maxSide/Math.max(im.width,im.height)); let width=Math.max(1,Math.round(im.width*scale)),height=Math.max(1,Math.round(im.height*scale)); let canvas=document.createElement('canvas'),ctx=canvas.getContext('2d'); if(!ctx)throw Error('Trình duyệt không hỗ trợ nén ảnh'); let best='',bestSize=Infinity; // Mục tiêu ~250 KB/ảnh; giữ độ nét tối đa trong giới hạn dung lượng. for(let round=0;round<4;round++){ canvas.width=width;canvas.height=height; ctx.fillStyle='#ffffff';ctx.fillRect(0,0,width,height); ctx.drawImage(im,0,0,width,height); const webpTest=canvas.toDataURL('image/webp',0.8); const format=webpTest.startsWith('data:image/webp;')?'image/webp':'image/jpeg'; for(const quality of [0.8,0.72,0.62,0.52]){ const data=canvas.toDataURL(format,quality); const bytes=Math.round((data.length-data.indexOf(',')-1)*3/4); if(bytesx.id===photoMachineId);if(!m)return;let files=Array.from(e.target.files||[]);m.photos=m.photos||[];if(m.photos.length+files.length>8){alert('Mỗi máy tối đa 8 ảnh.');return}for(let file of files){if(!file.type.startsWith('image/')){alert('Chỉ chọn file ảnh.');continue}try{let photo=await compressPhoto(file);let proposed=JSON.stringify({...db,machines:db.machines.map(x=>x.id===m.id?{...x,photos:[...m.photos,photo]}:x)});if(proposed.length>3800000){alert('Bộ nhớ ảnh gần đầy (giới hạn an toàn ~3,8 MB). Hãy sao lưu trước, rồi cân nhắc giảm số ảnh.');break}m.photos.push(photo);save()}catch(err){alert('Không thêm được ảnh: '+err.message)}}e.target.value='';drawPhotos();toast('Đã lưu ảnh máy. Hãy sao lưu dữ liệu kèm ảnh.')} // Hủy bán và xóa mua theo nguyên tắc đảo bút toán; không xóa khoản tiền đã trả cho thành viên. function auditRecord(action,detail){db.audit.push({id:uid(),date:new Date().toISOString(),action,detail})} function manualAllocationExists(){return db.distributions.some(d=>!d.autoLotId)} function reversalGuard(lid){let alloc=db.distributions.filter(d=>d.autoLotId===lid);if(alloc.some(d=>n(d.paid)>0)){alert('Không thể hủy: lợi nhuận lô này đã được trả cho thành viên. Cần thu hồi/đối chiếu tiền thực tế trước. Không tự hoàn tiền trên sổ.');return false}if(manualAllocationExists()){alert('Có khoản chia lợi nhuận thủ công chưa liên kết rõ với từng lô. Để tránh sai sổ, hãy đối chiếu các khoản này trước khi hủy giao dịch.');return false}return true} function cancelSale(id){if(warrantyRecords().some(r=>r.saleId===id)){alert('Máy đã có lịch sử bảo hành/bảo dưỡng. Hãy đối chiếu các khoản thu chi hậu mãi trước khi hủy giao dịch bán.');return}let sale=db.sales.find(s=>s.id===id);if(!sale)return;let m=db.machines.find(x=>x.id===sale.machineId),lot=db.lots.find(l=>l.id===m?.lotId);if(!lot)return;if(!reversalGuard(lot.id))return;let received=n(sale.received);let msg='HỦY GIAO DỊCH BÁN\n'+m.name+' — '+lot.code+'\nGiá bán: '+money(sale.price)+'\nTiền đã thu: '+money(received)+'\n\nMáy sẽ trở lại kho; doanh thu, công nợ và phân bổ lãi chưa trả của lô sẽ được tính lại.'+(received?'\n\nQUAN TRỌNG: Chỉ xác nhận sau khi đã thực tế hoàn lại '+money(received)+' cho khách.':'')+'\n\nAnh xác nhận hủy?';if(!confirm(msg))return;db.sales=db.sales.filter(s=>s.id!==id);db.distributions=db.distributions.filter(d=>d.autoLotId!==lot.id);auditRecord('Hủy bán',lot.code+' / '+m.name+'; doanh thu '+money(sale.price)+'; tiền thu đã đảo '+money(received));save();nav('sales');toast('Đã hủy bán và tính lại số dư theo sổ')} function deleteLot(id){let lot=db.lots.find(l=>l.id===id);if(!lot)return;let ms=db.machines.filter(m=>m.lotId===id);if(ms.some(m=>saleOf(m.id))){alert('Lô đã có máy bán. Hãy hủy tất cả giao dịch bán của lô trước khi xóa lô mua.');return}if(!reversalGuard(id))return;let expenses=db.cash.filter(c=>c.lotId===id);if(expenses.length){alert('Lô còn khoản thu/chi liên kết. Hãy đối chiếu và xử lý các khoản đó trước khi xóa lô.');return}if(!confirm('XÓA LÔ MUA '+lot.code+'\n'+ms.length+' máy; giá mua '+money(lot.cost)+'\n\nChỉ xác nhận khi khoản tiền mua máy đã được người bán hoàn lại thực tế. Xóa lô sẽ cộng lại giá mua vào tiền mặt theo sổ và xóa ảnh các máy thuộc lô. Anh đã sao lưu dữ liệu chưa?'))return;db.distributions=db.distributions.filter(d=>d.autoLotId!==id);db.machines=db.machines.filter(m=>m.lotId!==id);db.lots=db.lots.filter(l=>l.id!==id);auditRecord('Xóa lô mua',lot.code+'; '+ms.length+' máy; hoàn nguyên tiền mua '+money(lot.cost));save();nav('lots');toast('Đã xóa lô và tính lại số dư theo sổ')} function showAudit(){document.getElementById('overlay').innerHTML=`
`} // ---------- SỬA LÔ / SỬA MÁY: bảo toàn ID, lịch sử và bút toán ----------- const MCC_VERSION='2026-11-13-edit2'; function editMachineRow(machine){ const m=machine||{id:'',name:'',model:'',photos:[]}; const sold=!!m.id&&!!saleOf(m.id); const d=document.createElement('div');d.className='edit-machine-row';d.dataset.mid=m.id||''; d.innerHTML=`
${(m.photos||[]).length} ảnh hiện có ${sold?' • Đã bán':''} ${sold?'':''}
`; d.style.cssText='border:1px solid #d8e3f0;padding:12px;border-radius:12px;margin-bottom:10px;background:#f9fbff'; return d; } function previewEditPhotos(input){ const row=input.closest('.edit-machine-row');if(!row)return; const preview=row.querySelector('.purchase-preview'),files=[...input.files]; if(files.length>8){alert('Tối đa 8 ảnh mới mỗi máy.');input.value='';preview.textContent='';return;} preview.textContent=files.length?files.length+' ảnh mới: '+files.map(f=>f.name).join(', '):''; } function markEditMachineRemoved(b){ const row=b.closest('.edit-machine-row');if(!row)return; if(!confirm('Bỏ máy này khỏi lô? Ảnh của máy sẽ bị xóa khỏi dữ liệu khi lưu.'))return; row.dataset.deleted='yes';row.style.display='none'; row.querySelectorAll('input').forEach(x=>x.disabled=true); } function addEditMachine(){const list=document.getElementById('editMachineList');if(list)list.appendChild(editMachineRow(null))} function openEditLot(id){ const lot=db.lots.find(l=>l.id===id);if(!lot)return alert('Không tìm thấy lô máy.'); form('✏️ Sửa thông tin lô đã mua',`
Chỉnh sửa trực tiếp mà không phải xóa lô. Mã máy, hình ảnh cũ, giao dịch bán, công nợ và sổ quỹ được giữ nguyên.
${field('Mã lô *','code','text',lot.code,'required')}${field('Tên lô *','name','text',lot.name,'required')} ${field('Ngày mua','date','date',lot.date||today(),'required')}${field('Giá mua chung (đ) *','cost','number',String(lot.cost??0),'required')} ${field('Người bán / nguồn hàng','vendor','text',lot.vendor||'')}${field('Ghi chú','note','text',lot.note||'')}

Danh sách máy đã mua

Nếu lô đã kết toán hoặc đã chia lãi, phần mềm sẽ không cho thay đổi giá mua để bảo vệ sổ lợi nhuận. Tên, model và ghi chú vẫn được chỉnh sửa.
`, 'submitEditLot'); const list=document.getElementById('editMachineList');db.machines.filter(m=>m.lotId===lot.id).forEach(m=>list.appendChild(editMachineRow(m))); } async function submitEditLot(ev){ const v=vals(ev),id=v.editLotId,lot=db.lots.find(l=>l.id===id);if(!lot)return alert('Không tìm thấy lô cần sửa.'); const code=(v.code||'').trim(),name=(v.name||'').trim(),cost=n(v.cost),date=v.date; if(!ensure(code&&name&&date,'Nhập đầy đủ mã lô, tên lô và ngày mua.')||!ensure(positive(v.cost),'Giá mua không hợp lệ.')|| !ensure(!db.lots.some(l=>l.id!==id&&String(l.code).trim().toLowerCase()===code.toLowerCase()),'Mã lô đã tồn tại.'))return; const oldCost=n(lot.cost),costChanged=cost!==oldCost; if(costChanged&&(status(lot)==='closed'||db.distributions.some(x=>x.autoLotId===id)|| (lotSales(id).length&&manualAllocationExists()))){ alert('Không thể sửa GIÁ MUA của lô đã kết toán, đã phân bổ lợi nhuận hoặc có khoản chia lãi chưa đối chiếu. Các thông tin khác vẫn sửa được; hãy giữ giá cũ và chỉnh riêng sau khi đối chiếu sổ.');return; } const rows=[...ev.target.querySelectorAll('.edit-machine-row')];if(window.MCC_U13&&!window.MCC_U13.validateEdit(rows,id))return; const source=db.machines.filter(m=>m.lotId===id),sourceIds=new Set(source.map(m=>m.id)); const picked=[];const seen=new Set(); for(const row of rows){ let mid=row.dataset.mid||''; if(mid){if(!sourceIds.has(mid)||seen.has(mid))return alert('Danh sách máy không hợp lệ.');seen.add(mid)} if(row.dataset.deleted==='yes'){ if(mid&&saleOf(mid))return alert('Không được xóa máy đã bán.'); continue; } const nm=row.querySelector('.machineName').value.trim(),model=row.querySelector('.machineModel').value.trim(); if(!nm)return alert('Tên máy không được để trống.'); const prev=mid?source.find(m=>m.id===mid):null; const photos=[...(prev?.photos||[])];const files=[...row.querySelector('.machinePhotos').files]; if(photos.length+files.length>8)return alert('Mỗi máy tối đa 8 ảnh (bao gồm ảnh cũ).'); picked.push({...prev,id:mid||uid(),lotId:id,name:nm,model,machineCode:row.querySelector('.u13-code-input')?.value.trim()||'',groupId:row.querySelector('.u13-group-select')?.value||'',photos,files}); } for(const m of source){if(!seen.has(m.id))return alert('Máy thuộc lô bị thiếu trong biểu mẫu. Hãy mở lại và thử lần nữa.');} if(!picked.length)return alert('Lô phải có ít nhất một máy.'); const removed=source.filter(m=>!picked.some(x=>x.id===m.id)); if(removed.some(m=>saleOf(m.id)))return alert('Không thể xóa máy đã bán.'); if(costChanged){let delta=cost-oldCost; if(!confirm('Giá mua đổi từ '+money(oldCost)+' thành '+money(cost)+' ('+(delta>0?'+':'')+money(delta)+').\nSố dư tiền kinh doanh và lợi nhuận sẽ tính lại. Bạn đã kiểm tra hóa đơn thực tế và muốn lưu?'))return; } const btn=ev.target.querySelector('[type=submit]');if(btn)btn.disabled=true; try{ for(const item of picked){for(const f of item.files){item.photos.push(await compressPhoto(f))}} const before=source.map(m=>({id:m.id,name:m.name,model:m.model})); const after=picked.map(({files,...m})=>m); const oldCode=lot.code; // Commit only after every file is decoded and validated. Object.assign(lot,{code,name,date,cost,vendor:v.vendor||'',note:v.note||''}); db.machines=db.machines.filter(m=>m.lotId!==id).concat(after); auditRecord('Sửa thông tin lô mua',`${oldCode} → ${code}; giá mua ${money(oldCost)} → ${money(cost)}; máy ${source.length} → ${after.length}; thay đổi tên/model: ${before.filter(b=>{let a=after.find(x=>x.id===b.id);return a&&(a.name!==b.name||a.model!==b.model)}).length}`); save();closeModal();nav('lots');toast('Đã cập nhật lô và máy, giữ nguyên mã giao dịch'); }catch(err){alert('Không lưu được ảnh: '+err.message+'\nDữ liệu lô cũ vẫn được giữ.');if(btn)btn.disabled=false;} } function openEditMachine(id){ const m=db.machines.find(x=>x.id===id);if(!m)return; const l=db.lots.find(x=>x.id===m.lotId); form('✏️ Sửa tên / model máy',`
Máy thuộc lô ${esc(l?.code||'')}. Có thể sửa thông tin mô tả cả khi đã bán, không thay đổi giao dịch bán.
${field('Tên máy *','name','text',m.name,'required')}${field('Model / số máy','model','text',m.model||'')}
Để thêm hoặc xóa ảnh, dùng nút 📷 Ảnh trong Kho máy.
`, 'submitEditMachine'); } function submitEditMachine(ev){const v=vals(ev),m=db.machines.find(x=>x.id===v.machineId);if(!m)return; if(!ensure((v.name||'').trim(),'Tên máy không được để trống.'))return; const old=m.name+' / '+(m.model||'');m.name=v.name.trim();m.model=(v.model||'').trim(); auditRecord('Sửa thông tin máy',old+' → '+m.name+' / '+m.model);save();closeModal();nav('machines');toast('Đã sửa thông tin máy'); } // Render actions in both the Lô mua and Kho máy tables. lotTable=function(list){return tbl(['Mã lô','Tên lô','Số máy','Giá mua + chi phí','Doanh thu','Trạng thái','Lãi / lỗ','Thao tác'],list.map(l=>{ const ms=db.machines.filter(m=>m.lotId===l.id),x=encodeURIComponent(l.id); return tr([esc(l.code),esc(l.name),`${ms.filter(m=>saleOf(m.id)).length}/${ms.length} đã bán`,money(lotCost(l.id)),money(lotRevenue(l.id)), status(l)==='closed'?pill('Đã kết toán','green'):pill('Chưa kết toán','amber'),status(l)==='closed'?`${money(lotProfit(l.id))}`:'—', ` `]);}))} machines=function(){let rows=db.machines.filter(m=>(m.name+' '+m.model+' '+(db.lots.find(l=>l.id===m.lotId)?.code||'')).toLowerCase().includes(filter));return `
Tổng ${db.machines.length} máy • Còn ${db.machines.filter(m=>!saleOf(m.id)).length} máy
${tbl(['Ảnh','Mã lô','Tên máy','Model','Tình trạng','Giá bán','Thao tác'],rows.map(m=>{let s=saleOf(m.id),l=db.lots.find(l=>l.id===m.lotId),x=encodeURIComponent(m.id);return tr([photoThumb(m),esc(l?.code),esc(m.name),esc(m.model),s?pill('Đã bán','green'):((db.deposits||[]).some(d=>d.machineId===m.id&&d.status==='active')?pill('Đã đặt cọc','amber'):pill('Còn kho','amber')),s?money(s.price):'—',` `+(s?'':``)])}))}
`} // ---------- CHUNG ĐỊNH DẠNG SAO LƯU TRÊN CẢ 3 PHIÊN BẢN ----------- const MCC_DATA_KEYS=['lots','machines','sales','cash','members','distributions','fundTransactions','audit','warrantyRecords','productGroups','deposits']; const MCC_CORE_KEYS=['lots','machines','sales','cash','members','distributions']; function normalizePortableData(raw){ if(!raw||typeof raw!=='object'||Array.isArray(raw))throw Error('Dữ liệu không hợp lệ.'); const incoming=JSON.parse(JSON.stringify(raw)); for(const k of MCC_CORE_KEYS)if(!Array.isArray(incoming[k]))throw Error('Thiếu danh sách '+k); if(!Array.isArray(incoming.audit))incoming.audit=[]; if(!Array.isArray(incoming.fundTransactions))incoming.fundTransactions=[]; if(!Array.isArray(incoming.warrantyRecords))incoming.warrantyRecords=[]; if(!Array.isArray(incoming.productGroups))incoming.productGroups=[]; if(!Array.isArray(incoming.deposits))incoming.deposits=[]; // Dữ liệu của bản cá nhân cũ có sổ quỹ fundLedger thay vì fundTransactions. if(!incoming.fundTransactions.length&&Array.isArray(incoming.fundLedger)&&incoming.fundLedger.length){ for(const item of incoming.fundLedger){ const oldId=item.id||uid(); incoming.fundTransactions.push({id:oldId,date:item.date,type:item.type==='in'?'in':'out',kind:item.type==='in'?'profit':item.type==='back'?'transfer':'spend',amount:n(item.amount),note:item.note||'',...(item.distId?{distId:item.distId}:{})}); if(item.type==='back'&&!incoming.cash.some(x=>x.fundTransferId===oldId)){ incoming.cash.push({id:'legacy-fund-back-'+oldId,date:item.date,type:'income',amount:n(item.amount),note:'Nhận từ quỹ (chuyển đổi bản cá nhân): '+(item.note||''),fundTransferId:oldId}); } } } // Dự phòng trường hợp 2 loại sổ quỹ đều có dữ liệu khác nhau: không tự suy đoán. if(Array.isArray(incoming.fundLedger)&&incoming.fundLedger.length&&Array.isArray(raw.fundTransactions)&&raw.fundTransactions.length){ const txIds=new Set(raw.fundTransactions.map(x=>x.id)); if(incoming.fundLedger.some(x=>!txIds.has(x.id)))throw Error('File chứa 2 loại sổ quỹ không khớp. Cần đối chiếu thủ công.'); } for(const k of MCC_DATA_KEYS){ if(!Array.isArray(incoming[k]))throw Error('Danh sách '+k+' không hợp lệ.'); if(incoming[k].length>100000)throw Error('Quá nhiều giao dịch trong '+k); const seen=new Set(); for(const rec of incoming[k]){ if(!rec||typeof rec!=='object'||Array.isArray(rec))throw Error('Bản ghi '+k+' bị lỗi.'); if(k==='audit'&&!rec.id)continue; if(typeof rec.id!=='string'||!(/^[A-Za-z0-9_:.\-]{1,120}$/.test(rec.id)))throw Error('Mã bản ghi '+k+' không hợp lệ.'); if(seen.has(rec.id))throw Error('Bị trùng mã bản ghi trong '+k);seen.add(rec.id); } } const ids=k=>new Set(incoming[k].map(x=>x.id));const lotIds=ids('lots'),machineIds=ids('machines'),saleMachines=new Set(); for(const m of incoming.machines)if(!lotIds.has(m.lotId))throw Error('Máy không liên kết với lô mua hợp lệ.'); for(const s of incoming.sales){if(!machineIds.has(s.machineId))throw Error('Giao dịch bán thiếu máy tương ứng.');if(saleMachines.has(s.machineId))throw Error('Một máy bị bán trùng hai lần.');saleMachines.add(s.machineId);} for(const c of incoming.cash)if(c.lotId&&!lotIds.has(c.lotId))throw Error('Khoản thu/chi tham chiếu lô không tồn tại.'); const warrantyIds=new Set(incoming.warrantyRecords.map(w=>w.id)); const saleIds=new Set(incoming.sales.map(s=>s.id)); for(const w of incoming.warrantyRecords){if(!saleIds.has(w.saleId))throw Error('Hồ sơ bảo hành tham chiếu giao dịch bán không tồn tại.');for(const v of ['cost','received'])if(!Number.isFinite(Number(w[v]||0))||Number(w[v]||0)<0)throw Error('Chi phí hậu mãi không hợp lệ.')} for(const c of incoming.cash)if(c.warrantyRecordId&&!warrantyIds.has(c.warrantyRecordId))throw Error('Khoản thu/chi hậu mãi thiếu hồ sơ tương ứng.'); const memberIds=ids('members'),distIds=ids('distributions'); for(const d of incoming.distributions){if(!memberIds.has(d.memberId))throw Error('Chia lợi nhuận tham chiếu thành viên không tồn tại.');if(d.autoLotId&&!lotIds.has(d.autoLotId))throw Error('Chia lợi nhuận tham chiếu lô không tồn tại.');} for(const f of incoming.fundTransactions)if(f.distId&&!distIds.has(f.distId))throw Error('Giao dịch quỹ tham chiếu khoản lợi nhuận không tồn tại.'); for(const k of ['lots','sales','cash','distributions','fundTransactions'])for(const r of incoming[k]){ for(const key of ['cost','price','received','amount','paid'])if(Object.prototype.hasOwnProperty.call(r,key)){ const value=Number(r[key]);if(!Number.isFinite(value)||value<0)throw Error('Số tiền không hợp lệ trong '+k); } } for(const s of incoming.sales)if(n(s.received)>n(s.price))throw Error('Giao dịch bán đã thu vượt giá bán.'); for(const d of incoming.distributions)if(n(d.paid)>n(d.amount))throw Error('Khoản lợi nhuận đã trả vượt số phân bổ.'); return incoming; } function mergePortable(base,incoming){ const combined=normalizePortableData(base),copy=normalizePortableData(incoming);const stats=[]; for(const k of MCC_DATA_KEYS){ const index=new Map(combined[k].filter(r=>r.id).map(r=>[r.id,r]));let added=0; for(const rec of copy[k]){ if(k==='audit'&&!rec.id){if(!combined.audit.some(x=>JSON.stringify(x)===JSON.stringify(rec))){combined.audit.push(rec);added++}continue} if(index.has(rec.id)){ if(JSON.stringify(index.get(rec.id))!==JSON.stringify(rec))throw Error('Xung đột dữ liệu ở '+k+' / '+rec.id+'. Hai nơi đã sửa cùng bản ghi. KHÔNG gộp tự động.'); }else{combined[k].push(rec);index.set(rec.id,rec);added++} } if(added)stats.push(k+': +'+added); } const norm=s=>String(s??'').trim().toLowerCase(); for(const k of ['lots','members']){ const natural=k==='lots'?'code':'name';const keyMap=new Map(); for(const rec of combined[k]){const label=norm(rec[natural]);if(!label)continue;if(keyMap.has(label)&&keyMap.get(label)!==rec.id)throw Error('Trùng '+(k==='lots'?'mã lô':'tên thành viên')+' giữa hai bản. Cần đối chiếu trước khi gộp.');keyMap.set(label,rec.id)} } normalizePortableData(combined); return {data:combined,summary:stats.join(', ')||'Không có bản ghi mới'}; } function exportData(){const envelope={format:'maycongcu-v1',schemaVersion:2,exportedAt:new Date().toISOString(),data:db}; const blob=new Blob([JSON.stringify(envelope,null,2)],{type:'application/json'}),url=URL.createObjectURL(blob),a=document.createElement('a'); a.href=url;a.download='MayCongCu_SaoLuu_Chung3Ban_'+today()+'_'+new Date().toTimeString().slice(0,5).replace(':','-')+'.json'; if(window.AndroidBackup&&typeof AndroidBackup.saveJson==='function'){AndroidBackup.saveJson(JSON.stringify(envelope));URL.revokeObjectURL(url)} else{document.body.appendChild(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(url),10000);toast('Đã tạo file sao lưu dùng cho cả 3 bản')} } async function importData(e){const file=e.target.files?.[0];e.target.value='';if(!file)return; try{ if(file.size>110*1024*1024)throw Error('File lớn hơn 110 MB.'); const raw=JSON.parse(await file.text()); if(!['maycongcu-v1','maycongcu-v2'].includes(raw.format)||!raw.data)throw Error('Không đúng file sao lưu Máy Công Cụ.'); const incoming=normalizePortableData(raw.data); const choice=prompt('ĐÃ ĐỌC FILE SAO LƯU:\n'+incoming.lots.length+' lô, '+incoming.machines.length+' máy, '+incoming.sales.length+' giao dịch bán.\n\nChọn cách nhập:\n1 = THAY THẾ toàn bộ dữ liệu hiện tại (sau khi sao lưu bản cũ)\n2 = GỘP AN TOÀN, chỉ thêm bản ghi mới; nếu trùng/sửa khác nhau sẽ dừng\nBấm Hủy để không thay đổi.','2'); if(choice===null||choice==='')return; if(!['1','2'].includes(choice.trim()))throw Error('Chỉ nhập 1 hoặc 2.'); if(choice.trim()==='1'){ if(prompt('CẢNH BÁO: Dữ liệu đang mở sẽ bị THAY THẾ.\nHãy bấm Sao lưu bản hiện tại trước khi tiếp tục.\nGõ chính xác THAY THE để xác nhận:','')!=='THAY THE')return; db=incoming;save();nav('home');toast('Đã thay thế dữ liệu từ bản sao lưu');return; } const merged=mergePortable(db,incoming); if(!confirm('GỘP AN TOÀN\n'+merged.summary+'\nKhông có xung đột bản ghi theo mã.\n\nLưu ý: hệ thống không thể tự nhận biết mọi giao dịch nhập trùng bằng tay. Hãy sao lưu trước khi xác nhận. Tiếp tục?'))return; db=merged.data;save();nav('home');toast('Đã gộp các bản ghi mới'); }catch(err){alert('Không thể nhập dữ liệu: '+err.message+'\nDữ liệu đang dùng chưa bị thay đổi.');} } // MCC_STOCK_BY_LOT_V4 — inventory + reports: read-only details for sold and unsold machines. const stockBaseLots=lots, stockBaseSales=sales, stockBaseReports=reports; let stockSearch='',stockLotFilter='all',stockStatusFilter='all',stockOpenLot=''; function stockAllRows(){ const lm=new Map(db.lots.map(l=>[l.id,l])); const sm=new Map(db.sales.map(s=>[s.machineId,s])); return db.machines.map(machine=>({machine,lot:lm.get(machine.lotId),sale:sm.get(machine.id)})); } function stockByLotRows(lid,kind='all'){ return stockAllRows().filter(r=>r.machine.lotId===lid&&(kind==='all'||(kind==='sold'?!!r.sale:!r.sale))); } function stockTotalCards(){ const rows=stockAllRows(),sold=rows.filter(r=>r.sale),unsold=rows.filter(r=>!r.sale),revenue=sum(sold,r=>r.sale.price),received=sum(sold,r=>r.sale.received); return `
${card('Tổng số máy đã mua',rows.length,'Tính cả máy mua lẻ và mua lô')}${card('Đã bán',sold.length,'Đã chuyển khỏi kho')}${card('Còn trong kho',unsold.length,'Số máy chưa bán')}${card('Tổng tiền bán',money(revenue),'Đã thu '+money(received)+' · Còn nợ '+money(revenue-received))}
`; } function stockLotStats(){ return db.lots.map(lot=>{ const rows=stockByLotRows(lot.id),sold=rows.filter(r=>r.sale),remaining=rows.filter(r=>!r.sale); return {lot,rows,sold,remaining,received:sum(sold,r=>r.sale.received),revenue:sum(sold,r=>r.sale.price)}; }).sort((a,b)=>String(b.lot.date||'').localeCompare(String(a.lot.date||''))); } function stockMachineDetailRow(r){ const m=r.machine,s=r.sale; const photo=``; const actions=((db.deposits||[]).some(d=>d.machineId===m.id&&d.status==='active')?'ĐÃ ĐẶT CỌC ':'')+photo+` `+(s?'':` `); if(s)return tr([esc(m.name),esc(m.model||'—'),esc(s.date||'—'),esc(s.customer||'—'),money(s.price),money(s.received),money(n(s.price)-n(s.received)),actions]); return tr([esc(m.name),esc(m.model||'—'),esc(r.lot?.date||'—'),actions]); } function stockMachineTables(rows){ const sold=rows.filter(r=>r.sale),remaining=rows.filter(r=>!r.sale); return `

✅ Đã bán: ${sold.length} máy

${tbl(['Tên máy','Model','Ngày bán','Khách mua','Giá bán','Đã thu','Còn nợ','Thao tác'],sold.map(stockMachineDetailRow))}

📦 Còn lại trong kho: ${remaining.length} máy

${tbl(['Tên máy','Model','Ngày mua','Thao tác'],remaining.map(stockMachineDetailRow))}
`; } function stockMatches(lotStat){ const q=stockSearch.trim().toLocaleLowerCase('vi-VN'); if(stockLotFilter!=='all'&&lotStat.lot.id!==stockLotFilter)return false; if(stockStatusFilter==='sold'&&!lotStat.sold.length)return false; if(stockStatusFilter==='stock'&&!lotStat.remaining.length)return false; if(!q)return true; const normalized=v=>String(v??'').toLocaleLowerCase('vi-VN'); return [lotStat.lot.code,lotStat.lot.name,lotStat.lot.vendor,...lotStat.rows.flatMap(r=>[r.machine.name,r.machine.model,r.sale?.customer])].some(v=>normalized(v).includes(q)); } function stockLotPanel(l){ const {lot,rows,sold,remaining,revenue,received}=l; return `
📦 ${esc(lot.code||'Chưa có mã')} — ${esc(lot.name||'Lô máy')} Tổng ${rows.length} · Đã bán ${sold.length} · Còn kho ${remaining.length} Ngày mua ${esc(lot.date||'—')} · Doanh thu ${money(revenue)} · Nợ ${money(revenue-received)} Xem chi tiết từng máy ▾
${stockMachineTables(rows)}
`; } function stockRememberLot(el){if(el.open)stockOpenLot=el.dataset.lotId;else if(stockOpenLot===el.dataset.lotId)stockOpenLot=''} function stockLotSummaryHtml(){ const rows=stockLotStats().filter(stockMatches); const totals=stockLotStats(); return `
${rows.length}/${totals.length} lô
${rows.length?rows.map(stockLotPanel).join(''):'

Không có lô phù hợp với bộ lọc.

'}
`; } function stockSummaryRefresh(){ const el=document.getElementById('stockSummaryResults');if(el)el.innerHTML=stockLotSummaryHtml(); } function stockChangeLot(v){stockLotFilter=v;stockOpenLot='';stockSummaryRefresh()} function stockChangeStatus(v){stockStatusFilter=v;stockOpenLot='';stockSummaryRefresh()} function stockLotSummaryControls(){ const lotOptions=[['all','Tất cả lô'],...db.lots.map(l=>[l.id,(l.code||'Lô')+' — '+(l.name||'')])]; return `
`; } function stockSummaryPanel(inReports=false){ return `

📦 ${inReports?'Báo cáo chi tiết máy theo từng lô':'Kho máy: đã bán / còn lại theo từng lô'}

Mỗi máy được đếm đúng một lần. Bấm tên lô để xem hai danh sách riêng: máy đã bán và máy còn trong kho. Máy mua riêng lẻ được tính như một lô 1 máy.

${stockTotalCards()}${stockLotSummaryControls()}
${stockLotSummaryHtml()}
`; } // On the inventory screen, every lot has two independently readable sections. machines=function(){return stockSummaryPanel(false)}; // Existing report: keep all weekly / monthly / annual / all-time and CSV tools. reports=function(){return stockSummaryPanel(true)+stockBaseReports()}; // Buying just one machine follows the existing one-machine lot accounting logic. function openSingleMachinePurchase(){ openLot(); const modal=document.querySelector('#overlay .modal');if(!modal)return; modal.querySelector('.modalhead h2').textContent='🛒 Mua 1 máy'; const formEl=modal.querySelector('form'); const code=formEl.elements.namedItem('code'); if(code)code.value='LE-'+today().replaceAll('-','')+'-'+uid().slice(-4).toUpperCase(); const name=formEl.elements.namedItem('name');if(name)name.value='Máy mua lẻ'; const cost=formEl.elements.namedItem('cost');if(cost)cost.closest('.field').querySelector('label').textContent='Giá mua máy (đ) *'; const addBtn=modal.querySelector('.machineentry')?.parentElement?.nextElementSibling; if(addBtn&&addBtn.tagName==='BUTTON')addBtn.style.display='none'; const nm=modal.querySelector('.machineName');if(nm)nm.focus(); const removeBtn=modal.querySelector('.machineentry button:last-child');if(removeBtn)removeBtn.style.display='none'; } lots=function(){ const html=stockBaseLots(); return html.replace('
','
'+btn('+ Mua 1 máy','openSingleMachinePurchase()','alt')); }; // Batch sale records stay separate by machine so stock and debt remain correct. function openMultipleSale(){ const available=db.machines.filter(m=>!saleOf(m.id)); if(!available.length){alert('Không có máy còn kho để bán.');return} const rows=available.map(m=>{ const lot=db.lots.find(l=>l.id===m.lotId); return `
`; }).join(''); form('💰 Bán nhiều máy — một khách hàng',`

Chọn máy và nhập giá bán, tiền đã thu cho từng máy. Mỗi máy sẽ được ghi thành một giao dịch riêng để tính đúng tồn kho, công nợ và lợi nhuận lô. Nếu cần ảnh lúc bán, hãy dùng Bán 1 máy.

${field('Ngày bán','date','date',today(),'required')}${field('Khách mua *','customer','text','','required')}${field('Ghi chú chung','note')}
${rows}
`, 'submitMultipleSale'); } function submitMultipleSale(ev){ const v=vals(ev),selected=[...document.querySelectorAll('.bulk-sale-row')].filter(el=>el.querySelector('.bulk-check').checked); if(!ensure(selected.length>0,'Hãy chọn ít nhất một máy để bán.'))return; if(!ensure((v.customer||'').trim().length>0,'Vui lòng nhập tên khách mua.'))return; const pending=[]; for(const row of selected){ const machineId=row.querySelector('.bulk-check').value,m=db.machines.find(x=>x.id===machineId); const price=n(row.querySelector('.bulk-price').value),received=n(row.querySelector('.bulk-received').value); if(!m||saleOf(machineId)){alert('Có máy đã bán hoặc không còn trong kho. Vui lòng mở lại biểu mẫu.');return} if(price<=0||received<0||received>price){alert('Mỗi máy được chọn phải có giá bán lớn hơn 0, và số tiền đã thu từ 0 đến giá bán.');return} pending.push({id:uid(),machineId,lotId:m.lotId,date:v.date,customer:v.customer.trim(),note:v.note||'',price,received,photos:[],warrantyMonths:0,completedAt:new Date().toISOString()}); } if(!confirm('Xác nhận bán '+pending.length+' máy cho '+v.customer+'?\nCác máy được lưu thành '+pending.length+' giao dịch riêng.'))return; for(const item of pending){const {lotId,...sale}=item;db.sales.push(sale)} /* U9: bán nhiều máy không gọi chia lợi nhuận */ save();closeModal();nav('sales');toast('Đã lưu '+pending.length+' giao dịch bán máy, chưa chia lợi nhuận'); } sales=function(){return stockBaseSales().replace('
','
'+btn('+ Bán nhiều máy','openMultipleSale()','alt'))};

⚙️ QUẢN LÝ MÁY CÔNG CỤ

Đăng nhập để xem dữ liệu chung trên điện thoại và máy tính.

Quên mật khẩu?

');win.document.close();closeModal()} function cashPage(){prepare();const base=legacyCash();const receipts=db.receipts.slice().reverse();return base+newPanel('🧾 Phiếu thu công nợ (không tính trùng doanh thu)',tbl(['Ngày','Khách hàng','Nội dung','Số tiền'],receipts.map(r=>tr([esc(r.date),esc(db.customers.find(c=>c.id===r.customerId)?.name||r.customer),esc(r.note),money(r.amount)]))))} function openCashNew(){if(!guard())return;prepare();form('Ghi thu / chi',`
${selectField('Nghiệp vụ','type',[['expense','Chi tiền'],['income','Thu tiền khác'],['customer_receipt','Thu công nợ khách hàng']])}${field('Ngày','date','date',today(),'required')}${field('Số tiền','amount','number','','required')}${selectField('Khách hàng','customerId',customerOptions())}${selectField('Giao dịch còn nợ','saleId',db.sales.filter(s=>n(s.price)>n(s.received)).map(s=>[s.id,s.customer+' · '+money(n(s.price)-n(s.received))]))}${selectField('Loại chi','category',[['supplies','Mua vật tư / đồ dùng'],['staff','Chi nhân viên mua đồ'],['company','Chi phí công ty'],['machine','Chi liên quan máy'],['other','Khác']])}${field('Người nhận / nhân viên','recipient')}${selectField('Lô liên quan','lotId',[['','Chi chung'],...db.lots.map(l=>[l.id,l.code+' — '+l.name])])}${field('Nội dung','note','text','','required')}
Khi thu công nợ, chỉ cập nhật số đã thu của giao dịch bán; không ghi thêm doanh thu vào sổ Thu tiền khác.
`,'submitCash');const chosen=document.querySelector('#entry [name=customerId]');const debtSel=document.querySelector('#entry [name=saleId]');if(chosen&&debtSel){chosen.onchange=()=>{const id=chosen.value;const matches=db.sales.filter(s=>n(s.price)>n(s.received) && (!id || accountFor(s)?.id===id));debtSel.innerHTML=matches.map(s=>``).join('')}}} function saveCashNew(e){if(!guard())return;let v=vals(e),amount=n(v.amount);if(!(amount>0))return alert('Số tiền phải lớn hơn 0');prepare();if(v.type==='customer_receipt'){ const s=db.sales.find(s=>s.id===v.saleId);if(!s||!ensure(amount<=n(s.price)-n(s.received),'Số thu vượt công nợ của giao dịch'))return; const cid=accountFor(s)?.id||v.customerId||'';s.received=n(s.received)+amount;db.receipts.push({id:uid(),date:v.date,amount,customerId:cid,saleId:s.id,customer:s.customer,note:v.note});audit('Thu công nợ',s.customer+' '+money(amount)); }else{if(v.lotId&&status(db.lots.find(l=>l.id===v.lotId))==='closed')return alert('Lô đã kết toán. Vui lòng ghi chi phí chung và đối chiếu lợi nhuận đã phân bổ.');db.cash.push({...v,id:uid(),amount})} save();closeModal();nav('cash')} function openCustomerCollect(){if(!guard())return;prepare();const debts=db.sales.filter(s=>n(s.price)>n(s.received));if(!debts.length)return alert('Không còn công nợ');form('Thu công nợ khách hàng',`${selectField('Chọn khoản nợ','saleId',debts.map(s=>[s.id,s.customer+' — '+db.machines.find(m=>m.id===s.machineId)?.name+' — còn '+money(n(s.price)-n(s.received))]))}
${field('Ngày thu','date','date',today(),'required')}${field('Số tiền thu','amount','number','','required')}${field('Ghi chú','note','text','Thu công nợ')}
`,'submitCollect')} function saveCollectNew(e){if(!guard())return;let v=vals(e),s=db.sales.find(s=>s.id===v.saleId),amount=n(v.amount);if(!s||amount<=0||amount>n(s.price)-n(s.received))return alert('Số tiền thu không hợp lệ');prepare();s.received=n(s.received)+amount;db.receipts.push({id:uid(),date:v.date,amount,customerId:accountFor(s)?.id||'',saleId:s.id,customer:s.customer,note:v.note});audit('Thu công nợ',s.customer+' '+money(amount));save();closeModal();nav('sales')} function extraSaleControls(){prepare();return `
${selectField('Chi nhánh bán','branchId',officeOptions())}${selectField('Kiểu hoa hồng','commissionMode',[['amount','Nhập số tiền'],['percent','Theo % giá bán']])}${field('Hoa hồng (đ hoặc %)','commissionValue','text','0')}${field('Người nhận hoa hồng (bắt buộc nếu có hoa hồng)','commissionRecipient','text','')}`+`
${selectField('Mẫu phiếu in sau bán','printSaleStyle',[['clean','Mẫu 1 — Trang trọng'],['modern','Mẫu 2 — Hiện đại'],['compact','Mẫu 3 — Gọn']])}`+`
`} function customerPicked(sel){const c=db.customers.find(c=>c.id===sel.value),inp=document.querySelector('#entry [name=customer]');if(c&&inp)inp.value=c.name} function addSaleExpense(){const d=document.createElement('div');d.className='sale-expense-item';d.style='display:grid;grid-template-columns:1fr 140px auto;gap:7px;margin:6px 0';d.innerHTML='';document.getElementById('saleExpenseRows').append(d)} function openSaleNew(mid){if(!guard())return;legacyOpenSale(mid);const g=document.querySelector('#entry .formgrid');if(g){g.insertAdjacentHTML('beforeend',extraSaleControls());if(mid){let m=db.machines.find(m=>m.id===mid),lot=db.lots.find(l=>l.id===m?.lotId),b=document.querySelector('#entry [name=branchId]');if(b)b.value=m?.branchId||lot?.branchId||''}const style=document.querySelector('#entry [name=printSaleStyle]');if(style)style.value=db.company?.autoPrintTemplate||'clean';}} async function submitSaleNew(e){if(!guard())return;const fileInputs=e.target.querySelector('[name=salePhotos]');const photosFiles=fileInputs?[...fileInputs.files]:[];let v=vals(e),m=db.machines.find(m=>m.id===v.machineId); if(!m||saleOf(m.id))return alert('Máy đã bán hoặc không tồn tại');let price=n(v.price),received=n(v.received);if(price<=0||received<0||received>price)return alert('Giá bán hoặc số thu không hợp lệ');if(photosFiles.length>8)return alert('Tối đa 8 ảnh'); const costRows=[...e.target.querySelectorAll('.sale-expense-item')].map(el=>({name:el.querySelector('.expense-name').value.trim(),amount:n(el.querySelector('.expense-amount').value)}));if(costRows.some(x=>!x.name||x.amount<=0))return alert('Mỗi khoản chi phí cần có tên và số tiền dương'); const cm=Number(String(v.commissionValue||'0').replace(',','.').replace(/[^0-9.]/g,''))||0;if(cm<0||!Number.isFinite(cm)|| (v.commissionMode==='percent'&&cm>100))return alert('Hoa hồng không hợp lệ (0–100%)');const commission=v.commissionMode==='percent'?Math.round(price*cm/100):n(v.commissionValue);if(commission<0)return alert('Hoa hồng không hợp lệ');const recipient=String(v.commissionRecipient||'').trim();if(commission>0&&!recipient)return alert('Bạn cần nhập rõ TÊN NGƯỜI NHẬN HOA HỒNG trước khi lưu.');if(recipient.length>120)return alert('Tên người nhận hoa hồng quá dài.'); const total=costRows.reduce((a,x)=>a+x.amount,0)+commission;if(total>price&&!confirm('Chi phí và hoa hồng vượt giá bán, lợi nhuận có thể âm. Vẫn ghi nhận?'))return; const c=db.customers.find(c=>c.id===v.customerId);if(c)v.customer=c.name;if(!v.customer?.trim())return alert('Vui lòng chọn hoặc nhập tên khách'); const requestPrint=!!e.target.querySelector('[name=printAfterSale]')?.checked;const printStyle=['clean','modern','compact'].includes(v.printSaleStyle)?v.printSaleStyle:'clean'; let printWin=null;if(requestPrint){printWin=window.open('','_blank');if(printWin){printWin.document.write('Đang ghi nhận bán máyĐang lưu bán máy lên hệ thống… Phiếu in sẽ hiển thị sau khi lưu thành công.');printWin.document.close();}} let photos=[];for(let f of photosFiles){try{photos.push(await compressPhoto(f))}catch(err){if(printWin&&!printWin.closed)printWin.close();return alert('Không đọc được ảnh: '+err.message)}} const saleId=uid();const sale={id:saleId,machineId:m.id,date:v.date,completedAt:new Date().toISOString(),customer:v.customer.trim(),customerId:c?.id||'',price,received,note:v.note||'',photos,warrantyMonths:Math.max(0,Math.min(240,Math.floor(n(v.warrantyMonths)))),commission,commissionMode:v.commissionMode,commissionInput:cm,commissionRecipient:recipient,expenses:costRows.map(x=>({...x,id:uid()})),branchId:v.branchId||''};db.sales.push(sale); // Mỗi khoản chi có một mã liên kết với giao dịch bán; giá khách phải trả vẫn là price. for(const line of costRows){db.cash.push({id:uid(),date:v.date,lotId:m.lotId,saleExpenseId:saleId,type:'expense',amount:line.amount,note:'Chi phí bán máy '+m.name+': '+line.name,category:'machine'})} if(commission){db.cash.push({id:uid(),date:v.date,lotId:m.lotId,saleCommissionId:saleId,type:'expense',amount:commission,note:'Hoa hồng bán máy '+m.name+' → '+recipient+(v.commissionMode==='percent'?' ('+cm+'%)':''),recipient,category:'commission'})} if(v.branchId)m.branchId=v.branchId; const allocated=false;/* U9: chỉ chia khi quản trị bấm ở mục Chia lợi nhuận */audit('Bán máy',m.name+' '+money(price)+'; chi phí '+money(total));save();closeModal();nav('sales');toast(allocated?'Đã bán và phân bổ lợi nhuận':'Đã bán máy, ghi nhận chi phí và hoa hồng'); if(requestPrint){if(typeof saveQueue!=='undefined'){await saveQueue;const serverOk=document.getElementById('cloudStatus')?.textContent==='Đã đồng bộ';if(!serverOk){if(printWin&&!printWin.closed)printWin.close();alert('Dữ liệu CHƯA được xác nhận lưu lên Supabase. Không tự in phiếu. Hãy kiểm tra lỗi đồng bộ và sao lưu dữ liệu hiện có.');return;}}mccSalePrintDocument(saleId,printStyle,printWin);} } function mccSalePrintDocument(saleId, style='clean', providedWindow=null){ const s=db.sales.find(x=>x.id===saleId),m=s&&db.machines.find(x=>x.id===s.machineId); if(!s||!m){if(providedWindow&&!providedWindow.closed)providedWindow.close();alert('Không tìm thấy giao dịch đã lưu để in.');return false;} const company=db.company||{},customer=db.customers?.find(x=>x.id===s.customerId)||{}; const win=providedWindow&&!providedWindow.closed?providedWindow:window.open('','_blank'); if(!win){alert('Chrome đang chặn cửa sổ in. Hãy cho phép popup cho website hoặc dùng nút In trong danh sách bán máy.');return false;} const safe=esc; const fmt=(v)=>money(n(v)); const title='PHIẾU BÁN MÁY'; const txtCustomer=[s.customer||customer.name||'Khách hàng',customer.phone||'',customer.address||''].filter(Boolean).map(safe).join(' · '); const outstand=Math.max(0,n(s.price)-n(s.received)); const theme=style==='modern'?'modern':style==='compact'?'compact':'clean'; const logo=typeof company.logo==='string' && /^data:image\/(?:png|jpe?g|webp);base64,/i.test(company.logo)?``:''; const documentHtml=`${title} - ${safe(m.name)}
${logo}
${safe(company.name||'CÔNG TY MÁY CÔNG CỤ')}
${safe(company.address||'')}
${safe(company.phone||'')} ${safe(company.email||'')} ${company.tax?' · MST: '+safe(company.tax):''}

${title}

Ngày bán: ${safe(s.date||'')}
Khách hàng: ${txtCustomer}

Tên máy / ModelGiá bánĐã thuCòn nợ
${safe(m.name)} ${safe(m.model||'')}${fmt(s.price)}${fmt(s.received)}${fmt(outstand)}

Thời hạn bảo hành: ${n(s.warrantyMonths)} tháng
Ghi chú: ${safe(s.note||'—')}

Chi phí nội bộ và tiền hoa hồng không được đưa vào phiếu khách hàng.

Người bán
(Ký, ghi rõ họ tên)
Người mua
(Ký, ghi rõ họ tên)
`; let didPrint=false; const printOnce=()=>{if(didPrint||win.closed)return;didPrint=true;try{win.focus();win.print();}catch(err){console.warn('Hộp thoại in bị trình duyệt chặn',err);}}; try{win.onload=()=>{setTimeout(printOnce,350)};win.document.open();win.document.write(documentHtml);win.document.close();setTimeout(printOnce,1400);return true;} catch(err){alert('Không mở được phiếu in: '+err.message);return false;} } window.mccSalePrintDocument=mccSalePrintDocument; function saleExtraPanel(){prepare();return newPanel('🧮 Chi phí và hoa hồng theo giao dịch',tbl(['Ngày','Máy','Khách hàng','Người nhận hoa hồng','Hoa hồng','Chi phí khác','Giá bán trừ phí*','In'],db.sales.slice().reverse().map(s=>{let m=db.machines.find(m=>m.id===s.machineId),cost=(s.expenses||[]).reduce((t,c)=>t+n(c.amount),0);return tr([esc(s.date),esc(m?.name),esc(s.customer),esc(s.commissionRecipient||(s.commission?'Chưa ghi người nhận':'—')),money(s.commission),money(cost),money(n(s.price)-n(s.commission)-cost),` `])})))+'

* Số hiển thị là giá bán sau chi phí bán và hoa hồng, chưa trừ giá vốn mua máy và chi phí mua lô.

'} function openPrintForSale(id){openPrintPanel('sale');document.querySelector('[name=saleId]').value=id} function rolesPage(){const role=typeof cloudRole==='undefined'?'admin':cloudRole;let html=`

🔐 Tài khoản và nhân viên

Tài khoản hiện tại: ${esc(document.getElementById('accountName')?.textContent||'Cá nhân')} · Quyền: ${esc(role||'Quản lý')}

`; if(typeof cloudClient!=='undefined'&&cloudClient)html+=`

${btn('🔒 Đổi mật khẩu của tôi','openChangePassword()')}${role==='admin'?btn('🔑 Xem / đổi mã khôi phục Admin','MCC_ADMIN_RECOVERY.openSetup()','alt'): ''}

`; else if(typeof openLocalUsers==='function')html+=`

${permitted()?btn('👥 Quản lý nhân viên offline','openLocalUsers()'):''}

${btn('🔒 Đổi mật khẩu offline','openChangePassword()','alt')}

`; else html+='

Đây là bản cá nhân lưu trên trình duyệt, không có hệ thống mật khẩu đăng nhập riêng.

'; if(SHARED&&permitted())html+=`

Quản lý nhân viên và khách hàng

${btn('+ Thêm nhân viên / khách hàng','openWebStaff()')}${btn('↻ Tải danh sách nhân viên','loadWebStaff()','alt')}${btn('🔎 Kiểm tra kết nối nhân viên','testStaffConnection()','alt')}
Tài khoản Khách hàng chỉ đăng nhập vào phần mềm dùng chung này và xem ảnh máy còn kho. Quản trị viên bật/tắt máy được giới thiệu tại Kho máy. Không tạo website hoặc tên miền khách riêng.
Nếu thêm nhân viên báo lỗi, hãy bấm “Kiểm tra kết nối nhân viên” ở trên để xem nguyên nhân.
Bấm Tải danh sách để xem tài khoản. Không chia sẻ mật khẩu quản trị; mỗi khách nên có tài khoản riêng để bạn có thể khóa khi cần.
`; html+='
';return html} function openChangePassword(){if(typeof cloudClient!=='undefined'&&cloudClient){form('Đổi mật khẩu Cloudflare/Supabase',`
${field('Mật khẩu mới (ít nhất 8 ký tự)','pass1','password','','required minlength="8"')}${field('Nhập lại mật khẩu','pass2','password','','required minlength="8"')}
Đổi mật khẩu đăng nhập phần mềm Supabase, không phải mật khẩu Cloudflare.
`,'saveChangedPassword')} else if(typeof offlineAccounts!=='undefined'){form('Đổi mật khẩu offline',`
${field('Mật khẩu hiện tại','old','password','','required')}${field('Mật khẩu mới','pass1','password','','required minlength="8"')}${field('Nhập lại','pass2','password','','required minlength="8"')}
`,'saveChangedPassword')} else alert('Bản cá nhân không có tài khoản đăng nhập riêng');document.getElementById('entry')?.classList.add('mcc-password-form')} async function saveChangedPassword(e){let v=vals(e);if(v.pass1.length<8||v.pass1!==v.pass2)return alert('Hai mật khẩu mới phải trùng nhau, ít nhất 8 ký tự');if(typeof cloudClient!=='undefined'&&cloudClient){const {error}=await cloudClient.auth.updateUser({password:v.pass1});if(error)return alert('Không đổi được: '+error.message);closeModal();toast('Đổi mật khẩu thành công')} else if(typeof offlineAccounts!=='undefined'){let a=offlineAccounts.find(x=>x.username===offlineCurrentUser);if(!a)return alert('Không tìm thấy tài khoản');if(await pwdHash(v.old,a.salt)!==a.hash)return alert('Sai mật khẩu hiện tại');const updated=await newAccount(a.username,v.pass1,a.role);Object.assign(a,updated);await setLocal('accounts',offlineAccounts);closeModal();toast('Đã đổi mật khẩu offline')} } // Preserve old functions and extend the existing navigation without replacing the core accounting formulas. const legacyCash=window.cash,legacyOpenSale=window.openSale,legacyOpenMultiple=window.openMultipleSale,legacySubmitMultiple=window.submitMultipleSale,legacyOpenLot=window.openLot,legacySubmitLot=window.submitLot,legacyMachines=window.machines,legacySales=window.sales,legacyRender=window.render; labels.customers=['👥','Khách hàng'];labels.branches=['🏢','Chi nhánh'];labels.company=['🖨️','Cài đặt / Công ty / In'];labels.accounts=['🔐','Tài khoản']; function levelOnePage(){prepare();const rows=db.machines.map(m=>{const sold=!!saleOf(m.id),lot=db.lots.find(l=>l.id===m.lotId);return {m,lot,sold}}); return `
${card('Tổng số máy',rows.length,'')}${card('Đã bán',rows.filter(r=>r.sold).length,'')}${card('Còn trong kho',rows.filter(r=>!r.sold).length,'')}
`+newPanel('📦 Danh sách máy (không hiển thị tài chính)',tbl(['Lô','Máy','Model','Tình trạng'],rows.map(r=>tr([esc(r.lot?.code||'—'),esc(r.m.name),esc(r.m.model),r.sold?pill('Đã bán','green'):pill('Còn kho','amber')]))));} window.render=function(){prepare();if(!['customers','branches','company','accounts'].includes(page)){legacyRender()}else{document.getElementById('pagetitle').textContent=labels[page][1];document.getElementById('subtitle').textContent='Máy Công Cụ • Quản lý kinh doanh';document.getElementById('content').innerHTML=({customers:customersPage,branches:branchesPage,company:companyPage,accounts:window.rolesPage})[page]();} const items=Object.entries(labels).filter(([key])=>cloudRole==='viewer1'?['machines','accounts'].includes(key):(!window.MCC_STAFF_LIMITED||['home','lots','machines','sales','reports','accounts'].includes(key))); document.getElementById('sidenav').innerHTML=items.map(([key,val])=>``).join(''); if(window.MCC_STAFF_LIMITED&&page!=='accounts')document.getElementById('content').innerHTML=levelOnePage(); /* Level-one staff may inspect only counts and machine names. */ if(false&&window.MCC_STAFF_LIMITED&&page==='home')document.getElementById('content').innerHTML=`
${card('Tổng máy',db.machines.length,'')}${card('Máy đã bán',db.sales.length,'')}${card('Máy còn kho',db.machines.filter(m=>!saleOf(m.id)).length,'')}

Chỉ xem kho và bán máy

Nhân viên cấp 1 không được truy cập báo cáo tài chính.

`; if(typeof applyViewerReadOnly==='function'&&!permitted())applyViewerReadOnly(); }; window.openCustomer=openCustomer;window.saveCustomer=saveCustomer;window.customerHistory=customerHistory;window.openBranch=openBranch;window.saveBranch=saveBranch;window.openMoveMachine=openMoveMachine;window.saveMoveMachine=saveMoveMachine;window.openCompany=openCompany;window.saveCompany=saveCompany;window.openPrintPanel=openPrintPanel;window.printSelected=printSelected;window.openPrintForSale=openPrintForSale;window.openCash=openCashNew;window.submitCash=saveCashNew;window.openCollect=openCustomerCollect;window.submitCollect=saveCollectNew;window.customerPicked=customerPicked;window.addSaleExpense=addSaleExpense;window.openSale=openSaleNew;window.submitSale=submitSaleNew;window.openChangePassword=openChangePassword;window.saveChangedPassword=saveChangedPassword; window.cash=function(){return cashPage()};window.sales=function(){return legacySales()+saleExtraPanel()}; window.machines=function(){let html=legacyMachines();const available=db.machines.map(m=>tr([esc(m.name),esc(db.lots.find(l=>l.id===m.lotId)?.code),esc(db.branches.find(b=>b.id===(m.branchId||db.lots.find(l=>l.id===m.lotId)?.branchId))?.name||'—'),permitted()?``:'—']));return html+newPanel('📍 Vị trí từng máy',tbl(['Máy','Lô','Chi nhánh','Điều chỉnh'],available))}; window.openLot=function(){if(!guard())return;legacyOpenLot();const grid=document.querySelector('#entry .formgrid');if(grid){prepare();grid.insertAdjacentHTML('beforeend',selectField('Chi nhánh nhập lô','branchId',officeOptions()))}} window.submitLot=async function(e){if(!guard())return;const branchId=e.target.querySelector('[name=branchId]')?.value||'';const ids=new Set(db.lots.map(l=>l.id));await legacySubmitLot(e);const lot=db.lots.find(l=>!ids.has(l.id));if(lot){lot.branchId=branchId;save()}} window.openMultipleSale=function(){if(!guard())return;legacyOpenMultiple();const grid=document.querySelector('#entry .formgrid');if(grid)grid.insertAdjacentHTML('beforeend',selectField('Khách hàng đã lưu','customerId',customerOptions()));const el=document.querySelector('#entry [name=customerId]');el?.addEventListener('change',()=>customerPicked(el))} window.submitMultipleSale=function(e){if(!guard())return;const cId=e.target.querySelector('[name=customerId]')?.value||'';const before=new Set(db.sales.map(s=>s.id));legacySubmitMultiple(e);const c=db.customers.find(c=>c.id===cId);const added=db.sales.filter(s=>!before.has(s.id));if(c&&added.length){added.forEach(s=>{s.customerId=c.id;s.customer=c.name});save()}} window.nav=(function(oldNav){return function(next){if(cloudRole==='viewer1'&&!['machines','accounts'].includes(next))return alert('Nhân viên cấp 2 chỉ được xem Kho máy và đường link khách.');if(window.MCC_STAFF_LIMITED&&!['home','lots','machines','sales','reports','accounts'].includes(next))return alert('Không có quyền xem nội dung này.');return oldNav(next)}})(window.nav); // Hoàn tác an toàn GIAO DỊCH NHẬP NHẦM có hoa hồng / chi phí. // Chỉ áp dụng khi không có trao đổi tiền thật; vẫn giữ bản ghi hủy trong lịch sử. const originalCancel=window.cancelSale; if(typeof originalCancel==='function')window.cancelSale=async function(id){ if(cloudRole!=='admin')return alert('Chỉ quản trị viên mới được hủy giao dịch.'); const sale=db.sales.find(s=>s.id===id); if(!sale)return alert('Không tìm thấy giao dịch bán. Vui lòng tải lại trang và kiểm tra.'); const linkedCash=db.cash.filter(c=>c.saleExpenseId===id||c.saleCommissionId===id); // Giao dịch không có chi phí/hoa hồng vẫn theo quy trình hủy ban đầu. if(!linkedCash.length)return originalCancel(id); const machine=db.machines.find(m=>m.id===sale.machineId); const lot=db.lots.find(l=>l.id===machine?.lotId); if(!machine||!lot)return alert('Thiếu liên kết máy hoặc lô. Chưa thể hủy an toàn.'); if(warrantyRecords().some(r=>r.saleId===id))return alert('Máy này đã có hồ sơ bảo hành/bảo dưỡng. Cần đối chiếu trước khi hủy.'); if(!reversalGuard(lot.id))return; const statusEl=document.getElementById('cloudStatus'); if(statusEl?.textContent==='Đang đồng bộ…')return alert('Phần mềm đang đồng bộ. Hãy đợi xác nhận Đã đồng bộ rồi thực hiện lại.'); const totalCommission=linkedCash.filter(c=>c.saleCommissionId===id).reduce((sum,c)=>sum+n(c.amount),0); const totalCosts=linkedCash.filter(c=>c.saleExpenseId===id).reduce((sum,c)=>sum+n(c.amount),0); const text='HỦY BÁN DO NHẬP NHẦM\n' +machine.name+' — '+lot.code+'\n' +'Giá bán đã ghi: '+money(sale.price)+'\n' +'Tiền đã ghi là thu: '+money(sale.received)+'\n' +'Hoa hồng đã ghi: '+money(totalCommission)+'\n' +'Chi phí bán máy đã ghi: '+money(totalCosts)+'\n\n' +'CHỈ tiếp tục khi đây là dữ liệu NHẬP NHẦM: thực tế chưa nhận tiền, chưa chi hoa hồng hoặc các khoản chi phí trên.\n' +'Nếu thực tế đã có tiền giao nhận, bấm HỦY để dừng và đối chiếu kế toán.'; if(!confirm(text))return; const phrase=prompt('Để xác nhận chỉ hủy dữ liệu NHẬP NHẦM, hãy gõ chính xác: HUY NHAP NHAM'); if(phrase!=='HUY NHAP NHAM')return alert('Đã dừng, chưa thay đổi dữ liệu.'); const before=JSON.parse(JSON.stringify(db)); const now=new Date().toISOString(); const unpaidAlloc=db.distributions.filter(d=>d.autoLotId===lot.id); db.voidedSaleRecords=Array.isArray(db.voidedSaleRecords)?db.voidedSaleRecords:[]; db.voidedSaleRecords.push({id:uid(),voidedAt:now,reason:'Nhập nhầm giao dịch; không có trao đổi tiền thực tế',sale:JSON.parse(JSON.stringify(sale)),cash:JSON.parse(JSON.stringify(linkedCash)),unpaidAllocations:JSON.parse(JSON.stringify(unpaidAlloc)),lotCode:lot.code,machineName:machine.name}); db.sales=db.sales.filter(s=>s.id!==id); db.cash=db.cash.filter(c=>c.saleExpenseId!==id&&c.saleCommissionId!==id); db.distributions=db.distributions.filter(d=>d.autoLotId!==lot.id); auditRecord('Hủy bán nhập nhầm',lot.code+' / '+machine.name+'; hoàn tác doanh thu '+money(sale.price)+'; hủy ghi thu '+money(sale.received)+'; hoàn tác hoa hồng '+money(totalCommission)+'; hoàn tác chi phí '+money(totalCosts)+'; mã '+id); // Chờ Supabase xác nhận, không thông báo thành công trước khi đồng bộ. cloudSave(JSON.parse(JSON.stringify(db))).catch(()=>{}); await saveQueue; if(statusEl?.textContent!=='Đã đồng bộ'){ db=before; alert('Chưa xác nhận được lưu trên Supabase. Dữ liệu trên màn hình được giữ lại như cũ. Không thực hiện thêm thao tác; hãy kiểm tra kết nối và tải lại trang.'); return; } nav('sales'); toast('Đã hủy giao dịch nhập nhầm và hoàn tác hoa hồng/chi phí ghi sổ; máy trở lại kho.'); }; function openFeatureMenu(){const all=Object.entries(labels).filter(([k])=>!window.MCC_STAFF_LIMITED||['home','lots','machines','sales','reports','accounts'].includes(k));document.getElementById('overlay').innerHTML=`
`} window.openFeatureMenu=openFeatureMenu; const topTools=document.querySelector('.top .top-tools')||document.querySelector('.top .actions');if(topTools){const b=document.createElement('button');b.type='button';b.className='btn alt';b.textContent='☰ Danh mục';b.onclick=openFeatureMenu;topTools.prepend(b)} function staffRoleText(r){return r==='manager'?'Quản lý — chỉ thêm mới':r==='viewer2'?'Nhân viên cấp 1 — chỉ xem tất cả':r==='viewer1'?'Nhân viên cấp 2 — chỉ xem kho':r==='customer'?'Khách hàng — chỉ xem kho':r==='disabled'?'Đã khóa':'Chỉ xem (cũ)'} // U8: clarify whether the staff Edge Function is unreachable, missing, or rejecting the request. async function callStaffApi(body){ if(!permitted())throw Error('Chỉ quản lý được phép thao tác'); if(typeof cloudClient==='undefined'||!cloudClient)throw Error('Không có kết nối Supabase'); const {data:{session},error:sessionError}=await cloudClient.auth.getSession(); if(sessionError||!session?.access_token)throw Error('Bạn chưa đăng nhập Supabase; hãy đăng xuất rồi đăng nhập lại bằng tài khoản quản trị.'); let data,error; try{({data,error}=await cloudClient.functions.invoke('staff-admin',{body}));} catch(e){error=e} if(error){ const status=Number(error.context?.status||error.status||0); let serverDetail=''; if(error.context?.clone){ try{const response=await error.context.clone().json();serverDetail=String(response?.error||response?.message||'');}catch(_e){} } const detail=serverDetail||String(error.message||'Không xác định'); if(status===404)return Promise.reject(Error('Supabase chưa tìm thấy chức năng staff-admin (HTTP 404). Chỉ cập nhật Cloudflare không cài được chức năng này. Hãy chạy CAI_DAT_CHUC_NANG_NHAN_VIEN.cmd trong ZIP để triển khai lên đúng dự án Supabase.')); if(status===401)return Promise.reject(Error('Supabase từ chối xác thực (401). Hãy đăng nhập lại bằng tài khoản quản trị và kiểm tra cấu hình xác thực của Edge Function. Chi tiết: '+detail)); if(status===403)return Promise.reject(Error('Tài khoản không có quyền tạo nhân viên (403). Cần kiểm tra vai trò admin trong bảng app_users và SQL phân quyền. Chi tiết: '+detail)); if(error.name==='FunctionsFetchError'||/Failed to send a request|Failed to fetch|NetworkError/i.test(detail))return Promise.reject(Error('Không gửi được yêu cầu đến staff-admin. Có thể Edge Function chưa triển khai, mạng bị chặn hoặc cấu hình CORS/Supabase sai. Hãy chạy trình cài đặt staff-admin một lần và thử nút “Kiểm tra kết nối nhân viên”.')); throw Error('staff-admin'+(status?' (HTTP '+status+')':'')+': '+detail); } if(data?.error)throw Error('staff-admin: '+String(data.error)); return data; } async function testStaffConnection(){ const el=document.getElementById('staffConnectionStatus');if(el)el.textContent='Đang kiểm tra kết nối staff-admin…'; try{const data=await callStaffApi({action:'list'});const message='✅ Kết nối staff-admin hoạt động, tải được '+(Array.isArray(data.users)?data.users.length:'?')+' tài khoản nhân viên.';if(el)el.textContent=message;else alert(message);} catch(e){const message='❌ '+e.message;if(el)el.textContent=message;else alert(message);} } window.testStaffConnection=testStaffConnection; async function loadWebStaff(){const el=document.getElementById('webStaffList');if(!el)return;el.textContent='Đang tải…';try{const data=await callStaffApi({action:'list'});const rows=(data.users||[]).map(u=>tr([esc(u.display_name),esc(staffRoleText(u.role)),` `]));el.innerHTML=tbl(['Tên nhân viên','Cấp quyền','Thao tác'],rows)}catch(e){el.textContent='Chưa kết nối được chức năng nhân viên: '+e.message}} function openWebStaff(){if(!guard())return;form('Thêm Quản lý / Nhân viên (Supabase)',`
${field('Tên đăng nhập (chữ thường, không dấu)','username','text','','required autocomplete="off"')}${field('Mật khẩu TẠM do Admin cấp (tối thiểu 8 ký tự)','password','password','','required minlength="8" autocomplete="new-password"')}${selectField('Cấp quyền','role',[['manager','Quản lý: tạo mới, không sửa/xóa'],['viewer2','Nhân viên cấp 1: xem tất cả'],['viewer1','Nhân viên cấp 2: chỉ xem kho và link'],['customer','Khách hàng: xem kho công khai']])}${field('Tên hiển thị','display_name','text','')}

Nhân viên đăng nhập bằng tên và mật khẩu TẠM trên cùng link phần mềm, rồi bắt buộc đổi mật khẩu lần đầu. Khi nhân viên quên mật khẩu, Admin dùng nút Đặt lại mật khẩu trong danh sách nhân viên; không cần gửi email. Khi đăng nhập, khách chỉ nhìn thấy ảnh máy còn kho, không có giá.

`,'saveWebStaff')} async function saveWebStaff(e){let v=vals(e);if(!/^[a-z][a-z0-9_]{2,29}$/.test(v.username)||v.password.length<8)return alert('Tên đăng nhập hoặc mật khẩu không hợp lệ');try{await callStaffApi({action:'create',...v});closeModal();nav('accounts');loadWebStaff();toast('Đã tạo tài khoản thành công')}catch(err){alert('Không tạo được tài khoản: '+err.message)}} async function changeWebStaffRole(id){const r=prompt('Nhập 1 = Quản lý, 2 = Nhân viên cấp 1 xem tất cả, 3 = Nhân viên cấp 2 chỉ kho, 4 = Khách hàng','2');if(!['1','2','3','4'].includes(r))return;try{await callStaffApi({action:'role',user_id:id,role:r==='1'?'manager':r==='2'?'viewer2':r==='3'?'viewer1':'customer'});loadWebStaff()}catch(err){alert(err.message)}} async function resetWebStaffPassword(id){const pw=prompt('Nhập mật khẩu mới cho nhân viên (tối thiểu 8 ký tự)');if(!pw)return;if(pw.length<8)return alert('Mật khẩu tối thiểu 8 ký tự');try{await callStaffApi({action:'password',user_id:id,password:pw});toast('Đã đặt lại mật khẩu')}catch(err){alert(err.message)}} async function disableWebStaff(id){if(!confirm('Khóa quyền đăng nhập của nhân viên này?'))return;try{await callStaffApi({action:'disable',user_id:id});loadWebStaff()}catch(err){alert(err.message)}} window.openWebStaff=openWebStaff;window.saveWebStaff=saveWebStaff;window.loadWebStaff=loadWebStaff;window.changeWebStaffRole=changeWebStaffRole;window.resetWebStaffPassword=resetWebStaffPassword;window.disableWebStaff=disableWebStaff; window.MCC_READONLY_ACTIONS=/(?:openLot|openSingleMachinePurchase|submitLot|openSale|submitSale|openMultipleSale|submitMultipleSale|openCash|submitCash|openCollect|submitCollect|openProfit|submitProfit|openPay|submitPay|openFundTransfer|submitFundTransfer|openMember|submitMember|openRates|submitRates|openEditLot|openEditMachine|submitEditLot|submitEditMachine|deleteLot|cancelSale|addLocalUser|removeLocalUser|openLocalUsers|openCustomer|saveCustomer|openBranch|saveBranch|openMoveMachine|saveMoveMachine|openCompany|saveCompany|addSaleExpense|openWarrantyForm|saveWarranty|submitWarranty|removeWarranty|setFiveEqualRates|openFifthShare|assignProfit|allocatePastLots|openTransfer|submitTransfer|openLocalUsers|changeOfflineRole)\s*\(/i; window.changeOfflineRole=async function(u){if(typeof offlineAccounts==='undefined'||cloudRole!=='admin')return;let a=offlineAccounts.find(x=>x.username===u&&x.role!=='admin');if(!a)return;const role=prompt('Nhập 1 (chỉ kho/bán) hoặc 2 (xem tất cả)',a.role==='viewer1'?'1':'2');if(role!=='1'&&role!=='2')return;a.role=role==='1'?'viewer1':'viewer2';await setLocal('accounts',offlineAccounts);openLocalUsers();toast('Đã đổi cấp quyền');}; const pwStyle=document.createElement('style');pwStyle.textContent='body.viewer #overlay form.mcc-password-form{display:block!important}';document.head.appendChild(pwStyle);window.MCC_UPGRADE_READY=true; })();