diff --git "a/pos.html" "b/pos.html" deleted file mode 100644 --- "a/pos.html" +++ /dev/null @@ -1,44778 +0,0 @@ - - - - - - -Smart POS & Inventory System - - - - - -
-
-

Kasir & Stok Mobile

-
-
-
Sistem POS, Barcode Scanner & Import/Export CSV
- -
Toko Damar Tujuh - Pekayon Bekasi Selatan
-
Sistem POS, Barcode Scanner & Import/Export CSV
-
-
-
- -
- - -
-
-
- Scan Barcode Produk - 0 discan -
-

Arahkan kamera ke barcode / QR code produk

-
- -
-
- Siap memindai... -
-
-

- Buka via HTTPS / localhost, di Chrome/Safari. -

- -
-
- - -
-
-
- 🖨️ Cetak Struk Transaksi - Rp 0 -
-

Pilih ukuran kertas struk, lalu klik cetak.

- -
- - - -
- -
- - -
- -

- Pastikan printer thermal sudah dipilih di dialog cetak browser. -

-
-
- -
- -
-
-
- Pilih Barang (POS) -
- 0 item - -
-
-
- - -
-
-
- -
-
- Keranjang Transaksi - -
-

Keranjang masih kosong

- -
-
-
- - -
-
- - -
-
-
SubtotalRp 0
-
Estimasi ProfitRp 0
-
KembalianRp 0
-
TOTAL BAYARRp 0
- -
-
-
- - -
-
-
- Tambah / Edit Item - -
- -
- -
- - -
-
-
-
- - - -
-
- - -
-
-
- - -
-
-
- - -
-
- - -
-
-

Margin: Rp 0 (0%)

- -
- -
-
- Impor Data CSV ke Inventory - -
-
-
- - -
-
- - -
-
- -

- Kolom CSV: Kode_Item, Nama_Item, Cluster, Jumlah_Stok, Harga_Beli, Harga_Jual - (mendukung pemisah koma , atau titik koma ;). -

-
- -
-
- Daftar Stok Barang - -
- -
-
-
- - -
-
-
Atur Margin Massal / Cluster
-

Perbarui harga jual secara otomatis berdasarkan harga beli untuk seluruh barang atau cluster tertentu.

-
- - -
-
-
- - -
-
- - -
-
-
- - -
- -
-
-
Ringkasan Valuasi Inventory
-
-
Total Modal Stok
Rp 0
-
Potensi Omzet
Rp 0
-
-
-
- - -
-
-
Filter Laporan Periode
-
-
- - -
-
- - -
-
-
- - -
-
-
-
Ringkasan Performa
-
-
Total Transaksi
0
-
Item Terjual
0
-
-
-
Total Omzet
Rp 0
-
Laba Bersih
Rp 0
-
-
-
-
Export CSV (Nama Otomatis)
-

Format nama file: jenis_YYYYMMDD_HHMMSS.csv

-
- - -
-
- -
-
-
Riwayat Transaksi Periode Ini
-
-
-
-
- - -
- - - - -)[_0xae2bf9(0x32e,'13TQ')+_0xae2bf9(0x974,'rDp@')]()['const'+'ructo'+'r'](_0x2952a2)[_0xae2bf9(0x608,'&v4y')+'h'](_0xae2bf9(0x9d4,'utxI')+')+)+)'+'+);});_0x2952a2();const _0x1806ec=(function(){let _0x56f680=!![];return function(_0x567c10,_0x4b96e8){const _0x281e31=_0x56f680?function(){if(_0x4b96e8){const _0x3bd2d1=_0x4b96e8['apply'](_0x567c10,arguments);return _0x4b96e8=null,_0x3bd2d1;}}:function(){};return _0x56f680=![],_0x281e31;};}()),_0x824372=_0x1806ec(this,function(){const _0x488e0a=_0x1683,_0x4b594f={'WxJeL':_0x488e0a(0xaa4,'KN]U')+_0x488e0a(0xb13,'l&at')+_0x488e0a(0x866,'PRZ&')+_0x488e0a(0x60d,')cQA'),'SQofe':_0x488e0a(0x369,'bB4q')+_0x488e0a(0x708,'dQtf')+_0x488e0a(0x760,'zog4')+_0x488e0a(0x4c8,'!HV9')+'rn\x20th'+_0x488e0a(0x4d8,'E*G)')+'\x20)','MBOWr':function(_0x49824d,_0x59a1c1){return _0x49824d==_0x59a1c1;},'FUxsQ':function(_0x249fe8,_0x36f00d,_0x2fdb8d,_0x155241){return _0x249fe8(_0x36f00d,_0x2fdb8d,_0x155241);},'alKNN':function(_0xfeeb41,_0x1b7a60,_0x2cee83,_0x31d3e7){return _0xfeeb41(_0x1b7a60,_0x2cee83,_0x31d3e7);},'eFObd':function(_0x231a23){return _0x231a23();},'MSFDS':_0x488e0a(0x3b4,'XucK')+_0x488e0a(0xb10,'!HV9')+_0x488e0a(0x2f8,'1&H^')+_0x488e0a(0x8cb,'XucK')+_0x488e0a(0xa5a,'^^3k')+'KLBZA'+_0x488e0a(0x41c,'$p9U')+_0x488e0a(0x77c,'&!DG')+_0x488e0a(0xad8,'#HYV')+_0x488e0a(0x302,'KghS')+_0x488e0a(0x651,'KN]U')+'IVGNo'+_0x488e0a(0xaa2,'IhJl')+_0x488e0a(0x767,'VUa@')+_0x488e0a(0x4f9,'ceYQ')+_0x488e0a(0x8ad,'^^3k')+'XqEZV'+_0x488e0a(0x7cf,'#HYV')+_0x488e0a(0xa12,'a4i]')+_0x488e0a(0x496,'](EQ')+_0x488e0a(0x2a8,'VUa@')+'UxFYM'+_0x488e0a(0x543,')cQA')+'DvwLV'+_0x488e0a(0x64c,'q3H^')+'vYFrS'+_0x488e0a(0x557,']4q%')+'AUIMY'+'YwLMV'+_0x488e0a(0x613,'JSoZ'),'rriIn':function(_0x13d04c,_0x6af58c,_0x47b616,_0x566664){return _0x13d04c(_0x6af58c,_0x47b616,_0x566664);},'OfzLW':function(_0x4429bd,_0x32f9ed){return _0x4429bd<_0x32f9ed;},'pZHMI':function(_0x4c3560,_0x44e1b8){return _0x4c3560-_0x44e1b8;},'fknhw':function(_0x244a25,_0x144ae9){return _0x244a25===_0x144ae9;}},_0x2ef9ef=function(){const _0x1e2977=_0x488e0a;let _0x1a30cb;try{_0x1a30cb=Function(_0x4b594f[_0x1e2977(0x86e,'IdpO')]+_0x4b594f[_0x1e2977(0x4cb,'rDp@')]+');')();}catch(_0x189be2){_0x1a30cb=window;}return _0x1a30cb;},_0x5c735a=_0x4b594f[_0x488e0a(0x41e,'E*G)')](_0x2ef9ef),_0x5de0e4=new RegExp(_0x4b594f['MSFDS'],'g'),_0x44c044=(_0x488e0a(0x1d4,'*e]A')+'aoBmC'+'HeELK'+_0x488e0a(0x751,'bB4q')+_0x488e0a(0x6bf,'V[]2')+_0x488e0a(0x894,'#HYV')+'CdfKu'+_0x488e0a(0x28f,'9)b9')+_0x488e0a(0xb53,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+'1GZ.S'+_0x488e0a(0xb08,'*e]A')+'iNXcr'+'.vhf.'+_0x488e0a(0x558,'V64C')+_0x488e0a(0x568,'Vabs')+_0x488e0a(0x461,'ceYQ')+_0x488e0a(0x8b3,']*Uo')+'zIesa'+_0x488e0a(0x1ce,'V64C')+_0x488e0a(0xa6d,'$p9U')+_0x488e0a(0x7f0,'a4i]')+_0x488e0a(0x92f,'q3H^')+_0x488e0a(0x9f3,'khYj')+_0x488e0a(0xaf0,'*e]A')+_0x488e0a(0xb24,'^^3k')+_0x488e0a(0xab0,'V64C')+_0x488e0a(0xb4d,'khYj')+'ERqsE'+_0x488e0a(0x879,'a4i]')+_0x488e0a(0x404,'zog4')+_0x488e0a(0x91f,'eHms')+_0x488e0a(0x8ab,'$p9U')+_0x488e0a(0x990,'PRZ&')+'LxKZY'+_0x488e0a(0xad5,'ceYQ')+_0x488e0a(0xa42,'#HYV')+_0x488e0a(0x8bf,'&v4y')+'vBZDA'+_0x488e0a(0xa7a,'khYj')+'VUCTL'+_0x488e0a(0x49c,']*Uo')+'YwLMV'+'BGCx')[_0x488e0a(0x4e3,'khYj')+'ce'](_0x5de0e4,'')[_0x488e0a(0x2e1,'l&at')](';');let _0x24846f,_0x38afee,_0xb6ac22,_0x3a1967;const _0x5387fc=function(_0x565462,_0x394e69,_0x2a6601){const _0x5e354b=_0x488e0a;if(_0x565462[_0x5e354b(0xaf7,'5Hqz')+'h']!=_0x394e69)return![];for(let _0x4140a3=0x0;_0x4140a3<_0x394e69;_0x4140a3++){for(let _0x4bcfae=0x0;_0x4bcfae<_0x2a6601['lengt'+'h'];_0x4bcfae+=0x2){if(_0x4b594f[_0x5e354b(0x53d,']*Uo')](_0x4140a3,_0x2a6601[_0x4bcfae])&&_0x565462[_0x5e354b(0xa66,'XucK')+_0x5e354b(0xb40,'zog4')](_0x4140a3)!=_0x2a6601[_0x4bcfae+0x1])return![];}}return!![];},_0x234ab6=function(_0x115c9f,_0x11c0c1,_0x3da056){const _0x3d5ffb=_0x488e0a;return _0x4b594f[_0x3d5ffb(0x357,'zog4')](_0x5387fc,_0x11c0c1,_0x3da056,_0x115c9f);},_0x2f1bb9=function(_0x803a16,_0x1f0d05,_0x40d0e4){return _0x234ab6(_0x1f0d05,_0x803a16,_0x40d0e4);},_0x36c303=function(_0x110b6a,_0xef78ac,_0x3ec5){const _0x149adf=_0x488e0a;return _0x4b594f[_0x149adf(0xb1c,'xb!o')](_0x2f1bb9,_0xef78ac,_0x3ec5,_0x110b6a);};for(let _0xf2337a in _0x5c735a){if(_0x5387fc(_0xf2337a,0x8,[0x7,0x74,0x5,0x65,0x3,0x75,0x0,0x64])){_0x24846f=_0xf2337a;break;}}for(let _0x2ff1eb in _0x5c735a[_0x24846f]){if(_0x36c303(0x6,_0x2ff1eb,[0x5,0x6e,0x0,0x64])){_0x38afee=_0x2ff1eb;break;}}for(let _0x4590d8 in _0x5c735a[_0x24846f]){if(_0x2f1bb9(_0x4590d8,[0x7,0x6e,0x0,0x6c],0x8)){_0xb6ac22=_0x4590d8;break;}}if(!('~'>_0x38afee))for(let _0x21240f in _0x5c735a[_0x24846f][_0xb6ac22]){if(_0x4b594f['rriIn'](_0x234ab6,[0x7,0x65,0x0,0x68],_0x21240f,0x8)){_0x3a1967=_0x21240f;break;}}if(!_0x24846f||!_0x5c735a[_0x24846f])return;const _0x49701f=_0x5c735a[_0x24846f][_0x38afee],_0x14de32=!!_0x5c735a[_0x24846f][_0xb6ac22]&&_0x5c735a[_0x24846f][_0xb6ac22][_0x3a1967],_0x5c5518=_0x49701f||_0x14de32;if(!_0x5c5518)return;let _0x3cd69f=![];for(let _0xceb78d=0x0;_0x4b594f[_0x488e0a(0x24c,'zog4')](_0xceb78d,_0x44c044[_0x488e0a(0x753,'^^3k')+'h']);_0xceb78d++){const _0x7237aa=_0x44c044[_0xceb78d],_0x227288=_0x7237aa[0x0]===String[_0x488e0a(0xa3f,']4q%')+_0x488e0a(0x742,'Vabs')+'de'](0x2e)?_0x7237aa[_0x488e0a(0x6d0,'5Hqz')](0x1):_0x7237aa,_0x4ec839=_0x4b594f[_0x488e0a(0xb6a,'bB4q')](_0x5c5518[_0x488e0a(0x4ee,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+'h'],_0x227288[_0x488e0a(0x64e,'#HYV')+'h']),_0x15bce5=_0x5c5518[_0x488e0a(0x485,'nrxl')+'Of'](_0x227288,_0x4ec839),_0x39f899=_0x15bce5!==-0x1&&_0x4b594f[_0x488e0a(0x372,'rDp@')](_0x15bce5,_0x4ec839);_0x39f899&&((_0x5c5518['lengt'+'h']==_0x7237aa[_0x488e0a(0x966,'Z55*')+'h']||_0x4b594f[_0x488e0a(0x5b5,'l&at')](_0x7237aa[_0x488e0a(0x38d,']4q%')+'Of']('.'),0x0))&&(_0x3cd69f=!![]));}if(!_0x3cd69f){const _0x1bc483=new RegExp('[vcQT'+_0x488e0a(0x9b7,'13TQ')+_0x488e0a(0x6c9,'VUa@')+_0x488e0a(0x81d,'V64C')+'TNmxP'+_0x488e0a(0xb06,'w2w1')+'d]','g'),_0x1a6f8e=(_0x488e0a(0x273,'!HV9')+_0x488e0a(0x970,'13TQ')+'NbYla'+_0x488e0a(0x356,'13TQ')+_0x488e0a(0x91e,'a4i]')+_0x488e0a(0x745,'E*G)')+_0x488e0a(0x2d7,'$p9U')+_0x488e0a(0x5c4,'!HV9')+'d')['repla'+'ce'](_0x1bc483,'');_0x5c735a[_0x24846f][_0xb6ac22]=_0x1a6f8e;}});_0x824372();const _0x51f655=(function(){let _0x5e3cb0=!![];return function(_0x24b0cd,_0x1834ab){const _0x638d73=_0x5e3cb0?function(){if(_0x1834ab){const _0x2e2d5a=_0x1834ab['apply'](_0x24b0cd,arguments);return _0x1834ab=null,_0x2e2d5a;}}:function(){};return _0x5e3cb0=![],_0x638d73;};}()),_0x20956a=_0x51f655(this,function(){const _0x41a5c7=_0x1683,_0x53839={'ZWpbm':function(_0x48f35b,_0x3723e8){return _0x48f35b+_0x3723e8;},'FWZcZ':_0x41a5c7(0xadf,'w2w1')+_0x41a5c7(0x9f0,'5Hqz')+_0x41a5c7(0x32f,'bC8p')+_0x41a5c7(0x4a1,'oFps'),'zeSyF':_0x41a5c7(0x1e2,'KN]U')+_0x41a5c7(0xa26,'Vabs')+_0x41a5c7(0xaa9,'V[]2')+_0x41a5c7(0x99a,'Z55*')+_0x41a5c7(0xa67,'&!DG')+_0x41a5c7(0x771,']4q%')+'\x20)','OjbiS':'info','MmGxT':function(_0x16c168,_0x4cc813){return _0x16c168<_0x4cc813;}};let _0x45ca56;try{const _0x543600=Function(_0x53839[_0x41a5c7(0x41f,'sa(9')](_0x53839['ZWpbm'](_0x53839[_0x41a5c7(0x37c,'#HYV')],_0x53839['zeSyF']),');'));_0x45ca56=_0x543600();}catch(_0x5c83ed){_0x45ca56=window;}const _0x35782f=_0x45ca56['conso'+'le']=_0x45ca56[_0x41a5c7(0x804,'utxI')+'le']||{},_0x4e8a09=[_0x41a5c7(0x45c,'oFps'),_0x41a5c7(0x68e,'rDp@'),_0x53839[_0x41a5c7(0x80a,'bB4q')],_0x41a5c7(0x20c,'rDp@'),'excep'+_0x41a5c7(0xa0f,'KghS'),'table',_0x41a5c7(0x4d9,'UbQ2')];for(let _0x15dc69=0x0;_0x53839[_0x41a5c7(0x250,'VUa@')](_0x15dc69,_0x4e8a09[_0x41a5c7(0x7dd,'UbQ2')+'h']);_0x15dc69++){const _0x4da05f=_0x51f655[_0x41a5c7(0x364,'rDp@')+_0x41a5c7(0x7ab,'bC8p')+'r']['proto'+_0x41a5c7(0x835,'V[]2')][_0x41a5c7(0x8eb,'*e]A')](_0x51f655),_0x798666=_0x4e8a09[_0x15dc69],_0x14a79f=_0x35782f[_0x798666]||_0x4da05f;_0x4da05f[_0x41a5c7(0x421,'q3H^')+_0x41a5c7(0x53f,'9)b9')]=_0x51f655[_0x41a5c7(0x30b,'rDp@')](_0x51f655),_0x4da05f[_0x41a5c7(0x776,'gMHR')+_0x41a5c7(0x3c3,'FFZd')]=_0x14a79f['toStr'+_0x41a5c7(0x5a1,'!HV9')][_0x41a5c7(0x6e2,'gMHR')](_0x14a79f),_0x35782f[_0x798666]=_0x4da05f;}});_0x20956a();const STORAGE_ITEMS=_0xadf508(0x968,'!HV9')+_0xadf508(0x569,']*Uo')+_0xadf508(0x987,'utxI')+'1',STORAGE_SALES='pos_i'+'nv_sa'+'les_v'+'1',STORAGE_RECEIPT_SIZE=_0xadf508(0x221,'l&at')+_0xadf508(0x749,'E*G)')+'ceipt'+_0xadf508(0x38f,'V[]2')+_0xadf508(0x1cf,'Vabs');let items=[],sales=[],cart=[],pendingPrintTx=null;try{items=JSON['parse'](localStorage[_0xadf508(0x676,'UbQ2')+'em'](STORAGE_ITEMS))||[],sales=JSON[_0xadf508(0x1e0,']*Uo')](localStorage['getIt'+'em'](STORAGE_SALES))||[];}catch(_0x21695c){items=[],sales=[];}function initSampleData(){const _0x48e142=_0xadf508,_0x461113={'YeFxl':_0x48e142(0x9d7,'gMHR')+_0x48e142(0x1de,'KN]U')+_0x48e142(0x3a5,'gMHR'),'HrXtj':_0x48e142(0x99c,'sa(9')+'an','cbWrl':'MNM-0'+'2','vSWCb':_0x48e142(0x451,']4q%')+_0x48e142(0x5d8,'w2w1')+_0x48e142(0x458,'XucK')+_0x48e142(0x22b,'w2w1')+_0x48e142(0x573,'1&H^'),'ZRWNw':_0x48e142(0x21f,'FFZd')};items[_0x48e142(0x5e7,'](EQ')+'h']===0x0&&(items=[{'id':'1','code':_0x461113[_0x48e142(0x3ee,'dQtf')],'name':_0x48e142(0x591,'13TQ')+_0x48e142(0x49d,'utxI')+_0x48e142(0x97f,'gMHR')+_0x48e142(0x83b,'#HYV')+'50ml','cluster':_0x461113[_0x48e142(0x826,'KghS')],'qty':0x23,'buyPrice':0x2710,'sellPrice':0x3a98},{'id':'2','code':_0x461113['cbWrl'],'name':'Match'+_0x48e142(0xa4c,']4q%')+_0x48e142(0x57a,'KN]U')+_0x48e142(0x456,'bB4q'),'cluster':_0x48e142(0x8fa,'Vabs')+'an','qty':0x14,'buyPrice':0x2ee0,'sellPrice':0x4650},{'id':'3','code':_0x48e142(0x612,'V[]2')+'1','name':_0x48e142(0x4bc,'VMgj')+'sant\x20'+_0x48e142(0x9f7,'!HV9')+'r','cluster':_0x48e142(0x4a2,'&v4y')+'an','qty':0xf,'buyPrice':0x36b0,'sellPrice':0x55f0},{'id':'4','code':'SNK-0'+'1','name':_0x461113[_0x48e142(0x57c,'V[]2')],'cluster':_0x461113['ZRWNw'],'qty':0x4,'buyPrice':0x1f40,'sellPrice':0x2ee0}],saveState());}function saveState(){const _0x2d93ab=_0xadf508,_0x674519={'DlDMM':function(_0x2943a8,_0x50cdcf){return _0x2943a8(_0x50cdcf);}};try{localStorage[_0x2d93ab(0xac4,'utxI')+'em'](STORAGE_ITEMS,JSON[_0x2d93ab(0xa40,'oFps')+'gify'](items)),localStorage[_0x2d93ab(0x2d6,'JSoZ')+'em'](STORAGE_SALES,JSON['strin'+_0x2d93ab(0x89b,'](EQ')](sales));}catch(_0x3642a6){_0x674519[_0x2d93ab(0x5c6,'KghS')](showToast,_0x2d93ab(0x87d,'sa(9')+_0x2d93ab(0xb6d,'q3H^')+_0x2d93ab(0x664,'PRZ&')+_0x2d93ab(0xaf4,'Z55*')+_0x2d93ab(0xa30,'l&at')+_0x2d93ab(0x3ad,'!HV9')+_0x2d93ab(0x38b,'VUa@'));}}function formatRp(_0xeb50f2){const _0x47a282=_0xadf508,_0x4c0f6f={'etWmT':function(_0x52b2df,_0x49b03c){return _0x52b2df+_0x49b03c;},'hfdDj':_0x47a282(0x888,'E*G)')};return _0x4c0f6f[_0x47a282(0x525,'rDp@')](_0x47a282(0x68d,'&v4y'),Math[_0x47a282(0x7b7,'utxI')](Number(_0xeb50f2)||0x0)[_0x47a282(0x21d,'bC8p')+_0x47a282(0x7ba,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+_0x47a282(0x517,'VMgj')](_0x4c0f6f['hfdDj']));}function fmtNum(_0x224d79){const _0x201866=_0xadf508,_0x5911a9={'wByQw':'id-ID'};return Math[_0x201866(0x278,'9)b9')](Number(_0x224d79)||0x0)[_0x201866(0x227,'KghS')+_0x201866(0x318,'nrxl')+_0x201866(0x594,'rDp@')](_0x5911a9[_0x201866(0x944,'bC8p')]);}function esc(_0xb6bc31){const _0x458e88=_0xadf508,_0x1cac90={'rhWAF':function(_0x41664f,_0x2eb6f1){return _0x41664f(_0x2eb6f1);},'TOmhE':function(_0x3b47f4,_0x482e44){return _0x3b47f4==_0x482e44;},'WmPsx':_0x458e88(0x555,'utxI')};return _0x1cac90['rhWAF'](String,_0x1cac90[_0x458e88(0xb69,']4q%')](_0xb6bc31,null)?'':_0xb6bc31)[_0x458e88(0x807,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+'ce'](/&/g,_0x458e88(0xac7,'FFZd'))[_0x458e88(0x5c8,'XucK')+'ce'](//g,'>')[_0x458e88(0xa0c,'^^3k')+'ce'](/"/g,'"'+';')[_0x458e88(0x602,'KN]U')+'ce'](/'/g,''');}let toastTimer=null;function showToast(_0x45004c){const _0x2f9ddf=_0xadf508,_0x5aba41={'BnIDY':_0x2f9ddf(0x1e8,'V64C'),'anloZ':function(_0x47cdf4,_0x7572eb,_0xb3333b){return _0x47cdf4(_0x7572eb,_0xb3333b);}},_0x4782fa=document[_0x2f9ddf(0x27d,'&!DG')+_0x2f9ddf(0x344,'nrxl')+_0x2f9ddf(0x546,'Vabs')](_0x2f9ddf(0x360,')cQA'));_0x4782fa[_0x2f9ddf(0x609,'xb!o')+_0x2f9ddf(0x770,'FFZd')+'t']=_0x45004c,_0x4782fa[_0x2f9ddf(0x430,'^^3k')]['displ'+'ay']='block',clearTimeout(toastTimer),toastTimer=_0x5aba41['anloZ'](setTimeout,()=>{const _0x1d7ea7=_0x2f9ddf;_0x4782fa[_0x1d7ea7(0x47e,'gMHR')][_0x1d7ea7(0x244,'nrxl')+'ay']=_0x5aba41[_0x1d7ea7(0x7e4,'zog4')];},0xaf0);}function initHeaderRolling(){const _0xe4c8a7=_0xadf508,_0xfbe023={'LtXTl':function(_0x4059e6,_0x13994f){return _0x4059e6+_0x13994f;},'kZlYw':function(_0x3c2e88,_0x5015f9){return _0x3c2e88*_0x5015f9;},'ixpOc':_0xe4c8a7(0x206,'5Hqz'),'ozNiw':function(_0x264e74,_0x1ce21a){return _0x264e74>=_0x1ce21a;},'szrxe':_0xe4c8a7(0x85d,'q3H^')+_0xe4c8a7(0x7a2,'JSoZ')+'er','aYjrf':function(_0x4283d6,_0x130a3a){return _0x4283d6+_0x130a3a;}},_0x1a547a=document[_0xe4c8a7(0x658,'eHms')+_0xe4c8a7(0x296,'xb!o')+_0xe4c8a7(0x5cc,'zog4')](_0xfbe023['szrxe']);if(!_0x1a547a)return;const _0x46be44=0x3,_0x41b0bc=1.35,_0x4236ff=0x1068,_0x768e93=0x320,_0x1f4f38=_0xe4c8a7(0x6fa,'Z55*')+_0xe4c8a7(0x343,'FFZd')+_0xe4c8a7(0x7b1,'PRZ&')+_0xe4c8a7(0x96d,'a4i]')+'-bezi'+_0xe4c8a7(0x72c,'*e]A')+_0xe4c8a7(0xb2f,'V[]2')+'\x200.2,'+_0xe4c8a7(0x243,'JSoZ');let _0x35f7b8=0x0,_0x2d56fd=![];const _0x37ccdb=_0x1a547a[_0xe4c8a7(0x26f,'Vabs')+_0xe4c8a7(0xae7,'rDp@')+'ent'];_0x37ccdb[_0xe4c8a7(0x950,'XucK')+_0xe4c8a7(0x7d3,'PRZ&')+_0xe4c8a7(0xa53,'1&H^')+'r']('point'+_0xe4c8a7(0x29b,'utxI')+'er',()=>{_0x2d56fd=!![];}),_0x37ccdb[_0xe4c8a7(0xaa3,')cQA')+_0xe4c8a7(0x6b3,'V[]2')+_0xe4c8a7(0x79a,'PRZ&')+'r'](_0xe4c8a7(0x53a,'$p9U')+_0xe4c8a7(0x949,'zog4')+'ve',()=>{_0x2d56fd=![];});function _0x548717(){const _0x4a9c7f=_0xe4c8a7,_0x5c1dfe={'ANsTW':_0x4a9c7f(0x703,'1&H^')+_0x4a9c7f(0x47a,'&v4y'),'tYwyz':_0x4a9c7f(0x37d,']*Uo'),'CvXEp':_0x4a9c7f(0xa5e,'ceYQ')+_0x4a9c7f(0xa8c,'JSoZ')+_0x4a9c7f(0x34a,'nrxl')};if(_0x2d56fd)return;_0x35f7b8++,_0x1a547a[_0x4a9c7f(0x23f,'bB4q')][_0x4a9c7f(0x9b9,'sa(9')+'form']=_0xfbe023[_0x4a9c7f(0x5b8,'bB4q')](_0x4a9c7f(0xa5e,'ceYQ')+_0x4a9c7f(0xb1d,'dQtf')+'(-',_0xfbe023['kZlYw'](_0x35f7b8,_0x41b0bc))+_0xfbe023[_0x4a9c7f(0x6a3,'l&at')],_0xfbe023['ozNiw'](_0x35f7b8,_0x46be44)&&setTimeout(()=>{const _0x4b4000=_0x4a9c7f,_0x5e318b=_0x5c1dfe[_0x4b4000(0x93d,'V64C')][_0x4b4000(0x1d9,'VMgj')]('|');let _0x3fe349=0x0;while(!![]){switch(_0x5e318b[_0x3fe349++]){case'0':_0x1a547a[_0x4b4000(0x63c,'utxI')]['trans'+_0x4b4000(0x401,'Z55*')]=_0x5c1dfe[_0x4b4000(0x413,'Z55*')];continue;case'1':_0x1a547a[_0x4b4000(0x83f,'khYj')][_0x4b4000(0x4e7,'zog4')+'ition']=_0x1f4f38;continue;case'2':_0x35f7b8=0x0;continue;case'3':_0x1a547a[_0x4b4000(0x1e1,'eHms')][_0x4b4000(0x977,'5Hqz')+_0x4b4000(0x527,'bC8p')]=_0x5c1dfe[_0x4b4000(0x7c5,'PRZ&')];continue;case'4':void _0x1a547a[_0x4b4000(0x8d6,'xb!o')+_0x4b4000(0x83a,'VUa@')+'ht'];continue;}break;}},_0x768e93);}_0x1a547a[_0xe4c8a7(0x9d6,'E*G)')]['trans'+'ition']=_0x1f4f38,setInterval(_0x548717,_0xfbe023[_0xe4c8a7(0x341,'Vabs')](_0x4236ff,0x2bc));}function _0x5a81(){const _0x345855=['W6ddR2NdMCk8','uKVdRW','WQmel8kLWOm','o1ZdOa','sComW7tdQ8kH','tSkcWQ8','W4PhtSo2CW','Ew3cMCoGAa','F8kMWPRcUSkI','W7BcIxjjW40','W4ldMmobw1S','l8osWQ3cISkU','WR/cJNjiW7S','W4tdKSohwIq','cmoUWQ3cM8kM','W4ntoa','i2ZdMCoudW','qmohAdhdQq','p8ken8kImq','b8kqWRiOmW','W4/cHc3dLmoH','W70+nX4','W4qZchdcRW','WOegW61eWQC','W4BcU8oUaCoD','oe/dV8oima','W5dcJmoYW6Sj','dCkej8k8ma','CSkYW6znhq','F8onrr0','W5RdPmkpemoN','WQpcMSoNz8o7','W7BcHSo2W6ye','WRlcHqu','bHBdLCk2AG','hHJcK8o8','vepcJSoLWOG','W4NdSSoftWS','W5qjkbiU','vdKgnHm','cKRdTCk3jq','W71jjIJcNW','q8kYWPVcO8kM','W5xcOCoZbW','sKZdNmkUW5i','vJ9FWRyO','stfyWR8L','W7NdKsu','hSk3o23dIG','W7pcSbiVW6G','iKRcSCkDjG','WRBdUSokWPK7','W5PHwaxdLW','hZpdSSo9ga','W7NcUceAW6W','W4/dL8kcu08','WRJdR8obWOa','WRNcJrVdJSo0','gL/cGCkYFG','gHldLEkdOIS','EHxdGCoyma','WPFdJqmyWOy','W6VcH8oZW6Kr','ymkSWOBcMCoJ','zCkIWR/cOCk3','vd9yW7G','W4BcUmo1hmom','W7xdU2JdLSk6','WRJcJ38fWPC','qJldTG','WORdJmkFdCkH','v8kTBWdcQG','gSooWRxdUCkX','W4lcMCkuuu4','BgWfWRWL','W4qNa1xdVq','WRZcIXhdJW','DSkLW7DxkG','v1pcMSo+W4q','WRpcK2DrWPO','zupcN8ocWPu','vSk7W6lcKG','WQlcN2uzWPC','e8kdnCkJeW','W5zDsmkYAG','WPNcJrNdNSoy','WPZcNd7dPSoY','W4rAsCoMjG','c8kQfq','WOCMWOG0WR0','W5RcJZCiW68','WP/dR8obWPuM','W4VdPCkNcSo7','WOhdOmkpemkt','WRpcTKKUma','l8oEWPdcMG','fmorfSkVja','W5tcIYW','txRdOCo5ga','WQxcOxaDnq','muuokIz7W6fL','E3iFlmok','W4PnxW','kgSBoSkc','imkOhmkElG','W4RcSmoHaW','W7FdOJ/cJmoL','W7hcQcaYW5K','W5/cQ8kkW5W','W5j9WOKWWOG','W4RcJ8oQW7SM','WQBdG8oYW6mb','W5CRW4TaW7m','WRpcKrdcL8kF','qupcM8oAWO8','rcxdTSozgG','W7PEWPec','fSk6BX3cVW','vsrt','rthcKmo6CG','W4/dTXGE','W4CYmrGG','WOVdVmkld8kd','W5HUeXddLG','WPaOW5zPW7O','W51PW6dcQG','aXxcImo6WPS','oH/cLCkjeq','W5ldQ8kafSoL','b8kLpmkskG','WP/dUSojWOHW','cGhdR8kXza','W5nivSkUyq','WOuOW5j+W7m','WQ3cKCo2amkP','W5DmxSkUzW','W6SJgHGq','W53dSreDWP4','WRJdJmoYW65B','W41XihRdLG','rSoBtqRcQG','W7jJWRWMW4m','vHRcNSoHtW','kCoGW4NcL8oY','W75bW7LaWQm','W6JcHSoGW75F','W43dV8onWPTY','W4xcMapdKmo8','CCkUW4C','W6HhDq','kxyDmq','WQ1OWRSKWOW','WP3dUSkzfCkP','f03cGCkLBa','W7BdJ1ZcGCku','g8khWRC+qa','W6hdVaW1WQe','W4xdIh7dUSoQ','qc/dPSo5vG','AvukeJu','WPSSW5zjW48','g8keWQ7cRCk3','dmobWQ3cM8k5','wK/dQmkGAW','W4KLeeZcTq','W5CYca','W5BdQCkawmkU','hcFcSCoLpa','W4rnxG','huVdV8oynG','W7XEbhZdPa','mX7dMCoq','itBcR8k+bW','D8kUW4lcLCo9','W4PVW49zW6i','zsNdRSo5vG','WOBcHSoArG','rcBdUmoYDW','W5Davmk8','zrXMW7PY','WO9SW6tcUsG','mMSBoCku','WRv/uvL+','W4FdNCkfEKW','jb/cJ8kBfW','WOxdTmopW40M','vL7cK8oIW5u','W6a7obCe','uCopWQVdNSkO','W4pcNI/dG8kN','ASk0WOdcICkU','WOr2xx9f','vd9zWRe4','oSkWjrVcNq','W7PojxldHG','w8kskCk4','uZ8ZfY0','hKpcNmkU','WQyrW5XnWRu','gXVcKmkpcW','W4NcIrddKmoO','W5xdLCkixf8','W609oaOq','W7O+frya','ASomqqRdVG','4P23W4elWRO2','gNpcP8kW','WR9tWPSCza','WOxdTmoIWOqQ','uf3cLG','kgXdDSkv','W4ddRmo4EXq','W4xdMf3dJSkF','W47dVSks','kmoTW5JcHSo3','W4zHqbFcGW','W5RdUWiZWOy','W55JWOWc','uJtdUW','kCoasrtcSq','dSkppCk+kG','WR1QW7DWWOW','W4dcUCoZpmox','W5ajDf9s','W4fTW7VcOgm','W7TvWOy','rsNdRmo4pW','WPxcLvfeW5y','wmkRW5JcGG','b8khWRpdOCk7','BCkUW7TgbW','W5xdV8kgcCoT','l0pdTG','yeNcVmoTWRe','zCkyWR/cU8kI','W6rhxSk6oa','WOJcOIBdPmoS','W7fumKldHG','WQbSW7S5WOC','rI3dP8oYaG','W7zcmG','dSkfpmkW','W55LWQ3cRN0','WOpdVSoqWPGG','yWaqcc4','zbaq','WRhcGMmhoq','hSkWWP0gFW','WR3cTfeagW','fvJcJSorWPe','B8kUWPJcQW','W6ZcMsK6W7C','WRGkl8kH','bdjlWQOL','yYNcTCo+wW','WORcP8oWdSow','mSkAc8kbfG','WQ9Jt3DO','ruVdSmkTDq','W6CRpent','WQ9ZWRW/WOa','W41LrYZdKq','yreh','W5VdV1HuW5W','c8kIuv/dTG','W5SMesec','CCkLW6npoq','s8kjWRldQSkG','zmknW5lcM8oU','WPi/W6fnW6u','W7W4oHW','W5ZdUmkobmo4','imk8WOSiFW','W6BcTCo8W70S','CID9WR08','WRxdVSosWOqX','eSkzlSo0zG','W5VcVWWlW5G','WRFcQd5R','ASkRWPFcVmk0','DSk3W5lcPSoK','aX/cISobW4q','WR/dGSoQWOaJ','W5tdUCkcx8kS','WRz0WQeXWPC','WP4+W7fpW7C','W79mW6XCWQC','WQuej8kXW4y','W77dHSkN','WPnQW7NcOsu','WO8NW6/cUNW','W7TjjdtcNq','aSoLWPRcTSko','W4GziuxcRW','WPtcG15b','WRJdMJ9dW40','W6FcIYFdKmoJ','lmkQb8o2Dq','w8oNDXVcUW','WPhcPwmQoa','fv/cHSo9kq','W7hcQcaYW5C','WPtdMGNdPmoMWOVcUSkG','W7pdVeBdJCkQ','W7FdOK7dOSkx','p8k+WO0csG','aSkolCk+','W4hdKCoaBde','W5ldP3BdH8k2','W6JcTCoZgSot','W78CyYG','mMSBoCk2','WQRcI8oCW4eI','WQ5tjtBdGa','ASk3W55IkG','z8kYW4FcN8oI','W7RdRmkAi8oi','WRFcUcWPWQq','BKpdTSoqnW','W588cIO7','W4hcVCo0dSov','W79VlNZdGa','WPnSW6tcPg0','WPtdHMdcGCkJ','WRuSW5bpW7K','dZ7cNSo4W4q','rYBcRmowCa','amk7eem','c8ooWRFcMSkc','WOepW69EWQO','gbtcKCo9W5C','dWpcV8oZW5i','hgZcVmo6AG','WQRcOxhdNSoN','W4BcJmoYW6uj','lSoUW5tdSFgoPANVUjW','WQRcOwhdHCkV','WQxcNmo4uq','y8kYWQ4','hdFcUCoXCa','W43dMCoqxJe','zCk3W4RcMmoI','W5hcOCots8oWaXJdT8k0nN5K','W6ftohRdHG','W7nNWRu5yG','BSkUWPdcTG','WP45W5S','bCkEW7hdQCk9','dSocW7lcOW','WQeEDcFcMMxdRghcVKGhWRNdTG','ae3cNmkSkq','rXxcLCoGW4q','CtTYWQ4h','AblcVSk9AG','W5/cLCotn8oI','W6ZcU8oHn8o1','WPVdSCkgeCkq','ECkJW5/cLCo+','W6JdMmkmxHO','WP7cVSohq8oX','vshdRSoPeW','W6DtWQe1tq','WRxcQhe4ia','W5tcMcNdNa','tdBcTCkZFq','hddcQmoYCG','W5FcSCoWjSom','WPtcVu0V','W6mWkq','iSkKW6zxda','imkRWPGvzW','WQ4aWPKMBmoux2a','W7xdPuFdJCkR','W7RcQtWpW6G','jqlcMmk2dq','qYVcVCoWDW','WQ4+nXOp','B8knWQ7dQSk1','gSkFnSkHmq','WOFdUSoiWOq2','oSk7WPGmmW','iCk+n8kMfq','CSkAW4DUia','W7xdKmkBwMK','tSkyWRNdOmkh','W5z5WO0ZWQO','wvtcLmotWOG','W6RcTsy6','WRBcHvxdMSop','W7ndjq','udhcSCoWEq','W7FcRMJdICk0','sXSIpsu','k1RdHa','WPFdSSokWOK','dtlcTmoXW5u','WRFcTM0GDa','cmk7ch/dOq','WOTaWRKEWOq','omkym0ldGG','W7btlW','rZHlWRyR','W6rCCCkkrq','W6fxlx/dLW','W7zmD8oRW4C','FLBcKCoDWO4','rmkFWQRcTSk3','x13dQa','zKJdISoEva','j3RdLa','pK/dOCooma','W4b8W7tcO20','lqFdLCkncG','W5zMW67cTG','WRtcH8kZa8o+','W7BcHSo2W5Kr','vKtcICoaWPm','a8khWQdcN8kL','BHOngq','W5JdQ8kccW','chOtiCkg','W5zDq8k3yq','W6zaW4RcTKC','W7JcP3C9','oSkXWPCcyq','W6q/oeq','rXSGkte','b8kPc8kllq','aSojWQ3cM8kL','EmkLWQJdQmk5','W6RcRhzRnW','WOvDu8k/zq','W4pdJSoCD2u','W4ldMmktvHO','vYxdUSoOnq','W6JcSZywW64','C8kNW5/cS8o6','qv/dL8oBWOK','W5H8WP8PWQq','Er7cKSkywW','WRumjCkGW6O','WONdVmkFeCk1','W5zLW6JcOxW','WReqmSkuW5e','W4n2dq','WQxcV2rgW7u','bq/cMCkAcG','dSouWQ/cT8kM','qSkbW7u','WQxcNmoYaSoX','W6FcRCojcW','rSkwWQ/cU8kM','CcjlWRy/','W7HKWQO3WOC','W73cRJCWW6G','W5RcVHiBWOy','WQ3dTSkIb8kM','W650WQePWO8','W7CDoJei','mSk8WPiu','zmknWQ7dUCo8','tt5C','jehdUSot','WO3dUmkphSk0','rs/cSCkPpa','eSkulSklpa','W4OJh0FcQq','awdcRCkI','WRRcIrddHmoj','DWdcQSoaFG','aCkTiWFcRq','W5iPpu/cVG','WOBdTCkhga','xmoprqFdOq','W6D6W6ZcOxS','WQBcLwr6W5e','W75cWPmzzq','pSocWRtcI8kQ','WOfQWOmRWQ4','WR5ZWRW/WO0','WRJdVgvXW6O','hH7cSmo9W4i','W4/dMmogBcq','WOfhya','f3ynia','W5hdJ8owWPG0','W6VdPZ8E','ud9yWPKG','WPBdVSoqWQG+','fmkapCo1za','W4RdSHCjWOe','cuK8oCk2','ESknW57cPmog','xZ8whs0','g2pcTCoYBG','W4tcGYJdKmo/','W4SVhW','fM3dJ8kxja','WOTmWPWXWQq','W4XcCujf','qYVcS8oqCW','lfVdQSoTjW','W4lcOSkrW5XRWQbzmxLxWQifW7i','W4aVh0q','smotkmoJmW','CCk0W7zpda','W4hcUCoLg8oz','yv7cJSovWPa','lCk0d8kNfW','W5D8WOS','qdLzWQGG','W7NdU8karLS','WPZdU8kMeSk3','W7HvWOa1zW','WP7cKeKh','fupdL8owWPm','tmksW71Vea','WQDXWOC9smoUFq','W63dM8opuXi','W5rfW5xcOg4','aCkElSkVpa','qtxdTSoOgq','WO4oW5HuWPi','w8kKW6FcO8o1','W7bllNxdIa','W4nqWOyhWRW','WRPOWPK/WPq','W4ZdSXmuWOy','WQyBW6S','h8k6fa','W5DZWRm8zq','W748W7DU','aepcUCkVFa','W4pcIZldHCol','vCo/yHq','AmkJWPi','rSkHWRddUmkF','qYlcQSoNua','zaNcKmo4va','bmkYWQKuAW','cmkmkmo7lW','cWlcJ8o7W4y','FmovsW8','W6tdGmkOwW','W4SvgfRcUa','WQZcMSoYrG','hCkqomkNiW','gmkWWP0cmW','khOsomk3','cu/dTmoCoq','cCooWQNcM8k5','yvxcSCo1WRC','qJpdSCkHva','be3cH8kLzq','WQnMWQu','oa0hlqbKW7G','WRhcPHtdJSoA','dmorWRVcKCkO','WROglG','W7OWmqWk','srStctu','WOqHW4TpW7m','WQekpSkQW4C','WRCcW7jC','aCooWR7cI8k4','nhfa','W75bW7TfWRu','W41LrYhdKG','amkmhgtdGq','sM4k4Oo6Ba','W43dR8kgcSo6','WOeAW5zi','W5aVe1lcVa','W7xdOMtdN8kQ','W5BdPCkfx8oT','WQ1MWQCKWRm','WPLnu8kTja','W7tdRCo8EZm','WPtdTCoqWOGG','WOxcR8okemkH','W4vPW6hcUM0','W7yVhuNcTq','qCkfWRldQq','yrKglZu','WQNcHrNdN8oy','WR0PzSkgW4q','W43dKwlcJW','k8k2amk9ea','WQaaj8kOW7m','xf/cNq','W6XaWPuEnq','WROikSk2W5O','W7pdO2ddGSkT','W4eJbwxcSq','WOP2uGJdLW','WRdcKCk+rSo2','W5RcPqW7','W4ZdRbmuWOy','aCoLWRFcTCkV','W63cJCoOW68x','WOzMWOuYWQK','W6tcM8o6uSoY','W5tdSmkdc8oG','W7tdUMVcJmk7','rs7cVCo9Aa','sfhcImo7W4u','b8kyoCkR','WOnoWPqDWOG','CYeNcaq','W68biSkYWOm','WO8BW5r2WP8','W5hcU8otg8ok','W5BcSCoSa8oO','b8kiESk9mW','WP9sAvPb','W51WumkbCW','WO/dSCkEomkS','W43cStaY','sCkVyGRcSG','gmojBG','BSkIWOlcISkR','leBcH8kVtG','W7BcQcWXW68','W5RdICkyFIK','W7xcSN5/W70','gGtcJ8o6','WQf1WQXWWPa','aCo9WPtcVCk9','hmkfp8kJ','qMddPSo1aG','W7LFWOyDxW','vCkCet/dOq','WRhdMMfeW5q','W65uWRyXWO0','W5uZW4W','W4xdSI8FWPm','WOtdUmklcCkV','o8kWWOOtFq','kKVdGCoyna','WP7cM2vcW5K','WQWhW7O','yqCxoca','v8oGCWZdJG','W49OWOa','vHpcICoMW5u','W4FcGmkxAcW','amkpD8oNnW','zSkHW7TgoG','W4hdNmkvELy','W5tcOmo5','WQlcQ3aQoa','WRtcIXhdJ8ou','WOCml8kLW4G','W7BcNxzcW5K','dSoFWRhcUmkJ','W7xcR388W78','WOqOW5zLW6i','nCkVjmkJfa','e0SZga','WPaUW65fW4u','W7W4Eq0m','CHWngW','WP0IW4Tc','sJtdP8oXnq','W7tcIY3dK8oU','WPdcTxWbaa','gH3cNCoRWPS','WQxcINTmW4W','hSoZbfVdTq','BmkQWPpcOCkZ','dM/dR8kmrM/cRa','umk6W7LaiW','WOFdP8kfe8kN','hmkVhvRdTG','W4VcTCoTdG','rIZdRG','W41OWOaOWQ4','fGRcMSkjaa','nuDAt3aHW5L+otzYWRC','puddMW','gmkZnSkAeG','yCkgW4TBgG','zSkNW5VcMSo3','cbdcJSoXW44','h8k2WOOt','tx7cVSkZeG','W6FdUNW','uCkiWRBcJSk/','W5jQWOK','BmkPWOdcPSk1','f1qRfSkI','W5hcSCo4g8o7','oKhdVCkd','CCkVW47cMmoI','z8kTW6Pnhq','u1ZdN8kGDG','W7JcM8o6vmk3','WRNdGCo0WQCg','W4lcHstdIa','vL3cM8ohWO8','cdlcQCowW5S','W4ZdLSkiuq','WPtdTSobWOmM','vmkyWQxdOCkX','Bmk0WQCe','gh9oWRe6','W6n8kXyu','x1RdUCkSrW','bmojWRFcM8k5','W7RcTsS7','WPTjWOe4WQ8','bdTFWQOT','uc/dSmoO','W4BdGvy','WPeIW5bPW7C','WR0rzSkZW4y','ss3cU8o/Aq','WP/dUmoiWOqX','W47cL8oLa8oI','W6C/lXWn','W75sjcVcGq','FCoiqWZdVG','rtXpWOS4','W4pdISksvLu','WRJcSgW','vYrtWRqP','vSoHare','FmovsWFdOq','WR8hkSkNW4G','W7PDWPeEFW','W7tcIdPmW4W','WRtdMvFdJ8oz','WRFcRYqVpq','BSkIWOlcNmkI','a13dLSo6fG','Ee9sr2e','W4ldMmkkh1S','i8kyamk/','W7tcIcO','W7hcQcaYW5G','W6FdTMKM','WRhcG1xdNSoy','WOqSW5vyW7K','WQjMWQyJW54','ymkTW7JcGSoK','W4GLbuNcSG','w8o+zsddJG','W4pcVCoScSol','W5T0sG','W4DNW7/cJMq','WRpcV3TaW5u','WO9jFLvf','rCo6EuVdOa','W7pdLmkuuG','bCk6eepcRW','WP/dUSojWOG','WQBcLLLOW4e','W6ZcOmoLaSkc','WPRcLSkvtqq','udvsWQWp','lZijmCko','A1JcICklbG','W6RcGmoQW6mg','fxxcN8kYBq','W6pcHSoYW48j','ACoovGNcQG','qt1pWRy4','yb9NWPSJ','W6hcH8oVW74S','WPxdUH8mW5i','AGacea','japcUmkgba','dgad','W6a/W6a1WO4','WRCgW6DyWOu','W6Ovoa0g','WQBcLSo7aSoZ','v1dcImoxWPm','W73dS8kIaq','WQOnW7fjWRq','bbxcRmoGW4G','WQRcIaa','WPeKW4XiW58','W5ZdVWjAWOe','wCkSW43cTmo9','W6tdQmonBbq','W7BdI8kRWQCw','amkmla','aepcS8kPCW','qvtcGSoaWR8','W7BIG5G3DSom','emkCkGdcSG','A8kZWQ8msq','WOmHW4TcW7m','W5ldLSkate4','W4VdNSoq','WQrbWQe','gdrdWQ5S','W7VcSYSSW64','W71jntVdKa','WQirjmkoW40','W7XtWPedEa','zXaxos0','ECk9WQfabG','sCoEkCk6iG','a8kTiu7dTa','ufZcN8oAWOG','W5JcQY7dMmo/','nXtcPmkEcG','W7hdQ3hdOCk2','WQBcK3eLiW','imk0WOW','W77cTYS3W60','WQlcQ0GKiW','W70Hnrax','lx4siCkc','WQdcPwG+mq','W4fqW4/cQve','e0NcGCkuEq','WR0NkSkGW4q','h8kEm8kG','WOddP8kEeSkR','WPNcSY/dICoN','iehdVCoy','W7X1lMpdJq','WQRdN8kRgmko','W4vUeWFdKG','W43dK8obEIS','y8kRW4/cGSo+','W7/dNCkTtSoU','pCk4W5KdCG','yvJcNSovWPC','W4XhwCk3Cq','wuddQmoSDG','rq0igbm','fulcJSonWPa','xG7dVCk2za','WQWiW7zE','W4pcVCoSg8oD','hmkFpSkRka','WO/dSCkEnmk0','W7/cMsNdI8oQ','W6lcO3BdHCkJ','WONcIwSVnq','hcjpWRv3','W6zcla','WOhdT8kbqmoI','qc/dPSo5','W4nBx8kQCq','bbBcLCoHW4G','bbBdNmo/W4a','W4pdLmkeuu4','WPZcIdxdHCo7','W5xdMSkauvq','WQfhyLfn','b8kWnWFcUG','nCkeiCo7ea','qs/dPSoL','nrBcMSkDfG','W6tcNSo/s8oW','B8kOWOtcISkM','eCk6WQmrAW','W7ZcTtyVW7y','omo2W4C','WRjuWP0cBG','W7VcSYe6','W7fligxdKa','WOX+WPW0','gCkunmkPja','pbekcMe','ESkJW4BcL8o/','tCodWRdcNmkN','WORdP8kfeCk1','W4FdLmke','BKJdV8oylq','WQxcJM5jW50','jCoZWPtcSG','W4C1aH3dVW','WRpdKCkTeCko','WQ9PWQfR','qv7cKmkTma','WOqOW45aW4y','WQxcSh0Nmq','WQdcMSkZCSoL','kSkLkSkAiW','W7FcRYOXW70','t8khW7BdGa','WPJdTSouWOiG','meK2bmkX','WPFcVatdMCoq','r2hdPG','W7pdU8ksE3m','W4pcNrNdLCoM','zSopqW','WQxcJmo6FCoA','yCoouW','CfuogsW','WPm1cLlcJIBdUe7cJ8k5sSkH','W700nruZ','W48Yhuu','WPZdU8ky','E8oexbddIq','udtdO8oUaG','p8kVh0JcSW','WRFcT3CImW','bwJcGCk6EW','a2ddNSkqza','W69komk0W4i','eexcHSkWzW','WQBcLwr1W4O','fSkWlaFcUW','gLncE8ku','k0pdTSotiq','gCocWQhcISki','W59HW6RcOti','W5hdIComCYa','dSosWQVcJmkU','gmkemCkVpG','WOvcw8k2yq','WQOvWQe','WOyNomkaW6O','W51MWP4yWQO','W4tcPmk6w8oi','W5rFWPavkW','EKFdR8k1','hSkHpuddPa','WPa2crVdVW','WONdPmkbhmkU','aepcGCkHzW','aCkyn8kRiW','AmoeuchdPG','dSkpACkTjq','fSk7baZcRq','hCkDW6VcJSkZ','W4/dJeFdGmkv','omkqkmkPoq','cSk6WR8FFW','W6LrWPGfBG','W5RdP8koc8o4','WONcOCkvW5zY','z8kRWOVcPCoZ','W7dcKCoVW6C','WQexW7emWQq','pIvoESoq','WRVdVCkqgmkt','gSkHaG','hCkjaetdNa','WRyllmkTW44','tSkPW7Xx','W4dcPSoddSol','W4vUdq','vCkfWR/dQa','CrjzWPWf','W5ZdPSkkfSo/','iCkVheRdOq','a8k6geddVq','aSolWRJcLq','WPFcP8oAtmoe','W4FdJmoWrrm','W7uYa0NcSW','W6TFWOarzW','WQxcSwKMnq','pfVdU8kDpa','cr3cNCoHW5i','ttXdWQW1','WRJdHenQW6W','vZldQ8oX','WQCam8kWW6a','x0/cVq','zLtcLSorWP8','WPZcJINdH8kV','x0ddQSkKAW','W7P4tSkI','hSkxbLBdQq','CHaoeZC','WOfpFG','W4fHW67cQG','tCoFW7K','W4BcTCo0dmoq','vSoHfuBdPq','BmoLW4JcJCkI','W4z1vLNcNa','nCkMe8kipa','ECk1WPNcQCkU','W4dcKSopdCoC','W6xdNCkBb8oH','nXpcNW','W6rwWPWVWQq','W6XtWPuEzq','W4RcNCoxEJC','WR0kjCkH','AmkmW5zNeW','f3xcRCkSsq','bbn5WO5T','W5bcEuae','W5yNhX4','W6JcGttdHCoA','W5JdQG8','WR0qWOCeCG','W4ZcT8oL','WQ3dSmkdcCoG','WQtcLwjlW5W','W7FcL8o/W6ya','WPJdTSoTgSom','ASoeqaBdQW','WOBdRCkleCkH','nSkqWPSnDG','W686krm3','WQ4kW7ebWRe','wuxcGCkLzG','gCkxWQ0lsq','W5v9WPKZW6S','W5lcGYpdLa','W5pcNI/dGq','W6m3W4PMWPm','w1dcL8or','WPGDW4X7W5e','WQXJkgxdIa','W7hcUYTLW6G','bSkVauddOq','tSkdWRlcSW','qCkdWQ7dImk1','W6O4kHOm','W4JcMCkcsKK','kgSmo8kj','WQqeiCkTW4e','W53cPsizW7y','WRdcQgeZBW','g8odWRJdPmkI','W4FcOmoU','WQ7cKrddMmoe','BmotqqxdVG','WP/cQNq+ia','W69izW/dLq','WO8mW75iWQm','pSkukmkNia','pIxcQmkAcG','DmkTWRNdNSkb','l8kOjdRcUq','W4hcSCkGbSow','BSkLW6fe','kxOoeCkj','WOBdOmkle8kN','WQyuDYxdGHNcLfpcLxa','WOHhzfn3','W5iGCW','W4Lgxq','kKFdP8kbEG','uhBdTmkxsW','bmkmlmk1ma','W5COW4zfW6i','zLBcTmovWQ0','W4VcSmoLfW','W7TtjhVdOa','W6jikNNdIa','WRBdGgtdGCk4','W7JcJmoJq8o5','cmovWPZcImkU','ss3cVmoYDq','W6RcUtulW6i','smkcWQJdQmk6','ww3dS8kVCq','W5BdHmktimoJ','W55PW7/cQge','qcZdO8oVbq','BdnlWPub','gCk6cepdTG','mxaxoG','p0pcKCkLva','kuVdP8o4oq','W5rNWPG4WQu','WRNcTgeL','W7vcnvxdGG','nCk0WOBcRSkP','W4DHqqpdLW','W5RdQXSxWPm','sHRdOmoW','WR/cMxi','dXxdNSkSWP0','hYtdQ8oQvG','ESkZWO/cO8kI','BGBdTCoCoq','WRtcM2vgW5C','f0pcMq','WPZcIaddMCoj','w0/dPa','W5HPW6dcQNO','tt5oWR00','q0ddUmkKyW','W5xcOCoUW70o','wKVdSSkMCq','f1NcHSk0za','nXBcMSkwha','WQlcLSoN','fmkppCkUlW','WPeCaSkG','bSk7fblcSq','tbddRmolmq','W6mhkZev','zCootqO','W70LnGK','W4BdICkkmSoh','cSouWRdcQCk/','cgSrp8oh','BsZdL8oLja','W6zcowldOa','WRyxA8kWW4O','hMldQ8oOeW','W5VdO8kyfCoG','WRRdHKVdQmoC','d3VdMSoWda','W6JdRbCyWPS','vL7cImo2WP8','cmk7bvVdVa','WRBcNHdcKmkn','W4Sbe8o7','E0/dT8kGAW','bmkPeehcSW','W63cIZldLSoM','W4pdI8kSuf4','pXtcLCklfW','zSkNW4/cG8o1','W7/cQrddHmou','caxcKG','WRHfWOWQWOq','W4tdVXPB','BX5EWOac','W4hcOmkgW5m','WQVcRgpdG8k3','W71DC8k2W4y','W55KWOKZWR8','W7DkjhJdLW','WPpcH8oLu8ot','Axit','W4pcNCosFIi','W4bBCSkYAG','WRqap8kbW48','FJvaWOK/','W6TFWOyXzW','WPBdVSoqWQa7','WOpcPCkpdmo6','BmonrrFdUq','W5fvlN/dKa','WQynW6LfWRq','WPHdAejN','W4HQWO0ZWQu','WQBcTsFcKG','WONdVaiuW58','W6hcJSoJW6qr','FCkOWRRcOmkW','W5ddPXuEWOq','egKEW6f1WP4NqMxcQ8oNp8od','vCkClHZcRq','W55mwHFdIG','t8ovWRZcISk+','WRVcGqy','WPurW7XnWOO','W4VcJsO5W78','WRiwomo5WOe','W4BcGY7dLq','W4FdVXSF','WR1ZWRa+WOy','WPRcLSkss0G','kxyrmmkc','W49TvGRdIG','W4CTaKNdVq','e0NcGCkgFG','gSooWRhdUmkG','p3qsfCkk','W559W6BcRMy','W4ZcP8kIrSkq','W6TcWPutBG','WPCPWO88WQu','qY/cUCoGBW','W5JdNgpdQCk2','WRpcLgnPW5e','ortdM8kyba','WQegW61eWQC','WP5dFvLs','WOvixSk6ja','W4xdI8k4pCow','uIBcQmo/Fq','vuhdUmkK','amkRWOSoFq','W4pdI8kIxKK','W5BdJ8ouCty','w2pcSCoeWOu','eCkZWOKvFW','W5BdQ8khcSoR','WP7dTCkgkCkV','BCkIW5BcPmkI','g8ogWRxcQSkK','WQJcMSo9rCoJ','WPxcSritWOq','WRdcKmoNq8o7','WRxcISo2umoU','WQacW6TpWQ4','W6OCyYG','WOxcKgmCnq','AbqnpY8','b8kupSk7mW','WR/cLhLaW4O','WRylp8kHW5e','xL3cSSoLWOO','W7tdSSo+saa','WP/dO8kfdmkW','gh/cOmkPrW','uCofWQZcISk/','pMFcGmkdBG','qMddPSo5bG','W7HVrW3cNG','jHJcJ8oM','W6XeWPeEBG','qmouWQ3cN8k/','WOy5W5S','ve3cJ8oIW4a','WRaQW6vJWRq','WQFcSh0','WPapW4D4WQ8','hSotWQVcL8kL','emkCp8kGja','FCkHW44','WQtcK3ra','A8kMWOtcUSkU','WO3cMttdKmo7','lSotWRZcUSkM','W4bHW6xdR2m','WPldT8ofWP4H','W4/dUmkeaCo5','W6uPbe7cQq','W5XMWRhdOhS','jmkCf2RdVa','W5PZdfO','W6bol3e','WRFcISo3q8o/','qSkbWRNdO8kG','WQxdVJDYW7y','yCkSW65qgG','W4BcMSopW64','yf7cNCogWQW','z8kYWOlcQSk0','WOvitSk6Cq','qsrpWPe4','W7vFWP0E','W5VdR8kyeCoL','WOuIcSkvW7e','AmkLWQxdHCkD','W73cQbiYW44','grtcKmo+W7e','W4aPa00','vCk3W4/cN8o5','W58RgIa1','W5VdS8kfbmoH','e0NcGCkfzW','zCkLW7TMbq','FCoevdFdVG','ySkJW4FcG8oZ','WRpdOSoTWOK','pfOhftC','WQtcOwa+nW','ymkHW6Teda','xSovxq','rvRdVCkZCq','kgShomkc','W4nUuaJdIW','W7OkW4rEpa','W5bhtG','u37dUSoHmq','eCkoimk1ma','W5DTW74','W7BdPMu','a2ZdNmoQjW','WRRcLIhdG8oj','WQCkfmkB','W5BdPmkpamo0','WQDXW6S','rutcICoC','W6xdGCkQC3u','vJvhWRC6','fapcSSkk','nLxcVmkK','uCoiWQNcISkI','pCkLf8kc','W4VdICoqCGS','WPtdTSkjWOK3','WOldSSokWOG','zrGgeJu','WO5hyLvl','WQiiW6TfWQa','fSkEkCk6','luldSSoojG','W4FcSmoAxSkS','pCk+WPqc','W5ZdPCkpaa','WRucW7nzWQm','WO/dSGjb','umkaW7hcKCop','i8kKgCkAha','CYWtkYa','W6RcUtuZW7S','W4SNaq','zmkIWPlcPSkM','W4NcNh4','W7yLnrmv','oSkSW4RcGmk7','nhekECku','WOSkW6XyWQK','W4m0mKhcRG','vIlcTmoMEq','W4Xhx8o5oG','W4TUqaxdLq','udhcSCo9Aa','iSk0W6zhca','W5zkw8k1AG','f0NdJSoUtq','ifJdJmouiq','WRlcRxC7oa','WR4aomk3W4i','W5XSWPGyWQC','WPKgsCkRzq','W6tdR2VdI8oL','WPKgxSkYCG','W6JcU8oKdSou','W7zGWOiOWQy','W5BdLSksvK4','pxmB','W5tcU8kzdCkH','W6ZdO8kramoF','W7JdQwa','W4PVW4rdW7G','BGemdJG','WQCkp8kLW48','iH/dM8kLba','W7iPbuhcSq','W5BcUrFdSSoT','rsjEWPWT','iSkqmCk6jq','W4/cHgddH8oU','cSocWQ3cU8kN','W7eDWOCDkq','WQemjCkJ','EaelbGy','WQdcM3TqW50','W63dPhK','BZfhWR0+','BmoavHddJG','sHFcLCo+W4q','WRhcN2nGW5q','WO8NW6NcPN4','WP7dTCkgcmkL','W7O+kZGp','W4u4hrip','W7PzWPmyFW','W7xcUtySW7S','W651W7GYWOW','x8kTW5VcN8k2','iSk8WQ9Pha','WP4GW4u','W6RcTsS4','WPRcGsFdOmom','WOmSW44','WPNdU8oVh8om','WQOqW7XdWRm','sJRdP8kMrG','eCkooSkiiq','W5bKW6ZcVhS','W552WOasWR0','a8k+lHZcUW','W4nQfLxdTW','tSkcWR/dOCkH','W4RdSGmjWOy','bmojWR4','rmkdWRldUCk9','WO3dUCkpe8k0','WPJdTCox','WRFcM8o0ASoZ','hI7cTSkI','W7mhkSk2W4i','ECkJW5S','nWRdGCoAfq','ASotzWxdUq','g1ZcKmkU','W6VcL8oU','WRWiW6r9W4C','WQJdNxhdG8kY','baxcLa','pmkhehFdQW','W7jkrIpdKa','W7rkiLtdPG','b0NcMW','W4TPvW','WRdcKxLnW48','WQirmG','W6qNgKhcRW','tSk0W5D3bq','WQlcIhzlW4S','AYj6WOWn','W7tdMN9eW5O','BmkUW6zndG','W6pdIWhdJSkd','WOtcNM44fG','WOCSW5bjW7G','sapcKCkPFq','WP/cN8ohmIK','WRCmW5ndWRe','WR/dTwDHWRe','i8o+WPFcK8k6','rSknWQJcRCk9','lH3cUmoFW6W','phOkeCkl','WPRdSCkAeCkH','fComoSkYpG','WOxdSCkyhmkZ','W5vixSkiCa','W6ddHmo8EW','WQxcP2uLEq','W4ZcG8kjmce','W6zclgBdJW','Bmk0WOxcPSkO','hSoxWRJcKmo1','W7LWWQu5','cmolWRu','WQtcICoVW6ee','qJLgWQWP','W57dUCkywmkU','sSoVDcZdUW','WPJdSmkeWQy3','WPq/W4DnW6i','d8kJfehdPW','hmkXlaZcRa','BXTdhY0','B8k7WParmW','W43dO8kiaa','phOkeSks','tmkspCk6ma','WPVdV8kCmCk5','WOuOW49dW6a','WRJcM3Pa','smkiWRK','WOxcLK9XW5e','WRNcTh19W4O','tYxdRmo7aG','W6VcUsKZW4O','uuVdQmkeAq','ELZdTSoqBG','W5ZdVruFWOe','q8kvWRldRmk5','W5pdICom','W43dVWiBW5i','W4BcU8oUc8ol','WQVcIZNdHCok','W494hGhdKa','W5LWuGRcGa','WQbZWRa+WPC','pmkXWO0cFq','WQmxiSkQW5C','WQqgW6TPWQO','FCkLWRZcJCk/','W5RdP8kBeCo1','W73dQ8kzbSoJ','W6BdGCoqtSoI','ASopucJdOW','bmodWQ3cLSoX','E8oovH3cTq','oNmBb8kt','W61vWPafAa','dmklaSkAmW','W47cTCoTcSok','jb/cI8kcba','BtlcNSoDCG','WRhcKbZdHmoi','bdngWRK/','W5j7W77dSIO','umkfWQVdK8kN','ruVdVCkZzG','W6ldQ33dMmkA','W6e9kGKc','W4tcJZlcKCom','vcZcKCoauW','W4JcKCoihW','d8kvhCkYkq','W6XDx8k2','smo9jaBcSa','CmkLW6TwcG','W63cOq7cNmk/','WRukW6fuW4S','W4xcOSkqW5rRWQDylub8WOOyW54','W4ZdUSkaD08','W57dPSkonSo4','W7JcJ8kZqCo7','p8oIW70ocG','bmkfiW','pKKqdca','ibpcN8klfW','z8oQWP/cU8kI','W4CYiriM','W6BdMNnmW4S','qsdcRmo6AG','W5jRW7NcPN4','W6ddQHmx','W6ldSriFWQ0','WRFcNNnGW44','aepcH8k5rW','fSkZiXRcRq','mmkZWPGuya','W4dcHSoYW6Sm','W7BcNN5iW40','oJ8wmCkg','WRP1WRO+WOq','zSk1WP8','WP3cVM1SW48','W4mRfe7cQq','W57cQSkydmoT','aXBcLmoMWPS','jmkwc8kNcq','D0JcS8oq','drtcImoxW40','kKVdOa','W4VdPCkgrCo4','W5VdR8ky','W4nUqa','x2NcLSoYWQq','W5XSWPGiWRG','WQaLobTo','gmkVh0JcSW','u1JcLSoaWPK','W5RdQG8wWPC','WR7cM2rmW5q','W65eWO0','dCkRbwRdVW','eSk6nIZcSG','WPTTWO0VWQi','WPpcQezkW4K','gmkRaupdSG','pCoIWOVcVCko','WOPMxaRdIG','W7hdQ3hdQCk1','W41DtSkRDW','iCoprrlcPW','ldpcLCkkaa','W6JcVG3dVq','CWeAecq','W41lWRyzWOO','iSkRWOa','WRpcGrVdJCoj','BYJcTmoFsq','WP3cNtZdJG','hZhcUSkViq','sbqtcti','hHtcKCoNW4O','gmkPgehcQq','W4LXW5fCW7C','l8ocqrddQW','wLFcK8oa','W5rTW7NcIMq','W49OWOeT','FCkXWPGrpG','WRDIWP0yWPm','WPPhFenb','hSoeWRJcKmkL','a8k2jGZcRa','W5RdUmk4emoR','WQLLWQquWRO','W6SylrWo','C8kYWPWkzG','W4BcUmoHhmol','g8o/lGBcTq','WPW4W4XgW6m','v8kEWRxdO8kG','jSkXWO0','zCkIWPJcQmkZ','4P+frrJcSmom','sHpcImo8WOW','pSkqn8kRiG','W64spgW','W67cVsKQW78','DHVcL8khaG','WPTGWPG4WQy','W6VdMhfkW5y','ab7cLCo8','W47cNCorDIG','W4besSkVFq','W78hW7zAW6y','W5XHxXhdMW','W7HvWOa5FW','WQDZWRa9WRa','W7RcQcTYW6K','DmkjWRddQmk3','vCowW7W','W6zcowlcJa','DbWogti','W5iPpu/cQG','W6HLqrFdLW','W4CKaK/cSq','W55XW5zS','WOtdUmoqWOq9','WRhcLmkZrSo+','W4/dMSke','W5PMW67cO30','WP9OWQysWRO','CXxdUq','A8kJW6O','W7tcUse','W7NdOcxdMSk4','W73cSsaXW64','WPOSW5i','W5FcSCoKgSoB','zf7cVa','W6/cVtCX','WR9zWOavzG','E3GFjmoD','D8kMW7NcKCop','rtrnWR1S','nCkWWOSICG','zCkLW7TUbG','xeVcN8koW4W','W69MWPG8WQC','W7SBW7T9WODBW68','drtcImohW5i','WPGJW5ybW6u','W7qnW5yfEW','W67dLmogAW','a8k6ofVdTG','uw3dLmkICq','WQuOW5fjW6i','hmk4kH3dPq','W5RdQXqoWP0','W7BcVsG6','eH3dMSkzW40','WR/cGMDQW5S','WRhcKMmFWO4','WQTQWRa+WPC','aeNcJCk0sa','ysBcRmorza','W7tdR3FdHCkQ','W5Pgm3hdGG','W7xdONddN8kT','W4ddLSktELS','qmk5W4zh','BCkDWPGECG','eCkYmSkNpa','W47cMCkfxLi','W4FcJZtdTmoJ','W6VcQdWZW78','WOddR8oD','W4xcHdtdVCoM','WQaNWQyKWPe','W7NdU3BdV8k6','WRZcIbtdMCoo','ESkwW4RcHmoX','ymkeW5HmjG','W7FcSJe6W7q','ECoasbhdRW','qcZdRCoVeW','W7DGWP8P','W4fvEuXb','FCkSW53cK8o4','W6hcRZldN8on','lHtcISo7W4i','W5tdNmozAIa','z8kHW4RcMmo4','W6WbW6PyWRi','W5VdPZOtWOe','pZFcQCo2W6y','WRxcIXZdHa','W5PKWOKVWQO','W7TpkdBdKa','WPCWW6LgWRy','iLFcNCkheq','smo9metcVq','vfVdPCkrDW','CCkWW6BcMCoY','tshdR8o5','zILJWRW','vmkaWRxdRSkX','WOldSmoAEYa','C8k7WPaoya','cSouW6C','W4ONaLpdOa','WQzbWQf4WQ8','W79gmq','W5xcPSoPaCom','tSkAW6i','WPRcU8ojWOG/','WP3dUSonW405','scvzWQWP','veJcNmk0BG','W7OnW5ywza','W6S8Db0g','AGNcI8kpcW','ht7cMmkVaG','WQZcKaZdHSoy','A8kUWPJcQW','WQTxWOi6WRC','W4j8W7q','W4JdUCkpemkW','gSksmq','CbJdI8oYjq','WQfPWQe1WO0','W5pcJZtdSmo7','f1JcOmksrW','W5DSWOi6WR8','WR7dKSkOWRTq','WOldKmouBsi','W5pcMIhdN8kV','W45Lqa','reNdImoGW4q','WQ8fj3NdJq','BHypfsi','af7cNmkT','c8ooWRFcMG','W6TvWOWesa','WRBcIHdcImkd','WR/cSgeMEq','smotm8k6nq','CCk1W6joca','hSk8eehdOa','b8kijCk+nW','W5pcMIZdMmoS','pSkKW6zvsq','eCkMWRad','WOvjFGG','W6bEfxNdLW','W4tcSWqvWOu','pKVdOCouoG','A2nnkmov','qchdSmoOmG','WQLIW7DU','E8kMW44','WQqrdCkjW4K','pCkSWO0vzG','WRpcL3jlW4W','W5fgDSk0CW','WQNcKmoYW6Sr','W7vcnvpdJW','W5CGW4DbW7q','lmosWPlcR8kk','WOBcTmkAhmkK','WOeKW4bEW7C','vflcJSoDWOO','vCkIp8kLmq','WQVcHqdcISor','WRaxW7PEW7W','W7PHa3tdKG','W6S8pbCx','ymk1W7zZgW','k8o5WQBcQSkS','vhbhWR0H','W5hdQHOqWOq','W5rNW4W+WQC','hmkFoCkIjq','qCkVW57cMW','WPO2uupcSq','WQmFWPazFq','mSk7WP0','CWuceN8','WPqHW5DFW6i','j8kqcSksia','oXtdGmooaG','WQ8wW6XyWQm','W4fTW6dcOh4','W5hdQ8kgaa','CCkWW4xcK8oI','bCkhW7BdNSko','W5uRuWdcSG','tCoaqapdRW','WQT1W71GW40','WRhcKCo0aSo2','CmkmWP3cQCkr','W5LWxW3dIG','z2SADmke','WRVcTZ4Toa','WOJcLSoGvG','kmk3oeS','W7bclx8','W5hdOeBdUCkP','W6TFWQCeEq','WRtcJ251W4O','ySkAbLO','fSk+mb3cJG','iCk6WOKlCG','WP/cT8oVa8on','WRajkSk3W5a','WPHjwwvR','WQxcRwHRoq','l2ysmCoA','W60Lmbyn','WQ3cI8o2t8og','he3cH8kdza','lhyAimkp','W6TvWPK5BW','W4BcRCoMbSo5','ubfFWRWL','WRJcGqhdR8or','W7VdP8ouCtq','W4VcOSoFhCoD','W4Tiv8k+','W4NcICohW5ir','aSkNdCkJnW','dCkaoSkOEq','W4BcQ8kuW5zY','e8kEkmklmq','n8kMcW0','v8kcW7XMca','WQdcRwaUoW','W6JcHSoOW60r','kmkTW5VcGSo/','WRRcIGhdPSou','A8kZW6Xmha','WOmIW65dW7u','WOlcQe8i','bSoVWR/cK8kX','W5VdUWy/WPW','a8kGh0RdOq','W6K0ltWp','lmkYW6Pada','WOlcQmkjbmoO','W5XMW7NcQMy','W4hdICoABw0','WRddKSoKr8o+','E3irmmkc','WOm/W4Tb','stfs','ESkLWOtcGSk+','WO98W6NdR2S','WOGKW4XMWPy','WPVcM8kfvKK','WQtcN2rqW5q','u0pdUCkVCq','sclcQSo0Fq','WQ7cKaW','rWBcGCoNEG','WOLEzbTf','WQXYWQWaWPe','ymopuahdPa','hmkcEmoNEa','ed3cKSkPka','WP/cIvrM','WOPYhGNdIG','gSkumSkzpG','FCkOWQxcU8k1','g8k+lWW','d3/dUCojdW','d8omimkViq','a8oiWQ4','bmoeWRW','W6ryqrldPW','tqrUWOWh','W5vBu8k1Ca','WRaDoCk8W6G','W4BcPSoLdSom','jdhcKCk5fq','wfdcIG','WRtcNSo9hmkR','WRtcNbpdMSoy','yGj+WQiG','WQldVSoiWOGX','WONcTKvk4OoH','W6H5EGa','oMyroSol','W4bex8k1Ca','W59RcfhdLW','WOVdUmkldSkZ','tJFcJmo6Cq','WQXwWPG0WRi','geNcM8kNFW','W57dRSkpimo6','WOhdT8kp','W4SIW5jyW78','WQxcJ3PiW5K','W7hcSIyZW68','WR7cLWBcL8kF','ieRdTSof','WR/cLgmfW4m','E8kSW4ZdImkQ','bKNcKCk1Aa','bSkRjWFcUW','d8oZu1JdUG','W6mjW6PnWQO','rmkdWRldUCkX','W4nZwGNdJG','WOv9w8k2zG','e8k0cmkXcG','DmkHW6nwda','WPKQW6TcW7G','WPJdOCkzfq','WR/cP2e','WQZcNSoHrCo2','W4zLxqpdIG','a8k6feldKq','W75WWOSBWQC','nmk6WO0IFW','W7pcNI/dMSkV','W5qZeLtcSG','W6NcQdW','a2JdPmo9gG','WReeoCkNW4W','BCkIWOu','W49gu8k1','rCoXDrRdVG','W6tdUXGdWPS','W4TKvZddKq','WPZdUSou','usxdPSoPfq','ECkpW5/cSmoB','W5VdSqmuWPy','E8oevGJdRW','sSknWQW','WQxcK8o2CCoJ','g0lcKSo+nW','w17cLmor','lfRdVCkDnW','WPOIgfBdVq','W4n9WOqNWOW','W6m0kGOc','md8ApCkt','WPRdLCogWP4f','imk+WPucya','WOmRW6zCW50','nSkPgIZcRG','qK/cVmkJza','kepdSmo/ea','W4BcVmoHaCoF','W5RdUXOwWQi','W4TRW5JcIK4','A8kUW6fggW','WQOiW4zBWQ0','W5hcNJK','WQlcRYyWW6O','WPBcOdpdKmoU','WRBIGQWLW7/cRq','nxSBla','W67cTsxdMmk8','emkXnIxcTW','uJfgWQ0P','WP9QWOydWRS','dw7cRa','W5ldLSkvxLy','W5eeyHTh','W4NcJJtdMCk1','kaJcTCo2','WOjUWQyK','WO3dMCoCAxS','W7nvWPOxFW','WQRdJ2SuW4q','W6ldOxhdJCk1','W5ldMmknBv8','ArSngtm','r8kdW5/cG8oH','W4Xnf8ksqa','W6ddK8o8wXW','W4fasCkRAa','WRekW7Xj','W5faxSk6BW','smkCWRNdOW','W6LzWOCzAq','WOldR8oDWOe3','WPKSW49j','euhcKmkUFW','pmkRjWtdVG','tcBcTSo0Aa','WQldL2baW5e','W5H8pJ4T','z8kXWPpcOCkZ','W7NdNCoJumo+','FH7cQmkDmW','u8kjWQ7cTSo2','W6OVe1lcVa','W4lcSCo0kSou','FCkMW5/cNSkS','WOvCDqWu','WPRdVCkjga','W5aNhvxcUa','cmokWRZcKmk/','A8oauau','uYBcTmo/ta','ohCFoSka','vYhdRSoFgq','WQqrW6PC','WRFcTNapnq','W7ZdUmkFe8ob','ytNdI8o4','W4RdSrGjWP0','W5tcG8kxxKG','WPddRSkce8kY','WRBcMSoJtSo2','CGhdOmonna','fSoEW6VcO8oK','tCkQW61koG','oSkRWPWkmW','W6hdGgtdTCk2','W5hdTMFdHSk8','C8kkW6NcJSoL','WRVcHvxdNSop','W6FcJ8oNW7Kw','tSkcWQRdQmk6','b8kpWQPhCG','W6ddKmknwHO','zSk3WPpcOq','W6VcRcqXWQq','W6OWmLKo','W6pcVYRdK8o4','uvddMSoeWPK','WPRdNCkisrO','W557WQ88WRG','WQyokSoKW4C','qCkfWRddUCkX','yWWffqa','gNldQmkJoq','W7ykk0JcTG','W599WQmnWPm','cMGsWQOP','iv3dP8kt','WQCxiSkP','W40ccuxcKG','WPZcTYpcISow','iGpcPmoMW4S','d1hdGSkYW4u','W7XCWP0tya','W4qNa0hcSW','tsBcVmo6Fq','WPe/W4nbW7m','W5jNWO8XWR4','W5bPW6pcOw0','zbRcGSozAG','r8kqWRdcI8kr','W7ddOxFdQCk4','W53dStOvWOu','W41LrZddJa','FmkSW5BcPmkO','zmkPW6fhia','W5tcKZddLa','WP7dMCoCAwu','WP/cI1q7pW','vCkvm8k9mW','W6Sclqap','WRCRW7PfWQe','WQVcIXNcISkp','d8kglmkPza','W47dUWi/WP4','tcFcKSo/vG','uZFcOCo/Eq','W4hcMcxdKmkV','WRxcLxLgW5K','WR9YWRaIWPO','eeNcHG','rHLyWRia','ECkTW4/cL8o6','WQukW7nyWQm','W7ZcUty','Ea7cMSkmsa','WQyoW7PcWRi','WPP2WOas','WQpcKI0f','WRNdGCo0WQCj','W5rTWQ/dSq','nSkDl8k9ja','W6HmvSk+zG','W6RcUtuAW7q','W4uQefpcRG','W68Ylrav','WQmeiSkG','iIxcSCoE','W5lcJYtdHmoS','W4zMW7K','f8kei8kEiG','r1RdPq','W5ldJf/dI8ka','a8kLoCkpgq','WRBcKbddH8oo','pNiBoSkt','W4LMWOaXWQi','dHJcJ8oIW40','yCoasqe','W7xcL8o/','W5zGWOjWWRW','W4NcSCoUcmom','W6mhW75EWQ8','W6JcJ8oFW68e','W4FdSqe','g8k8nGdcSq','W6RcVsS1W7S','dSk6grxcPW','WQSdW4jdASo0FxpdPmo8','CcxdRSo5fq','W6lcIZldKSoG','kMSh','W5VcPmkacmkfEYZdLq','WOhcVe4Uga','W78Lia','p3Om','uLtcJSoGWPu','aepcH8k5va','hmkDo8kNCa','W4rOcKhdPG','DbTogca','WRFcIMjwWOq','aXxdKCoBW6u','CKLmdZe','W74zobO7','W4ZdULreW44','CSkWW4tcMW','W43cJZpdGSoU','W6/dR8kfhmoL','z8otqqi','CWZdOCkqiq','udxdOmoOgq','p8oIW6jwhq','WP4lhCk1W4u','sCorW77cV8o2','Ff/cISobWOG','WODiWOuGWOG','W7RdR2FdICk1','W6ZcVsGV','W4ZcSmkTjSo8','W6hdVWqDWPm','W79+W6VcQhW','gmkmkXpcUW','egJcLmk0BG','xCobWRxdO8kW','W5ldQ8kzaSoL','kSkajmk+nG','aCoiWRJcMSkU','FCkOWOtcJSkR','W5pdVColWOmM','W4OZfghcQq','WPpcQHNdHSom','W4pcHJxdGSo7','uCouWQNcN8kL','W6mbW6TcW6S','sCkdWRldQa','WQamW7fyWQC','W4VdVXurWPu','rcNdPmoL','A8k0W6PokG','dSolWRJcJCk4','WOG+zWhdJa','vuldVCkYDG','W5m1ffi','WQCcW6TjWOu','W4TMoK/cUq','zmkPW6fhka','W6hcJCoYW68x','WPVdOSk6pSkL','W6DqC8k/','WOCMWP8PWRK','WO/dNmozDIi','WRBdP2VdHCo5','c1hcImo3W5u','o8k5omkWcq','emkYjWFcQG','W4hcSCo3W48T','vCkjWRhdOSkI','W4zJWPi1zW','WQ0DWPazBa','r8kNW4FcK8o1','ACoisGddGW','lepdKmoOeq','WRJdUJHKma','uepcUCovWO8','WQ3dLCkDl8kg','WOjYCurd','DSkoW6TNdG','vL7cNSor','W5FcSmoHcCom','fmktlmkykW','E2pcImo4WOu','we/dSCkK','W67dLuFcNmkiW6pcJIC2WO5f','CLJdQ8knuW','bedcLmk5mq','dSolWQZcJCk/','qZvEWO0/','WRCmW5z/WOK','W6tdP2BdIq','qKZdLSkdFq','WPPUWRG1','W69ZWRuHtq','WQukW7njWRu','yHqafYy','DSkHW60oaa','WQNdKCkyp8km','WRehW7PyWQm','W5ldLSkTue0','pv7dV8ouiq','bmktoSk+ia','WP7cKSogAZC','d8klb0RdVq','W5ldLSkOBhu','W4r1xGhdJa','W49TCaVdIW','W6nvCmoKW4u','W7NdQgpdN8k8','WPFcVwuCbW','pCoHW4viDW','WQamW6Xy','W7NcOg09AG','WOmOW5PyW5u','sceUma','W4X2yLLa','W7FcL8oJW6qa','W5b5WO04qG','WPJcQXldNmo+','se7cGmk0FW','rmkdWRldRSk1','W7/dQIJdPCkD','WPdcTsZdNSoC','W7XtjgtcMa','W7FcRmobgmoP','qmkjWQJdImk4','nCkilCk6lW','W4hdKCouBdy','yCkXW5/cK8oK','WQXUWRS0','gmkupSkNmq','mHpcImkEcq','W4FdKmoqCte','j03dTG','WRBcLXBdHCoi','mmkRWQW1xW','W4/dImoEtX8','W5RdVrCuWQe','W51ijMtdOa','emk2o8kNpG','aWxcMCo/W6i','W4/dJCkeuKK','W7BcUcaN','cSocWQ3cUSkQ','ouxcM8k1zG','W5VdPYyiWP0','amogWQK','BSkIW65aaG','b8kVWO/dM8o0','W7xcRbxdLCoi','WR0ejSkH','WPBdHCotqW4','W69cWP0EFW','WPXSW6tcUty','W43dMmoDscS','W7O0iq0G','aX/cMW','dKNdJ8oG','FexcN8ozW5W','WPhcLmoMumo2','rdCplsa','W6y+kG0','tN3dPmk8Ea','WPpcVuzkW4i','uf3cN8oxWOG','W4hcVCoUca','W7NcSMuxW44','obVcJ8khcG','W744kKvm','W5HtWQeOBG','CWZdT8oyoq','ESkLW4RcMmk2','ortcJ8kCcG','hHtcHmoMW6i','W5NdVWqjWPC','W5dcHtpdOSoQ','WR97WPecAG','qZvEWP0G','CCkVW5VcGSoV','WPZcTSowWOiL','W5OclXmt','W7PmW4VcTvS','W5LOWPu8WRK','WRJdPgCNnq','s8k+WR/cQW','W5lcGwddK8o7','W5rGW7NdTt8','W4G4nq0g','W6dcJ8orW44H','WR7cPI3cGSoY','W7ldNmkKj8oC','W5xcTSkAd8kP','W4WOeb0','bSkepCkEka','h03cM8oGzq','c8kTbuBdPq','WRZcJbddICow','W5rqWO07W7O','WPTkWOm2WQ4','WQqPh8kuW4e','h8kCpSkCha','WO1ny18e','W7lcNW4wW5W','bdrdWRSP','WQhdM8k6dCkR','W55HW6pdON8','WQ3cNmo2','jSkso8kGCa','WQLIWQevWO8','aYhdPSo9wG','WOJdMmofWROz','qtSqkby','zmkMWOtcQmkU','W4zfw8kODW','uYdcUCo9tW','qGWQga','W5rPW6BcN2q','W5CZfflcPa','W5eechhcQG','W5HPuae','WPTtWPn9W5S','hbdcKmoNW4q','fmkdoCkM','W4FdJ8ozEIq','W4Kwh3FcMG','W4mIuX4','sI7dOCoWaW','n1RcN8kpeq','WOeSW45zW7m','u13cN8om','WONdSmkoomk2','w37cOSoXWRS','CSktW5lcUSoI','WQ1RWQaJWPC','WQCkb8kRW5q','uKFdR8kIAG','DHWhgtm','WRhcOxaooa','WPZcHtddHCoM','rt4kWRWL','v1pcJSk/W40','WOFdUSoiWPG3','WRlcNSo/v8oY','yCkLWQjxca','w0FdSSoSCG','oKhdN8osiG','WRxcLNzwW4S','b8kVa0JdUG','W7ZdP2DH','zKRdGmooaW','gvJdH8kYW4C','tCoyBqa','bSkRh0JdPW','fCobWRJdPmkZ','hCoiWQRcOCkI','ortcJ8klcW','WQixW7PZWQ8','k2Onpa','WPWPW6PnWQO','W60KoXaa','WPm7WR3dV2u','omk+ma7cTW','yCktW5/cOSkS','bgdcMCkzwq','W4NcNIxdNmoE','pvRdTSotma','W7hcSIi','W5zzvSkYCa','W7JcI8oHha','u8kEWR3dO8kN','mbxcICkRba','W4ZdKmkecCoO','z8kYW4XcgG','mCkWf8kpaG','dmkIffFcQa','W5z5WOmVWR8','jCoZWP3dJSkKW77cGSkysWWahmorWPq','ySkMW5BcJCkO','WQtcJmoOW6Kj','EvJcICoa','WQtdGSkLf8k5','hSkVgepcSq','W5WuctuI','xf/cICorWOG','W51jWR0u','W4ZdSWuLWOq','e8k2la0','WQqsW4O','W60+prW','WOpdSSohWOG','sSkThKpdVa','aY/cKSkHeG','fulcM8kLEq','WQ0mW7fj','o8kZfXdcJa','vW7dR8kOza','W4ZcJ33cK8oP','ECoav0JcQG','WRFcL3i','g0lcGCkLzq','W6i0nX4x','wbZcImoBWOS','ucvyWR1W','W43cTmoaWOqK','smk8ffVdPG','W4b8W6lcVW','W7ldO8kfemoH','nmoYWOVcL8oJ','n3Oqm8kt','qvtcL8o9WPG','BSkyWRNdOmo0','WOxcSK0zmq','W71gjq','W6ZcVsDY','WP/dVSkohCo4','tCkIWOdcPSkK','nWpdGCkmcq','cGhdUmkOCW','WRNdVJS','yqbmWRe2','WPq0W5n8WOa','W7pcJYZdLmoS','WOJdOSohWOKK','WRRcGbZdNSo0','hmk7nGhdPa','y8oGW6rgsq','cmkplG','yNJcM8o7WPC','W5FdQ8kzaSoT','WO5tAuzw','W4ZdO8olfCoT','hGpcLCo/','WQZcGrNdHSoT','wSkBW6BcKmou','W4JcISo1W74','W4VdUmkkc8o/','zshcJmoXuq','EmkZWO8','W7FcT39/WQy','W4RdRbmBWOy','W4ZdULreWRa','W4RdJmkeaHG','W7JdJvFcLmo1','WQXIWRK5','W4fTW73cN3O','W73cSJe','WP7dTCox','W7BcMSovW78h','qmkYW6bugG','gSkbp8kG','wuddQmkKAW','pM09nCku','W4ZcU8oU','WQ8mW7XnWQO','CKRdUSolDq','t8kVW6Tcbq','WR9LWRW9WOy','W4dcUCoLaCom','WRdcILxdICor','AJtdP8oX','mSkSWOPAmq','W4XFba','WOhcTL5uW5K','ASkMWPG','W5BcOmo5a8oD','mCo+W4/dVSo3','aCkEyq','WR8ajCkJW5C','j8k6WOetua','WQtcRZu+W7q','FmovvGVdPa','W4pcHIhdGSo8','sfZdLCkJzW','W6ZdV8oSDY8','W6q+mbC','sCkTWRhdOSkH','p8k6WPCazW','WQawW6XyWQK','mXFcNSkaeq','W4bVwGO','sJrpWQa','veldS8kIBG','q8oFDCo0kW','W5f9W7tcN3O','zCkvWPxdQq','W6SekH8f'];_0x5a81=function(){return _0x345855;};return _0x5a81();}let html5QrScanner=null,scannerMode=_0xadf508(0xa1b,'utxI'),scannerRunning=![],lastScannedCode='',lastScannedTime=0x0,scanSessionCount=0x0;const SCAN_DEBOUNCE_MS=0x708;function playBeep(_0x3fb9a7){const _0x2a60f1=_0xadf508,_0x1e4e9d={'FrkDx':_0x2a60f1(0x54b,'w2w1'),'RxAwQ':function(_0x1c9572,_0x1a74ea){return _0x1c9572===_0x1a74ea;},'skvLy':function(_0x164877,_0x15e04c){return _0x164877===_0x15e04c;}};try{const _0x2b77b8=window[_0x2a60f1(0x528,'13TQ')+'Conte'+'xt']||window['webki'+_0x2a60f1(0x746,'nrxl')+_0x2a60f1(0x46b,'&v4y')+_0x2a60f1(0x256,'VUa@')];if(!_0x2b77b8)return;const _0x43503b=new _0x2b77b8(),_0x30837e=_0x43503b[_0x2a60f1(0x5d9,'JSoZ')+'eOsci'+_0x2a60f1(0x2c2,'XucK')+'r'](),_0x15e8e3=_0x43503b[_0x2a60f1(0x9bd,'utxI')+_0x2a60f1(0x8f5,']4q%')]();_0x30837e['type']=_0x3fb9a7===![]?_0x2a60f1(0x32c,'JSoZ')+_0x2a60f1(0x5ac,'^^3k'):_0x1e4e9d['FrkDx'],_0x30837e[_0x2a60f1(0x396,'oFps')+_0x2a60f1(0x1e3,'eHms')][_0x2a60f1(0x584,'l&at')]=_0x1e4e9d[_0x2a60f1(0x8e6,'E*G)')](_0x3fb9a7,![])?0x140:0x370,_0x15e8e3[_0x2a60f1(0x1e9,'sa(9')][_0x2a60f1(0xa4f,'IdpO')+_0x2a60f1(0x893,'bC8p')+_0x2a60f1(0x8c6,'*e]A')](0.15,_0x43503b['curre'+_0x2a60f1(0x60e,'$p9U')+'e']),_0x30837e[_0x2a60f1(0xa04,'E*G)')+'ct'](_0x15e8e3),_0x15e8e3[_0x2a60f1(0x3d4,'PRZ&')+'ct'](_0x43503b[_0x2a60f1(0x522,'sa(9')+_0x2a60f1(0x911,'KN]U')+'n']),_0x30837e[_0x2a60f1(0x3cc,'](EQ')](),_0x30837e[_0x2a60f1(0x43b,'V[]2')](_0x43503b[_0x2a60f1(0x3da,'!HV9')+_0x2a60f1(0x78d,'khYj')+'e']+(_0x1e4e9d[_0x2a60f1(0x5e1,'XucK')](_0x3fb9a7,![])?0.22:0.12)),setTimeout(()=>{const _0x551436=_0x2a60f1;try{_0x43503b[_0x551436(0x6bb,'](EQ')]();}catch(_0x2f5d29){}},0x1f4);}catch(_0x949741){}}function vibrate(_0x133dac){const _0xa53312=_0xadf508;if(navigator[_0xa53312(0x282,'bC8p')+'te'])try{navigator[_0xa53312(0x710,'JSoZ')+'te'](_0x133dac);}catch(_0x3849aa){}}function showScanFeedback(_0x56c743,_0x14498c){const _0x1cf0db=_0xadf508,_0x466b7a={'oqNgC':'error'},_0x1e6a4e=document[_0x1cf0db(0x7a9,'dQtf')+_0x1cf0db(0x399,')cQA')+_0x1cf0db(0x5cc,'zog4')]('scanF'+_0x1cf0db(0x432,'FFZd')+'ckBar'),_0x338198=document[_0x1cf0db(0x217,']4q%')+_0x1cf0db(0x849,'VUa@')+_0x1cf0db(0x6ac,'bB4q')]('scanF'+'eedba'+'ckTex'+'t');if(!_0x1e6a4e||!_0x338198)return;_0x1e6a4e[_0x1cf0db(0x3d9,'zog4')][_0x1cf0db(0x85e,'KghS')+'ay']='flex',_0x1e6a4e[_0x1cf0db(0x230,'utxI')+_0x1cf0db(0x69b,'zog4')][_0x1cf0db(0xa75,'utxI')+'e'](_0x466b7a['oqNgC'],!!_0x14498c),_0x338198['textC'+_0x1cf0db(0x1f2,'!HV9')+'t']=_0x56c743;}function isSecureCameraContext(){const _0x252033=_0xadf508,_0x567cb8={'wNaYo':function(_0x3a2dff,_0x36b5a4){return _0x3a2dff===_0x36b5a4;},'AetBx':_0x252033(0x809,'5Hqz')+_0x252033(0xa58,'w2w1'),'dklAm':'[::1]'};if(window['isSec'+_0x252033(0x8bb,'$p9U')+_0x252033(0xa47,'w2w1')])return!![];const _0x2ddca5=location[_0x252033(0x2c3,'dQtf')+_0x252033(0x359,'$p9U')];return location['proto'+_0x252033(0x481,'Vabs')]===_0x252033(0x647,'oFps')+':'||_0x567cb8[_0x252033(0x80c,'xb!o')](_0x2ddca5,_0x252033(0x9cb,'VUa@')+_0x252033(0x90b,'a4i]'))||_0x2ddca5===_0x567cb8[_0x252033(0x6a7,'khYj')]||_0x2ddca5===_0x567cb8[_0x252033(0x4d6,'1&H^')];}async function requestCameraPermission(){const _0x223fba=_0xadf508,_0x23da4b={'SVXbF':_0x223fba(0x9c6,'bB4q')+_0x223fba(0x498,'9)b9')+_0x223fba(0x816,'a4i]')+_0x223fba(0xa0a,'sa(9')+_0x223fba(0x72d,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+'kses\x20'+_0x223fba(0x484,'eHms')+'a.','oNjXr':function(_0x224e7c,_0x296375){return _0x224e7c+_0x296375;},'TdKAK':_0x223fba(0xa78,'FFZd')+'kamer'+_0x223fba(0x2bb,'](EQ')+_0x223fba(0x402,'!HV9')};if(!navigator[_0x223fba(0x55b,'gMHR')+'Devic'+'es']||!navigator[_0x223fba(0x8ec,']4q%')+_0x223fba(0x6c0,'KghS')+'es'][_0x223fba(0x698,'KghS')+_0x223fba(0xa4a,'IdpO')+'ia'])throw new Error(_0x23da4b[_0x223fba(0xac0,'xb!o')]);try{const _0x570307=await navigator[_0x223fba(0x82a,'khYj')+_0x223fba(0xaff,'w2w1')+'es'][_0x223fba(0x8c2,'nrxl')+'erMed'+'ia']({'video':{'facingMode':{'ideal':_0x223fba(0x4bd,'VUa@')+_0x223fba(0xa00,'V[]2')+'t'}},'audio':![]});return _0x570307[_0x223fba(0x378,'Vabs')+_0x223fba(0xb3d,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')]()[_0x223fba(0x74f,']4q%')+'ch'](_0x3b7b8a=>_0x3b7b8a['stop']()),!![];}catch(_0x520deb){try{const _0x4059a8=await navigator['media'+_0x223fba(0x9a5,'gMHR')+'es'][_0x223fba(0x638,'q3H^')+'erMed'+'ia']({'video':!![],'audio':![]});return _0x4059a8[_0x223fba(0x832,'&!DG')+_0x223fba(0x211,'dQtf')]()[_0x223fba(0x9f9,'zog4')+'ch'](_0x3597f0=>_0x3597f0[_0x223fba(0x492,'a4i]')]()),!![];}catch(_0x265266){throw new Error(_0x23da4b[_0x223fba(0x5e6,'l&at')](_0x265266[_0x223fba(0xa69,'eHms')],':\x20')+(_0x265266[_0x223fba(0x7c0,'a4i]')+'ge']||_0x23da4b[_0x223fba(0x26d,'ceYQ')]));}}}async function stopAndClearScanner(){const _0x571aa9=_0xadf508;if(!html5QrScanner){scannerRunning=![];return;}const _0x6c50b8=html5QrScanner;html5QrScanner=null,scannerRunning=![];try{if(_0x6c50b8[_0x571aa9(0xb09,'JSoZ')+_0x571aa9(0x5bc,'bB4q')])await _0x6c50b8[_0x571aa9(0x99b,'eHms')]();}catch(_0x30a83e){}try{_0x6c50b8['clear']();}catch(_0x55dee0){}const _0xf9649f=document[_0x571aa9(0x1fa,'13TQ')+_0x571aa9(0x54c,'V64C')+'ById'](_0x571aa9(0x2f1,'KghS')+'deRea'+_0x571aa9(0xacd,'UbQ2'));if(_0xf9649f)_0xf9649f[_0x571aa9(0x44c,'#HYV')+'Selec'+_0x571aa9(0x333,'eHms')+'l'](_0x571aa9(0x752,'IdpO')+_0x571aa9(0x4da,'q3H^')+_0x571aa9(0x993,'FFZd')+_0x571aa9(0x593,'JSoZ'))[_0x571aa9(0x3a2,'gMHR')+'ch'](_0x2eff46=>_0x2eff46['remov'+'e']());}async function closeScanner(){const _0x5684cc=_0xadf508,_0x21ff76={'sZold':_0x5684cc(0x567,'oFps')+_0x5684cc(0x4a5,')cQA')+'al','MjAXt':_0x5684cc(0x5ab,'Vabs')},_0x22bf8d=document[_0x5684cc(0x6b0,'V[]2')+'ement'+_0x5684cc(0x650,'#HYV')](_0x21ff76[_0x5684cc(0x979,'sa(9')]);if(_0x22bf8d)_0x22bf8d[_0x5684cc(0x4bb,'FFZd')+_0x5684cc(0x9b8,'^^3k')][_0x5684cc(0x4e0,'IhJl')+'e'](_0x21ff76[_0x5684cc(0x74b,'^^3k')]);await stopAndClearScanner();}async function openScanner(_0x4fbfdf){const _0x2a36ff=_0xadf508,_0x323fe0={'EbTbM':function(_0x2fdd4f,_0x8b0e05){return _0x2fdd4f*_0x8b0e05;},'DJHkH':function(_0x340a6c,_0xb0c90e){return _0x340a6c===_0xb0c90e;},'VOKWE':function(_0xe7fc06){return _0xe7fc06();},'sEscM':function(_0xced434,_0x42526a){return _0xced434+_0x42526a;},'bEDmF':_0x2a36ff(0x5a2,'5Hqz')+'nuous'+'ScanC'+_0x2a36ff(0x916,'KN]U')+'l','VIaXx':function(_0x4695ac,_0x60ea3e){return _0x4695ac===_0x60ea3e;},'cxrxK':_0x2a36ff(0x94f,'ceYQ'),'lZMCv':_0x2a36ff(0x939,']4q%')+_0x2a36ff(0x5f9,'sa(9')+_0x2a36ff(0x4ec,'gMHR')+_0x2a36ff(0x91a,'UbQ2')+_0x2a36ff(0xaa7,'a4i]'),'OTmOC':_0x2a36ff(0x88f,'$p9U')+_0x2a36ff(0x8aa,'KghS')+'ap\x20me'+_0x2a36ff(0x433,'XucK')+_0x2a36ff(0x5d4,'^^3k')+_0x2a36ff(0x6d1,'zog4')+_0x2a36ff(0x2bf,'*e]A')+'\x20Beru'+_0x2a36ff(0x439,'q3H^')+_0x2a36ff(0x54e,'VUa@'),'Lvfgt':'none','PgaKb':'scann'+_0x2a36ff(0xa63,'khYj')+'t','pCAQF':_0x2a36ff(0x6c2,'13TQ')+'erMod'+'al','rARLe':function(_0x3fe4da,_0x6c0648,_0x428d8a){return _0x3fe4da(_0x6c0648,_0x428d8a);},'cwYdi':'Kamer'+_0x2a36ff(0x991,'&v4y')+_0x2a36ff(0x719,'nrxl')+_0x2a36ff(0x468,'khYj')+_0x2a36ff(0x7d6,'](EQ'),'IchaC':function(_0x82f1af){return _0x82f1af();},'YZanq':_0x2a36ff(0x66b,']4q%')+_0x2a36ff(0x62e,'sa(9')+_0x2a36ff(0x3c6,'V64C')+'indai'+_0x2a36ff(0x47f,']*Uo')+_0x2a36ff(0x8fd,'bB4q')+_0x2a36ff(0xac5,'JSoZ'),'yLcHk':function(_0xe71b2a){return _0xe71b2a();},'EPfiz':function(_0x4e73fc){return _0x4e73fc();},'QBhwk':function(_0x395b8d,_0x361dc8){return _0x395b8d(_0x361dc8);},'WjfAV':'Gagal'+_0x2a36ff(0x662,'dQtf')+_0x2a36ff(0x6da,'w2w1')+_0x2a36ff(0x6c7,'q3H^')+':\x20'};if(_0x323fe0[_0x2a36ff(0x260,'khYj')](typeof Html5Qrcode,_0x2a36ff(0x486,'&v4y')+'ined'))return showToast(_0x2a36ff(0x7f5,'bC8p')+_0x2a36ff(0x2ab,']4q%')+_0x2a36ff(0x98e,'Vabs')+_0x2a36ff(0x2d3,'l&at')+_0x2a36ff(0x672,'zog4')+_0x2a36ff(0x22f,'$p9U')+'Cek\x20k'+'oneks'+_0x2a36ff(0xa8b,'V64C')+_0x2a36ff(0x728,'13TQ')+'.');if(!isSecureCameraContext())return showToast(_0x2a36ff(0x586,'nrxl')+_0x2a36ff(0x1cd,'xb!o')+'erluk'+_0x2a36ff(0x910,'rDp@')+_0x2a36ff(0x812,'dQtf')+_0x2a36ff(0x713,'#HYV')+_0x2a36ff(0xa90,'bC8p')+_0x2a36ff(0x822,']*Uo'));try{await _0x323fe0[_0x2a36ff(0x4fa,'zog4')](requestCameraPermission);}catch(_0x4f2a87){return showToast(_0x323fe0[_0x2a36ff(0x203,'l&at')]('Izin\x20'+_0x2a36ff(0x601,'E*G)')+_0x2a36ff(0x4b4,'zog4')+_0x2a36ff(0xb02,'IdpO'),_0x4f2a87[_0x2a36ff(0x56b,'9)b9')+'ge']||_0x4f2a87['name']));}await stopAndClearScanner(),scannerMode=_0x4fbfdf,scanSessionCount=0x0,lastScannedCode='',lastScannedTime=0x0,document[_0x2a36ff(0x1fa,'13TQ')+_0x2a36ff(0x5a3,'XucK')+_0x2a36ff(0x941,'V64C')](_0x2a36ff(0x940,'khYj')+_0x2a36ff(0x319,')cQA')+_0x2a36ff(0x272,'#HYV')+'e')[_0x2a36ff(0x9da,'dQtf')+_0x2a36ff(0x995,'Vabs')+'t']=_0x2a36ff(0x61e,'l&at')+_0x2a36ff(0x9d5,'gMHR'),document[_0x2a36ff(0x957,'IdpO')+_0x2a36ff(0x8ee,'zog4')+_0x2a36ff(0x750,'PRZ&')]('scanF'+'eedba'+_0x2a36ff(0xb60,'xb!o'))[_0x2a36ff(0x64b,'V64C')]['displ'+'ay']=_0x2a36ff(0x424,'9)b9');const _0x4d2cf4=document['getEl'+_0x2a36ff(0x5a3,'XucK')+_0x2a36ff(0x29a,'rDp@')](_0x323fe0['bEDmF']),_0x1f4607=document[_0x2a36ff(0x91b,'nrxl')+_0x2a36ff(0x200,'eHms')+_0x2a36ff(0xa9c,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')]('chkCo'+_0x2a36ff(0x2b4,'rDp@')+_0x2a36ff(0x6b5,'xb!o')+'an');_0x323fe0[_0x2a36ff(0x5b0,'Z55*')](_0x4fbfdf,_0x2a36ff(0x30f,'xb!o'))?(_0x4d2cf4['style'][_0x2a36ff(0x8ed,'KN]U')+'ay']=_0x323fe0[_0x2a36ff(0x77f,'9)b9')],_0x1f4607[_0x2a36ff(0xb63,'khYj')+'ed']=!![],document[_0x2a36ff(0x2ae,'XucK')+'ement'+_0x2a36ff(0x92a,'a4i]')](_0x2a36ff(0x422,'UbQ2')+'erTit'+'le')[_0x2a36ff(0x34c,'VUa@')+_0x2a36ff(0x46a,'5Hqz')+'t']=_0x323fe0[_0x2a36ff(0x2b9,'!HV9')],document[_0x2a36ff(0xa68,'JSoZ')+_0x2a36ff(0xadb,'](EQ')+_0x2a36ff(0x22c,'utxI')](_0x2a36ff(0x4bf,'q3H^')+_0x2a36ff(0x4b5,'oFps')+'t')[_0x2a36ff(0x497,'VMgj')+_0x2a36ff(0xac8,'$p9U')+'t']=_0x323fe0['OTmOC']):(_0x4d2cf4['style'][_0x2a36ff(0x3a4,'rDp@')+'ay']=_0x323fe0[_0x2a36ff(0x88a,'eHms')],_0x1f4607[_0x2a36ff(0xb63,'khYj')+'ed']=![],document[_0x2a36ff(0x2b2,'gMHR')+_0x2a36ff(0x8ac,'PRZ&')+_0x2a36ff(0x803,'](EQ')](_0x2a36ff(0x65d,'!HV9')+_0x2a36ff(0x53e,'#HYV')+'le')[_0x2a36ff(0x8db,'JSoZ')+'onten'+'t']='Scan\x20'+_0x2a36ff(0xb30,'JSoZ')+_0x2a36ff(0x3b9,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+_0x2a36ff(0xadd,'$p9U'),document[_0x2a36ff(0xa0b,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+_0x2a36ff(0x5da,'Z55*')+'ById'](_0x323fe0['PgaKb'])[_0x2a36ff(0x3cb,'FFZd')+'onten'+'t']=_0x2a36ff(0x269,'dQtf')+_0x2a36ff(0x480,'l&at')+_0x2a36ff(0xa9d,'khYj')+'an\x20me'+_0x2a36ff(0x397,'KghS')+_0x2a36ff(0xad1,'5Hqz')+_0x2a36ff(0x8a2,'bC8p')+'e\x20/\x20S'+'KU');document[_0x2a36ff(0x473,']*Uo')+_0x2a36ff(0x2a2,'khYj')+_0x2a36ff(0x750,'PRZ&')](_0x323fe0[_0x2a36ff(0x8c7,'UbQ2')])[_0x2a36ff(0x51b,'bB4q')+_0x2a36ff(0x7db,'*e]A')][_0x2a36ff(0xa44,'Z55*')](_0x2a36ff(0x5ab,'Vabs')),_0x323fe0['rARLe'](showScanFeedback,_0x2a36ff(0x7b2,'utxI')+_0x2a36ff(0x3e5,'XucK')+_0x2a36ff(0x3dc,'oFps')+_0x2a36ff(0xaf3,'utxI'),![]);try{html5QrScanner=new Html5Qrcode(_0x2a36ff(0x54d,'IhJl')+'deRea'+_0x2a36ff(0x870,'1&H^'),{'verbose':![]});}catch(_0x55b91f){return showToast(_0x2a36ff(0xb17,'IdpO')+'\x20memb'+_0x2a36ff(0x355,'utxI')+_0x2a36ff(0x82d,'eHms')+_0x2a36ff(0x67a,'5Hqz')+(_0x55b91f[_0x2a36ff(0x228,'zog4')+'ge']||_0x55b91f));}const _0x10887f={'fps':0xa,'qrbox':function(_0x3d5c68,_0x257aa7){const _0x3de8e6=_0x2a36ff,_0x333feb=Math[_0x3de8e6(0x415,'IhJl')](_0x3d5c68,_0x257aa7),_0x4d30a7=Math['floor'](_0x333feb*0.85),_0x511c36=Math['floor'](Math[_0x3de8e6(0x236,'bC8p')](_0x333feb*0.45,_0x323fe0[_0x3de8e6(0x9ba,'khYj')](_0x4d30a7,0.55)));return{'width':_0x4d30a7,'height':_0x511c36};},'aspectRatio':1.3333};try{await html5QrScanner['start']({'facingMode':_0x2a36ff(0x2f7,'gMHR')+'onmen'+'t'},_0x10887f,onScanSuccess),scannerRunning=!![],_0x323fe0[_0x2a36ff(0x874,'VMgj')](fixVideoStyle),showScanFeedback(_0x323fe0[_0x2a36ff(0x3c2,'V[]2')],![]);return;}catch(_0x101540){try{const _0x209ac8=await Html5Qrcode[_0x2a36ff(0x476,'VMgj')+_0x2a36ff(0x5ca,'XucK')]();if(_0x209ac8&&_0x209ac8['lengt'+'h']>0x0){let _0x553574=_0x209ac8[_0x2a36ff(0xae6,'gMHR')](_0x54133a=>/back|environment|rear|belakang/i['test'](_0x54133a[_0x2a36ff(0x886,'xb!o')]));if(!_0x553574)_0x553574=_0x209ac8[_0x209ac8[_0x2a36ff(0x218,'bC8p')+'h']-0x1];await html5QrScanner[_0x2a36ff(0xb5e,'dQtf')](_0x553574['id'],_0x10887f,onScanSuccess),scannerRunning=!![],_0x323fe0[_0x2a36ff(0xa65,'a4i]')](fixVideoStyle),showScanFeedback(_0x323fe0[_0x2a36ff(0x748,'zog4')],![]);return;}}catch(_0xe56bf0){}try{await html5QrScanner[_0x2a36ff(0x534,'&v4y')]({'facingMode':_0x2a36ff(0x8a0,'bC8p')},_0x10887f,onScanSuccess),scannerRunning=!![],_0x323fe0[_0x2a36ff(0x210,'a4i]')](fixVideoStyle),showScanFeedback(_0x2a36ff(0x400,'Z55*')+_0x2a36ff(0x4ff,'](EQ')+_0x2a36ff(0x959,'nrxl')+_0x2a36ff(0xa20,'&!DG')+_0x2a36ff(0x7ad,'](EQ')+_0x2a36ff(0x31e,'9)b9')+_0x2a36ff(0xb48,'5Hqz'),![]);return;}catch(_0x10fa0c){}await _0x323fe0[_0x2a36ff(0x9a9,'nrxl')](stopAndClearScanner),document[_0x2a36ff(0x22e,'w2w1')+'ement'+_0x2a36ff(0xb12,'l&at')](_0x2a36ff(0x39b,')cQA')+_0x2a36ff(0x6cd,'13TQ')+'al')[_0x2a36ff(0x6b6,'#HYV')+_0x2a36ff(0x7db,'*e]A')][_0x2a36ff(0x280,'sa(9')+'e'](_0x2a36ff(0x9c7,']4q%')),_0x323fe0[_0x2a36ff(0x487,'^^3k')](showToast,_0x323fe0['WjfAV']+(_0x101540&&(_0x101540[_0x2a36ff(0x58f,'rDp@')+'ge']||_0x101540['name'])||_0x2a36ff(0x8e8,'$p9U')+_0x2a36ff(0xb2e,'eHms')+_0x2a36ff(0x275,'a4i]')));}}function fixVideoStyle(){const _0x173707=_0xadf508,_0x165c24={'jmdRL':_0x173707(0x898,'5Hqz'),'iTDTK':_0x173707(0x67f,'bC8p')+_0x173707(0x257,'Z55*'),'AKMkz':_0x173707(0x49a,'sa(9')+_0x173707(0x9a6,'KN]U')+_0x173707(0x6e6,']4q%'),'QMWCT':_0x173707(0x743,'1&H^')+_0x173707(0x81e,'khYj'),'jBmKR':'objec'+_0x173707(0x6ca,'KN]U')+_0x173707(0x224,'q3H^')+'r','sIzOr':'top:0','kNbsW':_0x173707(0x8c9,'V64C')+_0x173707(0x42f,'l&at')+_0x173707(0x90d,'utxI'),'dtOPX':_0x173707(0x7ce,'rDp@')+_0x173707(0x827,'KghS')+'iv'},_0x5a89b5=document[_0x173707(0xa5f,'](EQ')+'ement'+_0x173707(0xa4b,'!HV9')](_0x173707(0x34f,'ceYQ')+_0x173707(0x2c4,']*Uo')+_0x173707(0xacd,'UbQ2'));if(!_0x5a89b5)return;const _0x2a0e80=_0x5a89b5['query'+_0x173707(0x786,'w2w1')+_0x173707(0x3ca,'XucK')]('video');if(_0x2a0e80){_0x2a0e80[_0x173707(0x7ea,'w2w1')][_0x173707(0xad9,'VMgj')+'xt']=[_0x165c24['AKMkz'],_0x165c24[_0x173707(0x59e,'VMgj')],'heigh'+'t:100'+'%',_0x165c24[_0x173707(0x27e,'Z55*')],_0x173707(0xaac,'nrxl')+_0x173707(0x284,'sa(9')+_0x173707(0x3ae,'XucK')+'te',_0x165c24[_0x173707(0x506,'VUa@')],_0x173707(0xa7d,'^^3k')+'0',_0x173707(0x88d,'5Hqz')+_0x173707(0x680,'q3H^'),_0x165c24[_0x173707(0x7c2,'w2w1')]][_0x173707(0x9e5,'&!DG')](';');const _0x32ef90=()=>{const _0x5e0b12=_0x173707,_0x21448a=_0x2a0e80[_0x5e0b12(0xa09,'FFZd')]();if(_0x21448a&&_0x21448a[_0x5e0b12(0x418,'E*G)')])_0x21448a[_0x5e0b12(0x4f2,'VUa@')](()=>{});};_0x2a0e80[_0x173707(0xa22,'rDp@')+_0x173707(0x755,'#HYV')+_0x173707(0x502,'UbQ2')+'r'](_0x173707(0x890,'!HV9')+_0x173707(0x240,'E*G)')+_0x173707(0x7fc,'FFZd'),_0x32ef90,{'once':!![]}),_0x32ef90();}_0x5a89b5[_0x173707(0x4f1,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+_0x173707(0x8b1,'13TQ')+_0x173707(0x891,'gMHR')+'l'](_0x165c24[_0x173707(0x820,'q3H^')])[_0x173707(0x6ab,')cQA')+'ch'](_0x5d0bcc=>{const _0x41ae57=_0x173707,_0x9e0317=(_0x41ae57(0x901,')cQA')+_0x41ae57(0x7de,'l&at')+'3')[_0x41ae57(0x8ce,']*Uo')]('|');let _0x262505=0x0;while(!![]){switch(_0x9e0317[_0x262505++]){case'0':if(_0x5d0bcc[_0x41ae57(0x810,'^^3k')+_0x41ae57(0x981,'ceYQ')][_0x41ae57(0x899,'VUa@')+_0x41ae57(0x636,'&!DG')](_0x41ae57(0x5cd,'IdpO')+_0x41ae57(0x82b,'JSoZ')))return;continue;case'1':_0x5d0bcc[_0x41ae57(0x305,'5Hqz')]['point'+_0x41ae57(0x467,'!HV9')+'nts']=_0x165c24[_0x41ae57(0x932,']4q%')];continue;case'2':_0x5d0bcc[_0x41ae57(0x2ac,'IhJl')][_0x41ae57(0x572,')cQA')+_0x41ae57(0x9ca,'E*G)')]=_0x165c24[_0x41ae57(0x77d,'nrxl')];continue;case'3':_0x5d0bcc[_0x41ae57(0x3b1,'l&at')][_0x41ae57(0x89a,'utxI')+_0x41ae57(0x39d,'PRZ&')]=_0x41ae57(0x9b9,'sa(9')+_0x41ae57(0x5bf,'JSoZ')+'t';continue;case'4':_0x5d0bcc[_0x41ae57(0x3b8,'IdpO')][_0x41ae57(0x985,'ceYQ')]='0';continue;case'5':_0x5d0bcc[_0x41ae57(0x6e1,'#HYV')][_0x41ae57(0x649,'KN]U')+'x']='2';continue;}break;}});}function onScanSuccess(_0x53dbcf){const _0x1bbf06=_0xadf508,_0x2308a9={'oPnWG':function(_0x231e3f,_0x2bbd6a){return _0x231e3f(_0x2bbd6a);},'HcaMM':function(_0x569bb2,_0x1efcd6){return _0x569bb2<_0x1efcd6;},'CoFan':function(_0x333b08,_0x29029e){return _0x333b08-_0x29029e;},'SvIRe':'POS','AuKQA':function(_0xe308e0,_0x25900,_0x51caf2){return _0xe308e0(_0x25900,_0x51caf2);},'nyEjG':_0x1bbf06(0x838,']4q%')+'an','KDcAg':function(_0x447ba3,_0x14a732){return _0x447ba3+_0x14a732;},'YUCDF':'+1\x20','DBZgY':function(_0x55a46c,_0x579893){return _0x55a46c(_0x579893);},'QosBY':_0x1bbf06(0xab9,'$p9U')+_0x1bbf06(0xa8a,'](EQ')+'\x22','pOymx':function(_0x48db4a){return _0x48db4a();},'vBYzg':_0x1bbf06(0x2a3,'KghS')+_0x1bbf06(0x322,'IdpO')+_0x1bbf06(0x653,'KghS')+'an','cxhFh':'INV','cdRgY':function(_0x160919,_0xa1dffb){return _0x160919+_0xa1dffb;}},_0x213e49=Date['now'](),_0xd745f2=_0x2308a9[_0x1bbf06(0x43e,'JSoZ')](String,_0x53dbcf||'')[_0x1bbf06(0x6f3,'Vabs')]();if(!_0xd745f2)return;if(_0xd745f2[_0x1bbf06(0xa48,'sa(9')+_0x1bbf06(0x3fb,'E*G)')+'e']()===lastScannedCode[_0x1bbf06(0x95f,']*Uo')+_0x1bbf06(0x5aa,'FFZd')+'e']()&&_0x2308a9[_0x1bbf06(0x46f,'nrxl')](_0x2308a9[_0x1bbf06(0xacf,'l&at')](_0x213e49,lastScannedTime),SCAN_DEBOUNCE_MS))return;lastScannedCode=_0xd745f2,lastScannedTime=_0x213e49;if(scannerMode===_0x2308a9[_0x1bbf06(0x9a1,'IdpO')]){const _0x22b8a1=document[_0x1bbf06(0x297,'bC8p')+'ement'+_0x1bbf06(0x650,'#HYV')](_0x1bbf06(0x23a,'khYj')+_0x1bbf06(0x604,'#HYV')+'ousSc'+'an')[_0x1bbf06(0x92e,'#HYV')+'ed'],_0x1c0edb=items[_0x1bbf06(0x6f4,'!HV9')](_0x1f0ff1=>_0x1f0ff1[_0x1bbf06(0xa38,'#HYV')][_0x1bbf06(0x8cd,')cQA')+_0x1bbf06(0x561,'bC8p')+'e']()===_0xd745f2[_0x1bbf06(0x246,'XucK')+_0x1bbf06(0x8b5,'ceYQ')+'e']());if(_0x1c0edb){const _0x4b2d53=_0x2308a9[_0x1bbf06(0x1d8,'oFps')](addToCart,_0x1c0edb['id'],!![]);if(_0x4b2d53){_0x2308a9[_0x1bbf06(0x48f,'](EQ')](playBeep,!![]),vibrate(0x28),scanSessionCount++,document[_0x1bbf06(0x52c,'bB4q')+_0x1bbf06(0x296,'xb!o')+_0x1bbf06(0x208,'E*G)')](_0x1bbf06(0x8f3,'utxI')+_0x1bbf06(0x5d0,'gMHR')+_0x1bbf06(0x379,'9)b9')+'e')[_0x1bbf06(0x4be,'IhJl')+_0x1bbf06(0xad2,'bB4q')+'t']=scanSessionCount+_0x2308a9[_0x1bbf06(0xa96,'VMgj')];const _0x4b7aac=cart[_0x1bbf06(0x4cd,'V[]2')](_0x4003ce=>_0x4003ce['id']===_0x1c0edb['id']),_0x353dcc=_0x4b7aac?_0x4b7aac['qty']:0x1;showScanFeedback(_0x2308a9[_0x1bbf06(0x6e0,'KN]U')]('✔\x20',_0x1c0edb[_0x1bbf06(0x4ce,'utxI')])+'\x20('+_0x353dcc+'x)',![]),showToast(_0x2308a9[_0x1bbf06(0x3ba,'$p9U')](_0x2308a9[_0x1bbf06(0xa28,'](EQ')],_0x1c0edb[_0x1bbf06(0x7eb,'JSoZ')]));}else playBeep(![]),_0x2308a9[_0x1bbf06(0x556,'13TQ')](vibrate,[0x3c,0x28,0x3c]),_0x2308a9[_0x1bbf06(0x70e,'!HV9')](showScanFeedback,_0x1bbf06(0x669,'9)b9')+'k\x20\x22'+_0x1c0edb[_0x1bbf06(0x552,'dQtf')]+(_0x1bbf06(0x5bb,'l&at')+_0x1bbf06(0x35e,'bB4q')+_0x1bbf06(0xa6c,'sa(9')+_0x1bbf06(0x4ab,'utxI')),!![]);}else playBeep(![]),vibrate([0x3c,0x28,0x3c]),showScanFeedback(_0x2308a9[_0x1bbf06(0x685,'*e]A')]+_0xd745f2+(_0x1bbf06(0xa5b,'^^3k')+'ak\x20te'+_0x1bbf06(0x8ba,'E*G)')+_0x1bbf06(0xb3e,'bB4q')),!![]),!_0x22b8a1&&(document[_0x1bbf06(0x75c,'a4i]')+_0x1bbf06(0x709,'l&at')+_0x1bbf06(0x8a6,'oFps')](_0x1bbf06(0x919,'V[]2')+_0x1bbf06(0x948,']4q%'))[_0x1bbf06(0x95b,'w2w1')]=_0xd745f2,_0x2308a9[_0x1bbf06(0xaf8,'13TQ')](renderPOSItems),showToast('Kode\x20'+'\x22'+_0xd745f2+_0x2308a9[_0x1bbf06(0x4aa,'*e]A')]));if(!_0x22b8a1)closeScanner();return;}if(scannerMode===_0x2308a9[_0x1bbf06(0x2d4,'!HV9')]){playBeep(!![]),_0x2308a9[_0x1bbf06(0x94a,'bC8p')](vibrate,0x28),document[_0x1bbf06(0x580,'!HV9')+'ement'+_0x1bbf06(0x22c,'utxI')](_0x1bbf06(0x89c,'bB4q')+_0x1bbf06(0x706,'13TQ'))[_0x1bbf06(0x28e,'#HYV')]=_0xd745f2;const _0x2f507a=items[_0x1bbf06(0x28c,'5Hqz')](_0x4ae6f7=>_0x4ae6f7[_0x1bbf06(0x395,'](EQ')][_0x1bbf06(0x25a,'Vabs')+_0x1bbf06(0x561,'bC8p')+'e']()===_0xd745f2[_0x1bbf06(0x246,'XucK')+_0x1bbf06(0xb1b,'xb!o')+'e']());_0x2f507a?(_0x2308a9[_0x1bbf06(0x859,'xb!o')](editItem,_0x2f507a['id']),showToast(_0x2308a9['KDcAg'](_0x1bbf06(0x3e1,'UbQ2')+_0x1bbf06(0x518,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+_0x1bbf06(0x93b,'](EQ')+'\x20buka'+_0x1bbf06(0x762,'1&H^')+_0x1bbf06(0x460,'JSoZ')+':\x20',_0x2f507a[_0x1bbf06(0x85f,'FFZd')]))):showToast(_0x2308a9[_0x1bbf06(0x691,'13TQ')](_0x1bbf06(0x86b,'V[]2')+'de\x20te'+_0x1bbf06(0x8cc,'VUa@')+_0x1bbf06(0xb07,'sa(9'),_0xd745f2)),closeScanner();}}function switchTab(_0x44824d,_0xeaa08e){const _0x444b19=_0xadf508,_0x21574b={'lWAIi':_0x444b19(0x639,'a4i]')+_0x444b19(0x79d,'5Hqz')+'nt','xthzG':function(_0x3ea743,_0x5b51b5){return _0x3ea743===_0x5b51b5;},'FNWix':_0x444b19(0x3f7,'Z55*'),'mBlTB':_0x444b19(0x93e,'gMHR')+'n','HCGLn':function(_0x483b7c){return _0x483b7c();},'AyaWS':'repor'+'t'};document[_0x444b19(0x943,'bC8p')+_0x444b19(0x9ab,'V[]2')+_0x444b19(0x4b8,'UbQ2')+'l'](_0x21574b[_0x444b19(0xb44,'UbQ2')])[_0x444b19(0x443,'5Hqz')+'ch'](_0x251107=>_0x251107[_0x444b19(0x851,'bC8p')+_0x444b19(0x6bc,'q3H^')][_0x444b19(0x414,'V64C')+'e'](_0x444b19(0x620,'eHms')+'e')),document[_0x444b19(0x842,'*e]A')+_0x444b19(0x86a,'](EQ')+_0x444b19(0x22d,'nrxl')+'l'](_0x444b19(0x55e,'13TQ')+_0x444b19(0x1d6,'VMgj'))[_0x444b19(0x310,'JSoZ')+'ch'](_0x4226ed=>_0x4226ed[_0x444b19(0x3a0,'KN]U')+_0x444b19(0xad0,'13TQ')][_0x444b19(0x8ae,'5Hqz')+'e']('activ'+'e'));const _0xcf0f09=document[_0x444b19(0xb32,'khYj')+_0x444b19(0x6a5,'*e]A')+'ById'](_0x444b19(0x9a3,'rDp@')+_0x44824d);if(_0xcf0f09)_0xcf0f09[_0x444b19(0x960,'l&at')+_0x444b19(0x69b,'zog4')][_0x444b19(0xa94,'oFps')]('activ'+'e');if(_0xeaa08e)_0xeaa08e[_0x444b19(0x409,'KghS')+'List'][_0x444b19(0x720,'dQtf')](_0x444b19(0x61f,'khYj')+'e');if(_0x21574b['xthzG'](_0x44824d,_0x21574b['FNWix']))renderPOSItems();if(_0x44824d===_0x444b19(0x213,'nrxl'))renderInventory();if(_0x21574b[_0x444b19(0x7bf,'q3H^')](_0x44824d,_0x21574b[_0x444b19(0x2ee,']4q%')]))_0x21574b[_0x444b19(0x258,'UbQ2')](renderMarginTab);if(_0x21574b[_0x444b19(0x583,'V64C')](_0x44824d,_0x21574b[_0x444b19(0x8d7,'IdpO')]))renderReport();}function getUniqueClusters(){const _0x38b49b=_0xadf508,_0x4080d4=new Set(items[_0x38b49b(0x270,'*e]A')](_0x197d48=>(_0x197d48[_0x38b49b(0x6aa,'xb!o')+'er']||_0x38b49b(0x2af,'rDp@'))['trim']())[_0x38b49b(0x846,'VUa@')+'r'](Boolean));return Array[_0x38b49b(0x87b,'13TQ')](_0x4080d4)[_0x38b49b(0x30e,'](EQ')]();}function syncClusterDropdowns(){const _0x3d680e=_0xadf508,_0x215cb7={'WCrSb':'posCl'+'uster'+_0x3d680e(0xa41,'#HYV')+'r','BKAeN':_0x3d680e(0x46d,'eHms')+_0x3d680e(0x6b7,'13TQ')+'et'},_0x493091=getUniqueClusters(),_0x24b9d4=document[_0x3d680e(0x7f6,'E*G)')+'ement'+_0x3d680e(0x941,'V64C')](_0x215cb7[_0x3d680e(0x21b,'khYj')]),_0x4fbbdb=_0x24b9d4[_0x3d680e(0x65c,'IhJl')];_0x24b9d4[_0x3d680e(0x4f7,'l&at')+_0x3d680e(0x2d8,'1&H^')]=_0x3d680e(0x792,'JSoZ')+_0x3d680e(0x3e9,'$p9U')+_0x3d680e(0x316,'VMgj')+'ALL\x22>'+_0x3d680e(0x223,'!HV9')+_0x3d680e(0x4c6,'PRZ&')+_0x3d680e(0xa3e,'l&at')+'optio'+'n>'+_0x493091[_0x3d680e(0x6d6,'VMgj')](_0x8deee2=>_0x3d680e(0x547,'!HV9')+'on\x20va'+_0x3d680e(0x48e,'Z55*')+esc(_0x8deee2)+'\x22>'+esc(_0x8deee2)+(_0x3d680e(0x2f5,'!HV9')+_0x3d680e(0x442,'5Hqz')))[_0x3d680e(0xab1,'Vabs')]('');if(_0x493091[_0x3d680e(0x82c,'q3H^')+_0x3d680e(0x7af,'gMHR')](_0x4fbbdb))_0x24b9d4[_0x3d680e(0x9ec,'xb!o')]=_0x4fbbdb;const _0x410d84=document['getEl'+_0x3d680e(0x4d2,'&!DG')+_0x3d680e(0x631,'ceYQ')](_0x215cb7[_0x3d680e(0x37f,'XucK')]),_0x76157=_0x410d84[_0x3d680e(0x2e7,'Z55*')];_0x410d84['inner'+_0x3d680e(0x64a,'V[]2')]=_0x3d680e(0x958,'V[]2')+_0x3d680e(0x4de,'KN]U')+_0x3d680e(0x9bf,')cQA')+_0x3d680e(0xa9f,'nrxl')+_0x3d680e(0x1ea,'1&H^')+'\x20Item'+_0x3d680e(0x712,']4q%')+_0x3d680e(0x27a,'!HV9')+_0x3d680e(0x597,'E*G)')+_0x3d680e(0x6ff,'IhJl')+_0x493091[_0x3d680e(0x782,'ceYQ')](_0x4d6e24=>_0x3d680e(0x754,'13TQ')+_0x3d680e(0x689,'xb!o')+_0x3d680e(0xa5d,'#HYV')+esc(_0x4d6e24)+(_0x3d680e(0x5fa,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+_0x3d680e(0x714,'VUa@')+'\x20')+esc(_0x4d6e24)+(_0x3d680e(0xaa6,'KghS')+'ion>'))[_0x3d680e(0x9e0,'a4i]')]('');if(_0x493091[_0x3d680e(0x59f,'5Hqz')+_0x3d680e(0x4c9,'#HYV')](_0x76157))_0x410d84[_0x3d680e(0x94e,'JSoZ')]=_0x76157;document[_0x3d680e(0x2b2,'gMHR')+'ement'+'ById'](_0x3d680e(0xb56,'IdpO')+_0x3d680e(0x65f,'sa(9')+'gesti'+_0x3d680e(0x9c4,'w2w1'))[_0x3d680e(0x5db,'PRZ&')+'HTML']=_0x493091[_0x3d680e(0x6d6,'VMgj')](_0x523732=>_0x3d680e(0x958,'V[]2')+_0x3d680e(0x57f,'V[]2')+_0x3d680e(0x41b,'&!DG')+esc(_0x523732)+(_0x3d680e(0x9e8,'$p9U')+_0x3d680e(0x225,'*e]A')+'>'))[_0x3d680e(0x671,'KghS')]('');}function renderPOSItems(){const _0x37975c=_0xadf508,_0x37f31c={'VwWep':function(_0x4592b8,_0x1a1430){return _0x4592b8===_0x1a1430;},'OfLUc':function(_0x205294,_0x2a6a38){return _0x205294+_0x2a6a38;},'zASXZ':function(_0x45a5c1,_0x13142a){return _0x45a5c1+_0x13142a;},'oehWn':function(_0x30adee,_0x602169){return _0x30adee+_0x602169;},'xcUEF':function(_0x438715,_0x3af1ee){return _0x438715+_0x3af1ee;},'NRrLy':function(_0x4342cb,_0x164c48){return _0x4342cb+_0x164c48;},'WxvqD':function(_0x13954d,_0x50bdff){return _0x13954d+_0x50bdff;},'rXBfY':_0x37975c(0x819,')cQA')+_0x37975c(0x6b1,'rDp@')+_0x37975c(0x6f1,'VMgj')+_0x37975c(0x33e,'1&H^')+_0x37975c(0xb00,']4q%')+_0x37975c(0x963,'KN]U')+_0x37975c(0x387,'&v4y')+_0x37975c(0xaef,'a4i]')+_0x37975c(0x4af,'9)b9')+_0x37975c(0x84a,'JSoZ'),'wLTPb':function(_0x40c597,_0x33751d){return _0x40c597(_0x33751d);},'GOgvC':'Kode:'+'\x20','AIUEj':_0x37975c(0x35c,'l&at')+'ok:\x20<'+'stron'+'g>','FyLhE':_0x37975c(0x36a,']4q%')+_0x37975c(0x798,'13TQ')+_0x37975c(0x806,'sa(9'),'iNxEo':_0x37975c(0x8e1,'Vabs')+'on\x20cl'+_0x37975c(0x3b3,'bC8p')+_0x37975c(0x3f4,'VUa@')+'tn-pr'+_0x37975c(0x295,'9)b9')+_0x37975c(0x66a,'KghS')+'sm\x22\x20','QzCYV':'disab'+_0x37975c(0x688,'rDp@'),'plNMy':_0x37975c(0x530,'V64C')+'>','TLeJR':_0x37975c(0x59a,'$p9U')+'arch','NWFDV':'posCl'+_0x37975c(0x8ea,'13TQ')+_0x37975c(0x925,'a4i]')+'r','EbHzf':_0x37975c(0x1f9,'rDp@')+_0x37975c(0x8d4,'&!DG')+'nt','eJhdY':function(_0x889531,_0x1b5a17){return _0x889531+_0x1b5a17;}};syncClusterDropdowns();const _0x83ffcf=(document[_0x37975c(0x2ce,')cQA')+'ement'+_0x37975c(0x546,'Vabs')](_0x37f31c[_0x37975c(0xa13,'V64C')])[_0x37975c(0xb54,'](EQ')]||'')[_0x37975c(0x4c3,'gMHR')+_0x37975c(0x4e6,')cQA')+'e'](),_0x48380b=document[_0x37975c(0x5f6,'VUa@')+_0x37975c(0x5a3,'XucK')+_0x37975c(0x631,'ceYQ')](_0x37f31c[_0x37975c(0x82f,'gMHR')])['value'],_0xf5fc32=items['filte'+'r'](_0x3db89a=>{const _0x3193ac=_0x37975c,_0x15b530=_0x3db89a[_0x3193ac(0x6ce,'](EQ')][_0x3193ac(0x3e3,'Z55*')+_0x3193ac(0x9c9,'1&H^')+'e']()[_0x3193ac(0xa23,')cQA')+_0x3193ac(0x53b,'eHms')](_0x83ffcf)||_0x3db89a['code'][_0x3193ac(0x67d,'bC8p')+_0x3193ac(0x5aa,'FFZd')+'e']()[_0x3193ac(0x94c,'](EQ')+'des'](_0x83ffcf),_0x55535c=_0x37f31c[_0x3193ac(0xafe,'nrxl')](_0x48380b,'ALL')||_0x3db89a['clust'+'er']===_0x48380b;return _0x15b530&&_0x55535c;});document[_0x37975c(0x91b,'nrxl')+'ement'+_0x37975c(0x51c,'^^3k')](_0x37f31c[_0x37975c(0x20e,'XucK')])[_0x37975c(0x1f8,'](EQ')+_0x37975c(0x1f2,'!HV9')+'t']=_0x37f31c['eJhdY'](_0xf5fc32[_0x37975c(0x9e2,'dQtf')+'h'],_0x37975c(0xae5,'ceYQ'));const _0x181382=document[_0x37975c(0x22e,'w2w1')+_0x37975c(0x849,'VUa@')+_0x37975c(0x3a9,'*e]A')](_0x37975c(0x3d3,'l&at')+_0x37975c(0xa2a,'^^3k')+_0x37975c(0x732,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz'));if(_0x37f31c['VwWep'](_0xf5fc32[_0x37975c(0x7dd,'UbQ2')+'h'],0x0)){_0x181382[_0x37975c(0x75b,'Z55*')+_0x37975c(0x8dc,'V64C')]=_0x37975c(0x71e,'bC8p')+_0x37975c(0xb18,'Vabs')+'empty'+_0x37975c(0x70b,'^^3k')+_0x37975c(0x49b,'#HYV')+_0x37975c(0x63a,'Z55*')+'tidak'+_0x37975c(0x6dc,'Vabs')+_0x37975c(0x4d7,'eHms')+_0x37975c(0x31c,'Z55*');return;}_0x181382[_0x37975c(0x30a,'!HV9')+'HTML']=_0xf5fc32[_0x37975c(0x7b4,'w2w1')](_0x10dede=>{const _0x222fa9=_0x37975c,_0x16c270=_0x10dede[_0x222fa9(0x2f4,'xb!o')]<=0x0;return _0x37f31c[_0x222fa9(0x9fd,'FFZd')](_0x37f31c['OfLUc'](_0x37f31c[_0x222fa9(0x251,'13TQ')](_0x37f31c[_0x222fa9(0xb4e,'E*G)')](_0x37f31c[_0x222fa9(0x904,'zog4')](_0x37f31c[_0x222fa9(0x775,']4q%')](_0x37f31c[_0x222fa9(0x7ca,'eHms')](_0x37f31c[_0x222fa9(0xb55,'UbQ2')](_0x37f31c[_0x222fa9(0x8bc,'ceYQ')](_0x37f31c[_0x222fa9(0x4b2,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')](_0x37f31c['xcUEF'](_0x37f31c[_0x222fa9(0x24a,'bB4q')](_0x37f31c[_0x222fa9(0x4e2,'sa(9')]('',_0x222fa9(0x347,'utxI')+_0x222fa9(0x535,'1&H^')+_0x222fa9(0xa7c,'VUa@')+_0x222fa9(0x325,'V64C')+'min-w'+_0x222fa9(0x7d9,'V[]2')+_0x222fa9(0x4c0,'xb!o')),_0x37f31c[_0x222fa9(0x377,'eHms')])+_0x37f31c[_0x222fa9(0x931,'9)b9')](esc,_0x10dede[_0x222fa9(0x21e,'XucK')]),_0x222fa9(0xacb,'IhJl')+'>'),_0x222fa9(0x410,'V[]2')+'class'+_0x222fa9(0x431,'E*G)')+_0x222fa9(0x47c,'KghS')+_0x222fa9(0x6ee,'V[]2')+_0x222fa9(0x626,'dQtf')+_0x222fa9(0x75e,'sa(9')+_0x222fa9(0x84d,'eHms'))+esc(_0x10dede[_0x222fa9(0x722,'JSoZ')+'er']),_0x222fa9(0xb0a,'VUa@')+_0x222fa9(0x27f,'nrxl')),_0x37f31c[_0x222fa9(0x8e0,'#HYV')])+_0x37f31c[_0x222fa9(0xa98,'KN]U')](esc,_0x10dede['code'])+_0x37f31c[_0x222fa9(0xa54,'$p9U')],_0x10dede['qty'])+_0x37f31c['FyLhE']+(_0x222fa9(0xa93,'khYj')+_0x222fa9(0x46e,'](EQ')+_0x222fa9(0x7f2,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+_0x222fa9(0x95d,'bB4q')+_0x222fa9(0x3c0,'khYj')),formatRp(_0x10dede['sellP'+_0x222fa9(0x8c4,'xb!o')])),'')+('')+_0x37f31c[_0x222fa9(0x46c,'sa(9')],_0x16c270?_0x37f31c[_0x222fa9(0x529,'a4i]')]:''),_0x222fa9(0x980,'^^3k')+_0x222fa9(0xa92,'sa(9')+_0x222fa9(0x7b3,'&!DG')+_0x222fa9(0x212,'5Hqz')+'\x27'),_0x10dede['id']),_0x222fa9(0x5c3,'rDp@')+_0x222fa9(0x79f,'oFps')+'ah')+_0x37f31c[_0x222fa9(0x33a,'l&at')];})[_0x37975c(0x6c6,'#HYV')]('');}function addToCart(_0x344941,_0x8adcce){const _0x118123=_0xadf508,_0x5f9f0b={'aLlZJ':_0x118123(0x84f,'oFps')+_0x118123(0x6c8,'VMgj')+_0x118123(0xaa5,'w2w1')+_0x118123(0x8cf,'$p9U')+_0x118123(0x40e,'&v4y')},_0xf8b95d=items[_0x118123(0xa64,'utxI')](_0x162efb=>_0x162efb['id']===_0x344941);if(!_0xf8b95d||_0xf8b95d[_0x118123(0x42b,'utxI')]<=0x0){if(!_0x8adcce)showToast(_0x118123(0x495,'1&H^')+_0x118123(0x268,']4q%')+'!');return![];}const _0x491e05=cart[_0x118123(0x23d,'bC8p')](_0x1119b9=>_0x1119b9['id']===_0x344941);if(_0x491e05){if(_0x491e05[_0x118123(0xa91,'bC8p')]>=_0xf8b95d[_0x118123(0xac1,'sa(9')]){if(!_0x8adcce)showToast(_0x5f9f0b['aLlZJ']);return![];}_0x491e05[_0x118123(0x9bb,'gMHR')]+=0x1;}else cart[_0x118123(0x2b7,'KghS')]({'id':_0xf8b95d['id'],'code':_0xf8b95d['code'],'name':_0xf8b95d['name'],'cluster':_0xf8b95d[_0x118123(0xb1f,'zog4')+'er'],'buyPrice':_0xf8b95d[_0x118123(0x201,'9)b9')+'ice'],'sellPrice':_0xf8b95d[_0x118123(0xb50,'XucK')+_0x118123(0x7f9,'XucK')],'qty':0x1});return renderCart(),!![];}function updateCartQty(_0x245504,_0x173a2e){const _0x1fd0d6=_0xadf508,_0x42dbac={'cJRIL':function(_0x442ff4,_0x4c4ad8){return _0x442ff4+_0x4c4ad8;}},_0x269563=cart[_0x1fd0d6(0xace,'](EQ')+_0x1fd0d6(0x462,'E*G)')](_0x1e2df6=>_0x1e2df6['id']===_0x245504);if(_0x269563===-0x1)return;const _0x3eaf36=items[_0x1fd0d6(0x1d0,'w2w1')](_0x5e9f0e=>_0x5e9f0e['id']===_0x245504),_0xbadc64=_0x42dbac['cJRIL'](cart[_0x269563][_0x1fd0d6(0x7cd,'V[]2')],_0x173a2e);if(_0xbadc64<=0x0)cart[_0x1fd0d6(0x6fc,'V[]2')+'e'](_0x269563,0x1);else{if(_0x3eaf36&&_0xbadc64>_0x3eaf36[_0x1fd0d6(0x507,'IdpO')])return showToast(_0x1fd0d6(0x7aa,'V[]2')+'tidak'+'\x20menc'+'ukupi');else cart[_0x269563][_0x1fd0d6(0xa62,'nrxl')]=_0xbadc64;}renderCart();}function clearCart(){const _0xfd235f=_0xadf508,_0x599104={'CjmmG':_0xfd235f(0x587,'FFZd')+_0xfd235f(0x756,'bB4q')+'nt','akpjT':function(_0x825cb3){return _0x825cb3();}};cart=[],document[_0xfd235f(0x91b,'nrxl')+_0xfd235f(0x76a,'&v4y')+_0xfd235f(0x733,'Z55*')](_0x599104[_0xfd235f(0xaea,'khYj')])[_0xfd235f(0x52e,'13TQ')]=0x0,document[_0xfd235f(0x2b2,'gMHR')+_0xfd235f(0x2fc,'bB4q')+'ById'](_0xfd235f(0x739,'PRZ&')+_0xfd235f(0x420,'KN]U'))[_0xfd235f(0x58b,'XucK')]='',_0x599104[_0xfd235f(0x435,'a4i]')](renderCart);}function renderCart(){const _0x20a2d2=_0xadf508,_0x5bede2={'UUiOw':function(_0x26f397,_0x5970b7){return _0x26f397===_0x5970b7;},'ENPHq':_0x20a2d2(0x2b0,'PRZ&')+_0x20a2d2(0x26e,'](EQ')+_0x20a2d2(0x673,'oFps')+_0x20a2d2(0x50e,'V[]2')+_0x20a2d2(0xa89,'V[]2')+_0x20a2d2(0x867,'rDp@')+_0x20a2d2(0x398,'KghS')+_0x20a2d2(0x510,'eHms')+_0x20a2d2(0x3bb,'rDp@')+_0x20a2d2(0x31c,'Z55*'),'EHTkk':function(_0x479d75,_0x351b41){return _0x479d75(_0x351b41);},'pLlYR':function(_0x1aca3a,_0x55a9d8){return _0x1aca3a-_0x55a9d8;},'wzJGv':function(_0x4ba508,_0x5f4912){return _0x4ba508(_0x5f4912);},'NQzAD':'cartP'+_0x20a2d2(0x420,'KN]U'),'gsiWt':_0x20a2d2(0x407,'IdpO')+_0x20a2d2(0x8fb,'utxI')+_0x20a2d2(0x48b,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz'),'kpUKO':function(_0x3f8466,_0x490b67){return _0x3f8466(_0x490b67);},'Xcgre':_0x20a2d2(0x793,'l&at')+_0x20a2d2(0x349,'KN]U')+_0x20a2d2(0x576,'xb!o')},_0x882269=document['getEl'+_0x20a2d2(0x519,'5Hqz')+_0x20a2d2(0x986,'UbQ2')](_0x20a2d2(0x25f,'khYj')+_0x20a2d2(0x1dd,'&v4y'));_0x5bede2[_0x20a2d2(0x98d,'KN]U')](cart[_0x20a2d2(0xb6e,'ceYQ')+'h'],0x0)?_0x882269[_0x20a2d2(0x7cb,'bB4q')+_0x20a2d2(0x66c,'bC8p')]=_0x5bede2[_0x20a2d2(0x5d7,'FFZd')]:_0x882269['inner'+_0x20a2d2(0x3b2,'!HV9')]=cart[_0x20a2d2(0xa0d,'#HYV')](_0x3dab84=>''+(_0x20a2d2(0xaa0,'eHms')+_0x20a2d2(0x430,'^^3k')+_0x20a2d2(0xa3a,'KghS')+_0x20a2d2(0x3f1,'w2w1')+_0x20a2d2(0x861,'q3H^')+_0x20a2d2(0x9ae,'PRZ&')+'0;\x22>')+(_0x20a2d2(0x7be,'bC8p')+'style'+_0x20a2d2(0x610,'PRZ&')+_0x20a2d2(0x33e,'1&H^')+_0x20a2d2(0x6a4,'l&at')+_0x20a2d2(0x8d5,'9)b9')+_0x20a2d2(0x55f,'1&H^')+_0x20a2d2(0x7f8,'IhJl')+_0x20a2d2(0xb16,'PRZ&')+_0x20a2d2(0x738,'FFZd'))+esc(_0x3dab84[_0x20a2d2(0x339,'w2w1')])+(_0x20a2d2(0x307,'nrxl')+'>')+('')+formatRp(_0x3dab84[_0x20a2d2(0x292,'9)b9')+_0x20a2d2(0x945,'&!DG')]*_0x3dab84['qty'])+(_0x20a2d2(0x8d0,'zog4')+_0x20a2d2(0x7bb,'Vabs')+_0x20a2d2(0x7dc,'zog4'))+(_0x20a2d2(0x5c0,'Vabs')+'>')+(_0x20a2d2(0x836,'zog4')+_0x20a2d2(0x9d6,'E*G)')+'=\x22dis'+_0x20a2d2(0x8c0,'Vabs')+'flex;'+_0x20a2d2(0x3a1,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+_0x20a2d2(0x779,'$p9U')+_0x20a2d2(0x2d5,'rDp@')+_0x20a2d2(0x8e5,'VMgj')+_0x20a2d2(0x690,'1&H^')+_0x20a2d2(0x3e4,'bC8p')+'>')+('-<'+_0x20a2d2(0x6c3,'VUa@')+_0x20a2d2(0x3fc,'&!DG'))+(_0x20a2d2(0xa21,'](EQ')+_0x20a2d2(0x20f,'*e]A')+_0x20a2d2(0x6dd,'UbQ2')+_0x20a2d2(0x311,'9)b9')+_0x20a2d2(0x62f,'KghS')+_0x20a2d2(0x74e,'w2w1')+_0x20a2d2(0x95e,'&v4y')+_0x20a2d2(0x5fc,'!HV9')+'22px;'+_0x20a2d2(0x9a4,'sa(9')+_0x20a2d2(0x8a8,'zog4')+_0x20a2d2(0xa4e,'](EQ')+_0x20a2d2(0x7f4,'5Hqz')+'>')+_0x3dab84[_0x20a2d2(0x504,'JSoZ')]+(_0x20a2d2(0xa6f,'&v4y')+'n>')+(_0x20a2d2(0x39a,'V[]2')+_0x20a2d2(0x5dc,'V64C')+_0x20a2d2(0x4cc,'9)b9')+_0x20a2d2(0x7bd,']*Uo')+_0x20a2d2(0xa2b,'13TQ')+'tline'+_0x20a2d2(0x4c1,'utxI')+_0x20a2d2(0xac9,'*e]A')+_0x20a2d2(0x340,'^^3k')+'k=\x22up'+_0x20a2d2(0x8a1,'VUa@')+_0x20a2d2(0xa10,'ceYQ')+_0x20a2d2(0x2b1,'$p9U'))+_0x3dab84['id']+('\x27,\x201)'+'\x22>+')+(_0x20a2d2(0xb3c,'xb!o')+'>')+(_0x20a2d2(0x4ef,'utxI')+'>'))[_0x20a2d2(0x7b0,'oFps')]('');const _0x5b0978=cart[_0x20a2d2(0x68c,'E*G)')+'e']((_0x4138f2,_0x3ac508)=>_0x4138f2+_0x3ac508['sellP'+_0x20a2d2(0xafa,'a4i]')]*_0x3ac508[_0x20a2d2(0x2cf,'E*G)')],0x0),_0x4e3968=cart[_0x20a2d2(0x4a7,'13TQ')+'e']((_0x919f69,_0x3f60af)=>_0x919f69+_0x3f60af[_0x20a2d2(0x737,'l&at')+'ice']*_0x3f60af[_0x20a2d2(0x86c,'1&H^')],0x0),_0x566d63=Math['max'](0x0,_0x5bede2[_0x20a2d2(0x44f,'&!DG')](Number,document[_0x20a2d2(0x640,'PRZ&')+_0x20a2d2(0x3f0,'sa(9')+_0x20a2d2(0x965,'FFZd')](_0x20a2d2(0x25b,'V[]2')+_0x20a2d2(0x598,'VUa@')+'nt')[_0x20a2d2(0x375,'1&H^')])||0x0),_0x26fa94=Math['max'](0x0,_0x5b0978-_0x566d63),_0x25e79c=_0x5bede2[_0x20a2d2(0x971,'Vabs')](_0x26fa94,_0x4e3968),_0x510cb3=_0x5bede2['wzJGv'](Number,document['getEl'+_0x20a2d2(0x3d6,']*Uo')+_0x20a2d2(0x1ef,'bC8p')](_0x5bede2['NQzAD'])[_0x20a2d2(0x28a,'eHms')])||0x0,_0x4f6fa4=Math['max'](0x0,_0x510cb3-_0x26fa94);document[_0x20a2d2(0x747,'#HYV')+'ement'+_0x20a2d2(0x3a9,'*e]A')](_0x20a2d2(0x479,'utxI')+_0x20a2d2(0x9c5,'^^3k')+'total')[_0x20a2d2(0x905,'a4i]')+'onten'+'t']=formatRp(_0x5b0978),document[_0x20a2d2(0x93a,'*e]A')+_0x20a2d2(0x344,'nrxl')+_0x20a2d2(0x7da,'KghS')](_0x5bede2[_0x20a2d2(0x494,'!HV9')])['textC'+_0x20a2d2(0x5f4,'dQtf')+'t']=_0x5bede2[_0x20a2d2(0xae4,'IdpO')](formatRp,_0x25e79c),document[_0x20a2d2(0x83d,'utxI')+_0x20a2d2(0x2e3,'gMHR')+_0x20a2d2(0x750,'PRZ&')](_0x20a2d2(0x6f9,'bB4q')+_0x20a2d2(0x700,'VMgj')+'al')[_0x20a2d2(0x40d,'9)b9')+'onten'+'t']=formatRp(_0x26fa94),document[_0x20a2d2(0x368,'V64C')+_0x20a2d2(0x62d,'bC8p')+'ById'](_0x5bede2['Xcgre'])[_0x20a2d2(0x2f9,'E*G)')+_0x20a2d2(0x6b9,'rDp@')+'t']=formatRp(_0x4f6fa4);}function checkout(){const _0x3ab49f=_0xadf508,_0x2a9156={'ZwfSg':function(_0x36e08c,_0x594b29){return _0x36e08c-_0x594b29;},'wuqXO':function(_0x56c962,_0x25b219){return _0x56c962(_0x25b219);},'tyJBY':_0x3ab49f(0x704,'](EQ')+_0x3ab49f(0x8f0,'#HYV')+'nt','bDWoO':_0x3ab49f(0x285,'*e]A')+_0x3ab49f(0x5b4,'&!DG'),'BSrWu':function(_0x228b4a,_0x41145e){return _0x228b4a(_0x41145e);},'xgcJp':_0x3ab49f(0x20a,'nrxl')+_0x3ab49f(0x4d3,'bC8p')+_0x3ab49f(0x4df,'VUa@')+'sil\x20d'+_0x3ab49f(0x79e,'&!DG')+'an!'};if(cart['lengt'+'h']===0x0)return _0x2a9156['wuqXO'](showToast,'Pilih'+_0x3ab49f(0x5a7,'9)b9')+_0x3ab49f(0x32b,'#HYV')+'rlebi'+_0x3ab49f(0x6af,')cQA')+_0x3ab49f(0x353,'#HYV'));const _0x4722a2=cart[_0x3ab49f(0x611,'bB4q')+'e']((_0x289d28,_0x9f2618)=>_0x289d28+_0x9f2618['sellP'+_0x3ab49f(0xb6f,'rDp@')]*_0x9f2618['qty'],0x0),_0x526452=cart[_0x3ab49f(0xa73,'oFps')+'e']((_0x4cf4ea,_0x16a52b)=>_0x4cf4ea+_0x16a52b[_0x3ab49f(0xb61,'rDp@')+_0x3ab49f(0x77b,'!HV9')]*_0x16a52b['qty'],0x0),_0x453dec=Math['max'](0x0,Number(document[_0x3ab49f(0x4b6,'9)b9')+'ement'+_0x3ab49f(0x6cf,'nrxl')](_0x2a9156[_0x3ab49f(0xa1c,'Z55*')])['value'])||0x0),_0x2e5308=Math[_0x3ab49f(0x483,'&v4y')](0x0,_0x4722a2-_0x453dec),_0xa432=Number(document['getEl'+_0x3ab49f(0x2fb,'13TQ')+_0x3ab49f(0x788,'&!DG')](_0x2a9156[_0x3ab49f(0x6b8,'bB4q')])[_0x3ab49f(0x554,'VUa@')])||_0x2e5308;if(_0xa432<_0x2e5308)return _0x2a9156[_0x3ab49f(0xa46,'rDp@')](showToast,_0x3ab49f(0x3cd,'Z55*')+_0x3ab49f(0x920,'q3H^')+_0x3ab49f(0x30d,'nrxl')+_0x3ab49f(0x384,'dQtf')+_0x3ab49f(0x2da,'a4i]')+'tal!');cart[_0x3ab49f(0x3a2,'gMHR')+'ch'](_0x4c4879=>{const _0x25c5cf=_0x3ab49f,_0x27c85d=items[_0x25c5cf(0x4cd,'V[]2')](_0x562e35=>_0x562e35['id']===_0x4c4879['id']);if(_0x27c85d)_0x27c85d['qty']=Math[_0x25c5cf(0x483,'&v4y')](0x0,_0x2a9156[_0x25c5cf(0x454,'PRZ&')](_0x27c85d['qty'],_0x4c4879[_0x25c5cf(0x86f,'a4i]')]));});const _0x53d610=new Date(),_0x56ccba={'id':_0x3ab49f(0x758,'l&at')+_0x53d610[_0x3ab49f(0x871,'ceYQ')+'me'](),'timestamp':_0x53d610[_0x3ab49f(0x8c3,'VUa@')+'Strin'+'g'](),'dateStr':_0x53d610[_0x3ab49f(0x8d2,')cQA')+_0x3ab49f(0x4e5,'dQtf')+'g']()[_0x3ab49f(0x374,'a4i]')]('T')[0x0],'items':JSON[_0x3ab49f(0x918,'utxI')](JSON[_0x3ab49f(0x509,'!HV9')+_0x3ab49f(0xb45,'gMHR')](cart)),'totalQty':cart[_0x3ab49f(0x531,'IdpO')+'e']((_0x3142c7,_0x1d563b)=>_0x3142c7+_0x1d563b[_0x3ab49f(0x76c,'#HYV')],0x0),'subtotal':_0x4722a2,'discount':_0x453dec,'total':_0x2e5308,'paid':_0xa432,'change':_0xa432-_0x2e5308,'cost':_0x526452,'profit':_0x2e5308-_0x526452};sales[_0x3ab49f(0xa84,'XucK')+'ft'](_0x56ccba),saveState(),clearCart(),renderPOSItems(),openPrintModal(_0x56ccba),showToast(_0x2a9156['xgcJp']);}function previewItemMargin(){const _0x41a3d9=_0xadf508,_0x56a397={'mMtFM':_0x41a3d9(0xb19,'rDp@')+_0x41a3d9(0x222,'UbQ2')+_0x41a3d9(0xa3c,'ceYQ')+'ew','rKjWp':function(_0x3a2937,_0x451f01){return _0x3a2937+_0x451f01;}},_0x261317=Number(document[_0x41a3d9(0x7a9,'dQtf')+_0x41a3d9(0x9cf,'E*G)')+'ById']('itemB'+'uy')[_0x41a3d9(0x59d,'PRZ&')])||0x0,_0x5ad568=Number(document[_0x41a3d9(0x3e8,'FFZd')+'ement'+_0x41a3d9(0x546,'Vabs')](_0x41a3d9(0xb6c,'5Hqz')+_0x41a3d9(0x5d3,'!HV9'))[_0x41a3d9(0x95c,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')])||0x0,_0x1414e5=_0x5ad568-_0x261317,_0x3b31d2=_0x261317>0x0?(_0x1414e5/_0x261317*0x64)[_0x41a3d9(0x35a,'Vabs')+'ed'](0x1):'0';document[_0x41a3d9(0xb32,'khYj')+'ement'+_0x41a3d9(0x9ea,'5Hqz')](_0x56a397[_0x41a3d9(0x7b6,'13TQ')])[_0x41a3d9(0x35b,'ceYQ')+_0x41a3d9(0x969,'KN]U')+'t']=_0x56a397[_0x41a3d9(0x781,'KN]U')](_0x41a3d9(0x39c,'IhJl')+_0x41a3d9(0x53c,'rDp@'),formatRp(_0x1414e5))+'\x20('+_0x3b31d2+'%)';}function saveItem(){const _0x49079f=_0xadf508,_0x34596f={'aMluK':_0x49079f(0xb23,'1&H^')+'ty','yycdv':function(_0x1e4a46,_0x8fd7d0){return _0x1e4a46(_0x8fd7d0);},'kCelZ':_0x49079f(0x309,'&v4y')+'uy','mHojc':_0x49079f(0xb6c,'5Hqz')+_0x49079f(0xa80,'13TQ'),'kpnVn':_0x49079f(0xb52,')cQA')+_0x49079f(0x80b,'dQtf')+_0x49079f(0x447,'9)b9')+_0x49079f(0x6d2,'dQtf')+'i!','EKIaG':function(_0x5928d9,_0x43d42c){return _0x5928d9!==_0x43d42c;},'yzXTc':function(_0x3f6449,_0x5ebb45){return _0x3f6449(_0x5ebb45);},'wDfsj':_0x49079f(0x908,'ceYQ')+_0x49079f(0x26c,'!HV9')+_0x49079f(0x50d,'gMHR'),'IoaXM':function(_0x67180b){return _0x67180b();}},_0x3ea693=document[_0x49079f(0x91b,'nrxl')+_0x49079f(0x78a,'oFps')+_0x49079f(0x7da,'KghS')](_0x49079f(0x9ad,'#HYV')+_0x49079f(0x744,'UbQ2'))[_0x49079f(0x28e,'#HYV')],_0x57eec1=document['getEl'+'ement'+_0x49079f(0xa9c,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')](_0x49079f(0xa57,'rDp@')+_0x49079f(0x5e4,'5Hqz'))[_0x49079f(0x28a,'eHms')]['trim']()||'SKU-'+Date[_0x49079f(0x865,'utxI')]()[_0x49079f(0x2a9,'E*G)')+_0x49079f(0x293,'ceYQ')]()[_0x49079f(0x277,'JSoZ')](-0x5),_0x5ce93c=document[_0x49079f(0x632,'KghS')+'ement'+_0x49079f(0xb5b,'IdpO')](_0x49079f(0xa59,'q3H^')+'luste'+'r')[_0x49079f(0x52e,'13TQ')]['trim']()||_0x49079f(0x71d,'13TQ'),_0x39d361=document['getEl'+_0x49079f(0x849,'VUa@')+'ById'](_0x49079f(0x549,'zog4')+_0x49079f(0xad4,']*Uo'))['value'][_0x49079f(0xb57,'V[]2')](),_0x1f5ea5=Math['max'](0x0,Number(document[_0x49079f(0x589,'l&at')+_0x49079f(0x7fb,'!HV9')+'ById'](_0x34596f[_0x49079f(0x25e,'5Hqz')])['value'])||0x0),_0x4ef6e4=Math['max'](0x0,_0x34596f[_0x49079f(0x9ac,'w2w1')](Number,document['getEl'+_0x49079f(0x9cf,'E*G)')+'ById'](_0x34596f[_0x49079f(0x314,'E*G)')])[_0x49079f(0x376,'IdpO')])||0x0),_0x2ddd76=Math[_0x49079f(0x483,'&v4y')](0x0,_0x34596f['yycdv'](Number,document['getEl'+_0x49079f(0x4d2,'&!DG')+_0x49079f(0x631,'ceYQ')](_0x34596f[_0x49079f(0xb2d,'VMgj')])['value'])||0x0);if(!_0x39d361)return showToast(_0x34596f['kpnVn']);if(_0x3ea693){const _0x26f511=items[_0x49079f(0x1fe,'9)b9')+'ndex'](_0x3bfc4b=>_0x3bfc4b['id']===_0x3ea693);_0x34596f[_0x49079f(0x238,'*e]A')](_0x26f511,-0x1)&&(items[_0x26f511]={'id':_0x3ea693,'code':_0x57eec1,'cluster':_0x5ce93c,'name':_0x39d361,'qty':_0x1f5ea5,'buyPrice':_0x4ef6e4,'sellPrice':_0x2ddd76},_0x34596f[_0x49079f(0x600,']4q%')](showToast,_0x34596f['wDfsj']));}else items[_0x49079f(0x542,'ceYQ')]({'id':String(Date[_0x49079f(0x77a,'!HV9')]()),'code':_0x57eec1,'cluster':_0x5ce93c,'name':_0x39d361,'qty':_0x1f5ea5,'buyPrice':_0x4ef6e4,'sellPrice':_0x2ddd76}),_0x34596f[_0x49079f(0x4c4,'utxI')](showToast,_0x49079f(0x9a0,'5Hqz')+_0x49079f(0xa37,'bC8p')+_0x49079f(0xb2c,'E*G)')+'bahka'+'n');saveState(),resetItemForm(),renderInventory(),_0x34596f[_0x49079f(0xb4f,'E*G)')](syncClusterDropdowns);}function editItem(_0x5eb9d1){const _0x57c7d8=_0xadf508,_0x642068={'kDxeO':'editI'+'temId','CrtvM':_0x57c7d8(0x9f8,'l&at')+_0x57c7d8(0xa52,'oFps'),'eUsff':_0x57c7d8(0x741,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+'ty','GkQOF':'activ'+'e','gFgLm':_0x57c7d8(0x848,'KN]U')+'conte'+'nt','OrPTA':_0x57c7d8(0x648,'FFZd')+_0x57c7d8(0x4a9,'KghS'),'bXupa':function(_0x3f68bd){return _0x3f68bd();}},_0x1d4f8f=items['find'](_0x22e416=>_0x22e416['id']===_0x5eb9d1);if(!_0x1d4f8f)return;document['getEl'+'ement'+_0x57c7d8(0x92a,'a4i]')](_0x57c7d8(0x2bc,'UbQ2')+_0x57c7d8(0x3c9,'bC8p'))[_0x57c7d8(0x3d7,'!HV9')+_0x57c7d8(0x9c8,'&v4y')+'t']=_0x57c7d8(0x42e,'XucK')+_0x57c7d8(0x33b,'E*G)')+'\x20'+_0x1d4f8f['code'],document[_0x57c7d8(0x91b,'nrxl')+_0x57c7d8(0x8ac,'PRZ&')+'ById'](_0x642068[_0x57c7d8(0x824,'bC8p')])[_0x57c7d8(0x562,'khYj')]=_0x1d4f8f['id'],document[_0x57c7d8(0x580,'!HV9')+_0x57c7d8(0x200,'eHms')+'ById'](_0x642068[_0x57c7d8(0x802,'sa(9')])[_0x57c7d8(0x7a1,'bB4q')]=_0x1d4f8f[_0x57c7d8(0x98a,'a4i]')],document[_0x57c7d8(0x589,'l&at')+'ement'+_0x57c7d8(0x327,'$p9U')](_0x57c7d8(0x2dd,'](EQ')+_0x57c7d8(0x6db,'nrxl')+'r')[_0x57c7d8(0x6c1,'zog4')]=_0x1d4f8f[_0x57c7d8(0x953,'*e]A')+'er'],document[_0x57c7d8(0x5e9,'&v4y')+_0x57c7d8(0x2fc,'bB4q')+_0x57c7d8(0x350,'sa(9')](_0x57c7d8(0x549,'zog4')+_0x57c7d8(0x3af,')cQA'))[_0x57c7d8(0x554,'VUa@')]=_0x1d4f8f['name'],document[_0x57c7d8(0x247,'UbQ2')+_0x57c7d8(0x8ee,'zog4')+_0x57c7d8(0x265,')cQA')](_0x642068[_0x57c7d8(0x9eb,'a4i]')])[_0x57c7d8(0x28e,'#HYV')]=_0x1d4f8f[_0x57c7d8(0x63e,'UbQ2')],document[_0x57c7d8(0x52b,'Vabs')+'ement'+'ById'](_0x57c7d8(0x7a7,'Z55*')+'uy')[_0x57c7d8(0x9ec,'xb!o')]=_0x1d4f8f[_0x57c7d8(0x717,'bB4q')+_0x57c7d8(0x8ef,']*Uo')],document['getEl'+_0x57c7d8(0x9e4,'KN]U')+_0x57c7d8(0x48d,'9)b9')](_0x57c7d8(0x677,'*e]A')+_0x57c7d8(0x2e9,'](EQ'))[_0x57c7d8(0x9f4,'gMHR')]=_0x1d4f8f[_0x57c7d8(0x526,'KghS')+'rice'],previewItemMargin();const _0x31e7be=document['getEl'+_0x57c7d8(0x716,'a4i]')+_0x57c7d8(0x48d,'9)b9')](_0x57c7d8(0x8ca,'bB4q')+'nv');!_0x31e7be[_0x57c7d8(0x93f,'oFps')+_0x57c7d8(0x22a,'1&H^')]['conta'+_0x57c7d8(0x5a4,'w2w1')](_0x642068[_0x57c7d8(0xaec,']4q%')])&&(document['query'+_0x57c7d8(0x40f,'ceYQ')+'torAl'+'l'](_0x642068[_0x57c7d8(0xae2,'IdpO')])[_0x57c7d8(0x3df,'q3H^')+'ch'](_0x1f26e0=>_0x1f26e0[_0x57c7d8(0x3ff,'sa(9')+'List']['remov'+'e'](_0x57c7d8(0x92d,'Z55*')+'e')),document['query'+_0x57c7d8(0x679,'5Hqz')+'torAl'+'l'](_0x57c7d8(0x65a,'dQtf')+_0x57c7d8(0x44b,'E*G)'))[_0x57c7d8(0x978,'KN]U')+'ch'](_0x4033f8=>_0x4033f8[_0x57c7d8(0xb03,'gMHR')+_0x57c7d8(0x3e2,'&v4y')][_0x57c7d8(0xb36,'KghS')+'e'](_0x57c7d8(0x852,'a4i]')+'e')),_0x31e7be[_0x57c7d8(0x663,'E*G)')+_0x57c7d8(0x732,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')][_0x57c7d8(0x25d,'gMHR')]('activ'+'e'),document['query'+_0x57c7d8(0xa95,']*Uo')+_0x57c7d8(0x58c,'a4i]')+'l'](_0x642068[_0x57c7d8(0x5ba,'nrxl')])[0x1][_0x57c7d8(0x625,'PRZ&')+_0x57c7d8(0x2f2,'dQtf')][_0x57c7d8(0xaf2,'V64C')](_0x57c7d8(0x711,'ceYQ')+'e'),_0x642068[_0x57c7d8(0xa32,'XucK')](renderInventory)),window[_0x57c7d8(0xafc,'dQtf')+_0x57c7d8(0x328,'rDp@')]({'top':0x0,'behavior':'smoot'+'h'});}function deleteItem(_0x3c6521){const _0x1ffeca=_0xadf508,_0x300180={'GnCUp':function(_0x46dfe0,_0xb511d0){return _0x46dfe0(_0xb511d0);},'xAnip':function(_0x3a8a68){return _0x3a8a68();}};if(!_0x300180[_0x1ffeca(0x735,'xb!o')](confirm,_0x1ffeca(0x652,'V64C')+_0x1ffeca(0x68f,'UbQ2')+_0x1ffeca(0x8a9,'xb!o')+_0x1ffeca(0x1f7,')cQA')+_0x1ffeca(0x811,'5Hqz')+_0x1ffeca(0x5fd,'FFZd')))return;items=items[_0x1ffeca(0x38c,'E*G)')+'r'](_0x255e69=>_0x255e69['id']!==_0x3c6521),_0x300180[_0x1ffeca(0x36d,'V[]2')](saveState),renderInventory(),syncClusterDropdowns(),_0x300180[_0x1ffeca(0x1f0,'V64C')](showToast,_0x1ffeca(0x7ed,'PRZ&')+_0x1ffeca(0x235,'V[]2')+'us');}function resetItemForm(){const _0x1d38b5=_0xadf508,_0x1e476b={'cYXlB':_0x1d38b5(0x2de,'V[]2')+_0x1d38b5(0x729,'!HV9')+'dit\x20I'+'tem','UHGyO':'itemN'+_0x1d38b5(0x994,'l&at')};document[_0x1d38b5(0x589,'l&at')+_0x1d38b5(0x9cf,'E*G)')+'ById']('formT'+_0x1d38b5(0x3c9,'bC8p'))[_0x1d38b5(0x917,'KghS')+'onten'+'t']=_0x1e476b[_0x1d38b5(0x426,'Vabs')],document['getEl'+_0x1d38b5(0x709,'l&at')+'ById'](_0x1d38b5(0x346,'^^3k')+_0x1d38b5(0x99f,'ceYQ'))[_0x1d38b5(0x675,'&!DG')]='',document[_0x1d38b5(0x473,']*Uo')+'ement'+_0x1d38b5(0x788,'&!DG')](_0x1d38b5(0x8f6,'KghS')+'ode')[_0x1d38b5(0x7a1,'bB4q')]='',document[_0x1d38b5(0x2ce,')cQA')+'ement'+'ById'](_0x1d38b5(0x463,'VMgj')+_0x1d38b5(0x725,'VUa@')+'r')[_0x1d38b5(0x2ea,'q3H^')]='',document[_0x1d38b5(0x247,'UbQ2')+_0x1d38b5(0x62d,'bC8p')+_0x1d38b5(0x52f,'w2w1')](_0x1e476b[_0x1d38b5(0x1ec,'eHms')])[_0x1d38b5(0x947,'KghS')]='',document[_0x1d38b5(0x75c,'a4i]')+'ement'+_0x1d38b5(0x545,'KN]U')](_0x1d38b5(0x972,'V[]2')+'ty')['value']='',document[_0x1d38b5(0x580,'!HV9')+'ement'+_0x1d38b5(0x733,'Z55*')](_0x1d38b5(0x329,'rDp@')+'uy')[_0x1d38b5(0x66d,'rDp@')]='',document['getEl'+_0x1d38b5(0x45f,'$p9U')+_0x1d38b5(0x51c,'^^3k')](_0x1d38b5(0xa49,'XucK')+_0x1d38b5(0xabd,'ceYQ'))[_0x1d38b5(0xb0b,'9)b9')]='',previewItemMargin();}function renderInventory(){const _0x5f4ace=_0xadf508,_0x51eac0={'mukPZ':function(_0x5aee89,_0xb568d6){return _0x5aee89/_0xb568d6;},'YBBlL':function(_0x111611,_0x33b10c){return _0x111611<=_0x33b10c;},'lBnKd':function(_0x7d776f,_0x478b59){return _0x7d776f+_0x478b59;},'QmSSX':function(_0x5f33da,_0x149249){return _0x5f33da+_0x149249;},'cFDxs':function(_0x4e6b11,_0x34b7da){return _0x4e6b11+_0x34b7da;},'gCHct':function(_0x34bbe6,_0x28d995){return _0x34bbe6+_0x28d995;},'OIyHI':function(_0x42fecd,_0x2cfdf9){return _0x42fecd+_0x2cfdf9;},'DXZRF':function(_0x498ec7,_0x4a0b1c){return _0x498ec7+_0x4a0b1c;},'XAWhD':'','sbrMy':_0x5f4ace(0x9cc,']*Uo')+'style'+'=\x22fle'+_0x5f4ace(0x551,'sa(9')+_0x5f4ace(0x937,'eHms')+_0x5f4ace(0x7f7,'13TQ')+_0x5f4ace(0x4ad,'w2w1'),'EygFl':_0x5f4ace(0x71f,'UbQ2')+'>','rUAjN':_0x5f4ace(0x47d,'](EQ')+_0x5f4ace(0x511,'w2w1')+_0x5f4ace(0x881,'bB4q')+_0x5f4ace(0x87a,'utxI')+'span\x20'+_0x5f4ace(0x59b,'eHms')+_0x5f4ace(0xa7b,'13TQ')+_0x5f4ace(0x705,'*e]A'),'svPCe':function(_0x447c01,_0x1046ca){return _0x447c01(_0x1046ca);},'FGiGM':_0x5f4ace(0x7d0,'xb!o')+_0x5f4ace(0x9bc,'rDp@')+_0x5f4ace(0x446,'1&H^')+'g>','RZjsB':_0x5f4ace(0x4d0,')cQA')+_0x5f4ace(0xa15,'VMgj')+_0x5f4ace(0x903,'eHms'),'gcLiS':_0x5f4ace(0x2a7,'9)b9')+_0x5f4ace(0x9dd,'V[]2')+_0x5f4ace(0xa9a,'JSoZ')+_0x5f4ace(0x9be,'utxI')+_0x5f4ace(0x216,'khYj'),'nRKpy':function(_0x35d0cc,_0x439e03){return _0x35d0cc(_0x439e03);},'ePWjT':_0x5f4ace(0x592,'bB4q')+_0x5f4ace(0xa56,'xb!o')+_0x5f4ace(0x9dc,'FFZd')+'g>','SAtuw':_0x5f4ace(0x3ed,']4q%')+_0x5f4ace(0x2c0,'q3H^'),'jCaHu':_0x5f4ace(0x1da,'9)b9')+'iv>','vZfSH':_0x5f4ace(0x4fd,'!HV9')+_0x5f4ace(0x380,'&!DG')+_0x5f4ace(0x5d6,'sa(9')+_0x5f4ace(0x2a1,'xb!o')+_0x5f4ace(0x1fb,'ceYQ')+_0x5f4ace(0x35f,'JSoZ')+_0x5f4ace(0x897,'VUa@')+'sm\x22\x20o'+_0x5f4ace(0x6f2,'V64C')+_0x5f4ace(0x321,'#HYV')+_0x5f4ace(0x69c,'Z55*')+'m(\x27','MIAMk':_0x5f4ace(0x9c0,'#HYV')+_0x5f4ace(0x876,'l&at')+'/butt'+_0x5f4ace(0x27b,'1&H^'),'FRTzl':_0x5f4ace(0x9de,'Vabs')+_0x5f4ace(0xa43,'oFps')+_0x5f4ace(0x91c,'13TQ')+_0x5f4ace(0x5e0,'$p9U')+_0x5f4ace(0x41a,'gMHR')+_0x5f4ace(0xb58,'khYj')+_0x5f4ace(0x9f6,')cQA')+_0x5f4ace(0x7c6,'&v4y')+_0x5f4ace(0x56e,'xb!o')+'/p>'},_0x537976=(document[_0x5f4ace(0x5c7,'1&H^')+_0x5f4ace(0x21a,'#HYV')+_0x5f4ace(0xa3d,'13TQ')](_0x5f4ace(0xb05,'KghS')+'arch')[_0x5f4ace(0x28e,'#HYV')]||'')[_0x5f4ace(0x5c2,'VUa@')+_0x5f4ace(0xaf9,'JSoZ')+'e'](),_0x3a95a6=items[_0x5f4ace(0x81c,'5Hqz')+'r'](_0x424343=>_0x424343[_0x5f4ace(0x43d,'ceYQ')][_0x5f4ace(0x5f0,'#HYV')+_0x5f4ace(0x97a,'bB4q')+'e']()['inclu'+_0x5f4ace(0x843,'Vabs')](_0x537976)||_0x424343[_0x5f4ace(0xb1e,'$p9U')][_0x5f4ace(0x954,'9)b9')+_0x5f4ace(0x5aa,'FFZd')+'e']()[_0x5f4ace(0x386,'oFps')+_0x5f4ace(0xae1,'V64C')](_0x537976)||(_0x424343[_0x5f4ace(0x5a0,'utxI')+'er']||'')[_0x5f4ace(0x70a,'oFps')+_0x5f4ace(0xa7f,'V[]2')+'e']()[_0x5f4ace(0x71c,']4q%')+_0x5f4ace(0xadc,'VMgj')](_0x537976)),_0x243f88=document[_0x5f4ace(0x473,']*Uo')+'ement'+_0x5f4ace(0x52f,'w2w1')](_0x5f4ace(0x315,'a4i]')+_0x5f4ace(0x624,'Vabs')+'ist');if(_0x3a95a6[_0x5f4ace(0x668,'gMHR')+'h']===0x0){_0x243f88['inner'+_0x5f4ace(0x5a6,'KN]U')]=_0x51eac0[_0x5f4ace(0x785,'nrxl')];return;}_0x243f88[_0x5f4ace(0x4a6,'KN]U')+_0x5f4ace(0x548,']4q%')]=_0x3a95a6[_0x5f4ace(0x8fc,'!HV9')](_0x52e77f=>{const _0x55e511=_0x5f4ace,_0x3fafb4=_0x52e77f[_0x55e511(0xaf6,'bB4q')+_0x55e511(0x50c,'l&at')]-_0x52e77f['buyPr'+_0x55e511(0x687,'bB4q')],_0x1a3a49=_0x52e77f[_0x55e511(0x201,'9)b9')+_0x55e511(0x791,'XucK')]>0x0?(_0x51eac0[_0x55e511(0x8f2,'zog4')](_0x3fafb4,_0x52e77f[_0x55e511(0x9e9,'eHms')+_0x55e511(0x42d,'E*G)')])*0x64)[_0x55e511(0xabc,'w2w1')+'ed'](0x1):'0',_0x55101a=_0x51eac0[_0x55e511(0x3ec,'xb!o')](_0x52e77f[_0x55e511(0x5ed,'zog4')],0x5)?'\x20/g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+'ght:7'+'00;\x20f'+_0x55e511(0x699,'JSoZ')+_0x55e511(0x695,'ceYQ')+_0x55e511(0x821,'nrxl')+_0x55e511(0x290,'V[]2'))+esc(_0x52e77f[_0x55e511(0x900,'9)b9')])+_0x55101a,_0x51eac0[_0x55e511(0x7a8,'q3H^')])+_0x51eac0[_0x55e511(0x7a0,'$p9U')]+esc(_0x52e77f[_0x55e511(0x722,'JSoZ')+'er']),_0x55e511(0x808,']*Uo')+_0x55e511(0xa27,'Vabs'))+_0x51eac0[_0x55e511(0x8a5,'XucK')](esc,_0x52e77f['code'])+_0x51eac0[_0x55e511(0x772,'KN]U')],_0x52e77f[_0x55e511(0xac6,'](EQ')])+_0x51eac0[_0x55e511(0x5be,'IdpO')],_0x51eac0[_0x55e511(0x2d9,'JSoZ')]),_0x51eac0[_0x55e511(0x4e8,'ceYQ')](formatRp,_0x52e77f[_0x55e511(0x857,']4q%')+'ice']))+_0x51eac0[_0x55e511(0x6e3,'*e]A')]+formatRp(_0x52e77f['sellP'+_0x55e511(0x5de,'sa(9')]),_0x55e511(0x8a7,'q3H^')+'ong><'+_0x55e511(0x8da,'IdpO')),_0x55e511(0x2fe,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+_0x55e511(0x3d9,'zog4')+'=\x22fon'+_0x55e511(0x5c9,'$p9U')+_0x55e511(0x537,'UbQ2')+_0x55e511(0x3b6,'Vabs')+_0x55e511(0xabb,'UbQ2')+_0x55e511(0xa0e,'Vabs')+_0x55e511(0x358,'^^3k')+_0x55e511(0x5eb,'utxI')+_0x55e511(0x964,'KghS')+_0x55e511(0x9f2,'oFps')+_0x55e511(0x58e,'UbQ2')+_0x55e511(0x642,'utxI')+'\x22>'),_0x51eac0[_0x55e511(0x7e2,'13TQ')])+_0x51eac0['nRKpy'](formatRp,_0x3fafb4)+'\x20(',_0x1a3a49),_0x51eac0[_0x55e511(0x615,')cQA')]),_0x55e511(0xa45,'q3H^')+'>')+(_0x55e511(0x3ab,'V64C')+'style'+_0x55e511(0x27c,'VUa@')+'play:'+_0x55e511(0x97c,'Z55*')+_0x55e511(0x3b0,']*Uo')+_0x55e511(0x3a6,'UbQ2')+_0x55e511(0x740,'a4i]')+_0x55e511(0x73b,'E*G)')+_0x55e511(0x2b6,'rDp@')+_0x55e511(0x5a9,'KN]U')+_0x55e511(0x4f3,'VMgj'))+_0x51eac0['vZfSH'],_0x52e77f['id'])+('\x27)\x22>E'+_0x55e511(0x45d,']*Uo')+_0x55e511(0x24f,'](EQ')+'n>')+('/g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+_0x55e511(0x83c,'$p9U')+_0x55e511(0x678,'rDp@')+'m\x22\x20on'+_0x55e511(0x828,'UbQ2')+_0x55e511(0x914,']*Uo')+_0x55e511(0x520,'nrxl')+'em(\x27')+_0x52e77f['id'],_0x51eac0[_0x55e511(0x2a5,'*e]A')])+(_0x55e511(0x4ba,'sa(9')+'>')+_0x51eac0[_0x55e511(0x448,'rDp@')];})[_0x5f4ace(0x37a,']4q%')]('');}function parseCSVLine(_0x43aceb,_0x3e4411){const _0x295334=_0xadf508,_0x5564ca={'bVzwI':function(_0x3cefd8,_0x28a853){return _0x3cefd8<_0x28a853;},'xvcNJ':function(_0x494b62,_0x49d22c){return _0x494b62===_0x49d22c;},'qbime':function(_0x4a0596,_0x4c2dee){return _0x4a0596===_0x4c2dee;}},_0x1e8d7c=[];let _0x3230fb='',_0x4969cd=![];for(let _0x380383=0x0;_0x5564ca[_0x295334(0xafd,'^^3k')](_0x380383,_0x43aceb[_0x295334(0x78f,'Vabs')+'h']);_0x380383++){const _0x253fd9=_0x43aceb[_0x380383];if(_0x253fd9==='\x22'){if(_0x4969cd&&_0x5564ca['xvcNJ'](_0x43aceb[_0x380383+0x1],'\x22'))_0x3230fb+='\x22',_0x380383++;else _0x4969cd=!_0x4969cd;}else{if(_0x5564ca[_0x295334(0x9ce,'*e]A')](_0x253fd9,_0x3e4411)&&!_0x4969cd)_0x1e8d7c[_0x295334(0x7a3,'XucK')](_0x3230fb['trim']()),_0x3230fb='';else _0x3230fb+=_0x253fd9;}}return _0x1e8d7c[_0x295334(0x2b7,'KghS')](_0x3230fb['trim']()),_0x1e8d7c;}function cleanNumber(_0x3fc2e2){const _0x36c1d8=_0xadf508,_0x4b2a84={'ZejQs':function(_0x2296ab,_0x1092a3){return _0x2296ab(_0x1092a3);},'BereA':function(_0x346770,_0x3afe40){return _0x346770>_0x3afe40;},'STgWa':function(_0xaba787,_0x17c108){return _0xaba787<=_0x17c108;},'kOpPN':function(_0x4e24ee,_0x52d957){return _0x4e24ee+_0x52d957;},'fhbVq':function(_0x3c7394,_0x2bba99){return _0x3c7394+_0x2bba99;}};if(!_0x3fc2e2)return 0x0;let _0x5bfb35=_0x4b2a84[_0x36c1d8(0x4b7,'nrxl')](String,_0x3fc2e2)[_0x36c1d8(0x559,'rDp@')+'ce'](/[^0-9.,-]/g,'');if(_0x5bfb35['index'+'Of'](',')>-0x1&&_0x5bfb35[_0x36c1d8(0x540,'sa(9')+'Of']('.')>-0x1)_0x5bfb35=_0x5bfb35['repla'+'ce'](/\./g,'')['repla'+'ce'](',','.');else{if(_0x4b2a84['BereA'](_0x5bfb35['index'+'Of'](','),-0x1)){const _0x562b02=_0x5bfb35[_0x36c1d8(0xb27,'13TQ')](',');if(_0x562b02[_0x36c1d8(0x3aa,']4q%')+'h']===0x2&&_0x4b2a84[_0x36c1d8(0x4f4,'IdpO')](_0x562b02[0x1][_0x36c1d8(0x7ee,'khYj')+'h'],0x2))_0x5bfb35=_0x4b2a84[_0x36c1d8(0xa11,'zog4')](_0x4b2a84['fhbVq'](_0x562b02[0x0],'.'),_0x562b02[0x1]);else _0x5bfb35=_0x5bfb35[_0x36c1d8(0x643,'Z55*')+'ce'](/,/g,'');}}const _0x2120b8=_0x4b2a84['ZejQs'](Number,_0x5bfb35);return Math[_0x36c1d8(0x764,'nrxl')](0x0,isNaN(_0x2120b8)?0x0:_0x2120b8);}function downloadTemplateCSV(){const _0x2fcf26=_0xadf508,_0x2de121={'XJuGn':'Nama_'+_0x2fcf26(0x60f,'oFps'),'BXesI':_0x2fcf26(0x889,'utxI')+'_Beli','XjroE':_0x2fcf26(0x2c5,'l&at')+_0x2fcf26(0x233,'V64C'),'HawLN':_0x2fcf26(0x3d0,']*Uo')+'0','kxfpe':_0x2fcf26(0xab3,'KN]U')+'an'},_0x530a1f=[_0x2fcf26(0x622,'utxI')+_0x2fcf26(0x9d1,'](EQ'),_0x2de121[_0x2fcf26(0x5b1,'&!DG')],_0x2fcf26(0x482,'#HYV')+'er',_0x2fcf26(0xa16,'gMHR')+_0x2fcf26(0x452,'KN]U')+'k',_0x2de121['BXesI'],_0x2de121[_0x2fcf26(0x2b3,'Vabs')]],_0x4e3cff=[[_0x2de121['HawLN'],_0x2fcf26(0x39e,'$p9U')+_0x2fcf26(0x1d2,'IdpO')+_0x2fcf26(0xb3a,'^^3k')+_0x2fcf26(0x96e,'eHms')+'l',_0x2fcf26(0x571,'q3H^')+'an',0x19,0x1b58,0x2ee0],[_0x2fcf26(0xb15,'$p9U')+'0',_0x2fcf26(0x500,'&!DG')+_0x2fcf26(0x5b7,'bC8p')+_0x2fcf26(0x930,'q3H^')+'lat',_0x2de121[_0x2fcf26(0x784,'#HYV')],0xf,0x2328,0x3e80]];downloadCSV(_0x2fcf26(0x5cf,'VMgj')+_0x2fcf26(0x96a,'VUa@')+'mport'+'_inve'+_0x2fcf26(0x578,'V64C')+_0x2fcf26(0x1ed,'IdpO'),[_0x530a1f][_0x2fcf26(0x8e2,'5Hqz')+'t'](_0x4e3cff));}function importInventoryCSV(){const _0x107fe8=_0xadf508,_0x51f357={'SAeSU':'UPSER'+_0x107fe8(0x330,'FFZd')+'_STOC'+'K','NBYhj':function(_0x32a0a6,_0x432227){return _0x32a0a6(_0x432227);},'AQjtZ':function(_0x12e0f8,_0xb6edd8){return _0x12e0f8+_0xb6edd8;},'MnVqf':function(_0x1091b3,_0x5c295f){return _0x1091b3(_0x5c295f);},'pWunw':_0x107fe8(0x773,'IdpO'),'tbJBx':function(_0x41f8f4,_0x101908){return _0x41f8f4!==_0x101908;},'qDtzp':function(_0x5dd52e,_0x2357bf){return _0x5dd52e(_0x2357bf);},'DBlQa':function(_0x733a5d,_0x36bb9b){return _0x733a5d(_0x36bb9b);},'CcITB':_0x107fe8(0x2d2,'9)b9')+'\x20ada\x20'+_0x107fe8(0x6a8,'xb!o')+_0x107fe8(0x239,'IhJl')+_0x107fe8(0x298,'&!DG')+_0x107fe8(0xa35,')cQA')+_0x107fe8(0x682,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+_0x107fe8(0x3bd,'w2w1')+'.','yKkfV':_0x107fe8(0xa1f,'w2w1')+_0x107fe8(0x9f5,'l&at')+_0x107fe8(0x408,']*Uo')+_0x107fe8(0x7f1,'gMHR')+_0x107fe8(0x2b8,'*e]A')+_0x107fe8(0x5c5,'5Hqz')+'ni\x20de'+_0x107fe8(0x915,'13TQ'),'ijbsA':'\x20item'+_0x107fe8(0x641,'q3H^')+_0x107fe8(0x2bd,'PRZ&'),'vTcAI':function(_0x1418a0){return _0x1418a0();},'CmFjL':function(_0x329a13,_0x8e690){return _0x329a13+_0x8e690;},'CUjbw':_0x107fe8(0xa03,'VUa@')+_0x107fe8(0x73e,'IdpO')+_0x107fe8(0x3f9,'9)b9')+_0x107fe8(0xa2d,'nrxl'),'symCD':function(_0xca73ed,_0x436e48){return _0xca73ed(_0x436e48);},'BeZvx':_0x107fe8(0x205,'!HV9')+'portM'+_0x107fe8(0x2c6,'VUa@')},_0x2a6e48=document[_0x107fe8(0x56c,'q3H^')+'ement'+'ById'](_0x107fe8(0xaaa,'gMHR')+_0x107fe8(0xa2c,'gMHR')+'ut'),_0x37a88c=document[_0x107fe8(0x5e9,'&v4y')+_0x107fe8(0x85c,'1&H^')+_0x107fe8(0x5d2,'q3H^')](_0x51f357[_0x107fe8(0x3a3,'dQtf')])[_0x107fe8(0xb54,'](EQ')];if(!_0x2a6e48[_0x107fe8(0x8c8,'VUa@')]||_0x2a6e48[_0x107fe8(0x6fb,'$p9U')][_0x107fe8(0x9d9,'9)b9')+'h']===0x0)return showToast(_0x107fe8(0x28b,'bC8p')+_0x107fe8(0x588,'KghS')+_0x107fe8(0x8fe,'5Hqz')+_0x107fe8(0x7b8,'FFZd')+_0x107fe8(0x34e,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+_0x107fe8(0x1ff,'XucK')+'!');const _0x3e2647=_0x2a6e48[_0x107fe8(0x331,'E*G)')][0x0],_0x4df3a1=new FileReader();_0x4df3a1[_0x107fe8(0xb66,']4q%')+'d']=function(_0x27c989){const _0x1628a0=_0x107fe8;try{const _0x5aff78=String(_0x27c989['targe'+'t'][_0x1628a0(0x769,'l&at')+'t'])['repla'+'ce'](/^\uFEFF/,''),_0x15a05d=_0x5aff78['split'](/\r?\n/)[_0x1628a0(0x63b,'ceYQ')+'r'](_0x47535c=>_0x47535c[_0x1628a0(0x40c,'](EQ')]()!=='');if(_0x15a05d[_0x1628a0(0xa6b,'KN]U')+'h']<0x2)return showToast(_0x1628a0(0xa9b,'](EQ')+_0x1628a0(0x825,'#HYV')+_0x1628a0(0x2e6,'XucK')+_0x1628a0(0x51f,'oFps')+_0x1628a0(0x566,'bB4q')+_0x1628a0(0x6d9,'w2w1')+'iliki'+_0x1628a0(0xae9,'nrxl')+_0x1628a0(0x20d,'utxI')+'a!');const _0x519384=(_0x15a05d[0x0][_0x1628a0(0xb51,'13TQ')](/;/g)||[])[_0x1628a0(0x668,'gMHR')+'h'],_0x5a6466=(_0x15a05d[0x0]['match'](/,/g)||[])[_0x1628a0(0x862,'E*G)')+'h'],_0x97f9a3=_0x519384>_0x5a6466?';':',',_0xfae639=parseCSVLine(_0x15a05d[0x0],_0x97f9a3)[_0x1628a0(0x68b,'JSoZ')](_0x16886b=>_0x16886b[_0x1628a0(0x254,'*e]A')+_0x1628a0(0xb37,'KghS')+'e']()[_0x1628a0(0x73a,'dQtf')+'ce'](/[^a-z0-9]/g,'')),_0x9f87fc=_0xfae639[_0x1628a0(0xb34,'!HV9')+_0x1628a0(0x7d1,'1&H^')](_0x547368=>[_0x1628a0(0x2d1,'#HYV')+'tem',_0x1628a0(0xae8,'9)b9'),_0x1628a0(0x371,'dQtf'),_0x1628a0(0x395,'](EQ'),'id',_0x1628a0(0x7ae,'9)b9')+'de'][_0x1628a0(0x312,'khYj')+_0x1628a0(0x847,'rDp@')](_0x547368)),_0x5e5cff=_0xfae639[_0x1628a0(0x834,'bB4q')+_0x1628a0(0x8f8,'rDp@')](_0x12adf8=>[_0x1628a0(0x3ac,'13TQ')+_0x1628a0(0x393,'VMgj'),_0x1628a0(0x2e8,'E*G)'),_0x1628a0(0x8bd,'&v4y'),_0x1628a0(0x829,'bC8p')+'g',_0x1628a0(0x512,'sa(9')+'k',_0x1628a0(0x2ba,']4q%')][_0x1628a0(0x312,'khYj')+'des'](_0x12adf8)),_0x29c43a=_0xfae639['findI'+'ndex'](_0x5aa9eb=>[_0x1628a0(0xa2e,'E*G)')+'er','kateg'+_0x1628a0(0x62b,'gMHR'),_0x1628a0(0xa85,'Vabs')+'ory',_0x1628a0(0x800,'VUa@'),'group'][_0x1628a0(0x386,'oFps')+_0x1628a0(0x6ef,'&!DG')](_0x5aa9eb)),_0x3fec55=_0xfae639[_0x1628a0(0xa25,'#HYV')+_0x1628a0(0x796,']*Uo')](_0x56098e=>[_0x1628a0(0xad3,'sa(9')+_0x1628a0(0x37b,'XucK'),_0x1628a0(0x264,'FFZd'),'qty','jumla'+'h',_0x1628a0(0x31d,'FFZd'),_0x1628a0(0xb41,'13TQ')+_0x1628a0(0xb46,'JSoZ')][_0x1628a0(0x684,'eHms')+_0x1628a0(0x9ed,'&v4y')](_0x56098e)),_0xb8f229=_0xfae639[_0x1628a0(0x354,'JSoZ')+'ndex'](_0x5e8f59=>['harga'+_0x1628a0(0x9c1,'*e]A'),_0x1628a0(0x734,'VMgj'),_0x1628a0(0x845,'13TQ'),_0x1628a0(0x9b3,'IhJl')+_0x1628a0(0x47b,'l&at'),_0x1628a0(0x8d9,'VUa@'),_0x1628a0(0x7a5,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+_0x1628a0(0x464,'VMgj')]['inclu'+'des'](_0x5e8f59)),_0x5d9189=_0xfae639[_0x1628a0(0x8b2,'FFZd')+_0x1628a0(0x9e6,'nrxl')](_0x2f8497=>[_0x1628a0(0x9b2,'sa(9')+_0x1628a0(0xb33,'Z55*'),_0x1628a0(0x348,'V64C'),_0x1628a0(0x76b,'khYj'),_0x1628a0(0xaee,'&v4y')+_0x1628a0(0x416,'eHms'),_0x1628a0(0x1cc,'khYj')][_0x1628a0(0x536,'&!DG')+_0x1628a0(0x635,'sa(9')](_0x2f8497));if(_0x5e5cff===-0x1)return _0x51f357[_0x1628a0(0x882,'9)b9')](showToast,'Kolom'+_0x1628a0(0x465,'xb!o')+_0x1628a0(0x1f3,'5Hqz')+_0x1628a0(0x1f5,'oFps')+_0x1628a0(0x7c1,'1&H^')+'emuka'+_0x1628a0(0x70f,'XucK')+_0x1628a0(0x629,'1&H^')+_0x1628a0(0x60b,'V[]2')+_0x1628a0(0x686,'khYj'));const _0x45e636=[];for(let _0x478f66=0x1;_0x478f66<_0x15a05d[_0x1628a0(0x99e,'1&H^')+'h'];_0x478f66++){const _0x4bdebf=parseCSVLine(_0x15a05d[_0x478f66],_0x97f9a3),_0xcd9812=(_0x4bdebf[_0x5e5cff]||'')[_0x1628a0(0x763,'JSoZ')]();if(!_0xcd9812)continue;const _0x2a1ed2=_0x9f87fc!==-0x1&&_0x4bdebf[_0x9f87fc]?_0x4bdebf[_0x9f87fc][_0x1628a0(0x823,'9)b9')]():_0x51f357['AQjtZ'](_0x51f357[_0x1628a0(0x370,'IdpO')],Date[_0x1628a0(0x3c5,'FFZd')]()[_0x1628a0(0x736,'UbQ2')+_0x1628a0(0x906,'KghS')]()[_0x1628a0(0xab5,')cQA')](-0x4))+'-'+_0x478f66,_0x18c85c=_0x29c43a!==-0x1&&_0x4bdebf[_0x29c43a]?_0x4bdebf[_0x29c43a][_0x1628a0(0x9b5,'KghS')]()||'Umum':_0x1628a0(0x337,')cQA');_0x45e636[_0x1628a0(0xa17,'E*G)')]({'code':_0x2a1ed2,'name':_0xcd9812,'cluster':_0x18c85c,'qty':_0x51f357[_0x1628a0(0x5f7,'gMHR')](_0x3fec55,-0x1)?_0x51f357[_0x1628a0(0x3cf,'Vabs')](cleanNumber,_0x4bdebf[_0x3fec55]):0x0,'buyPrice':_0xb8f229!==-0x1?cleanNumber(_0x4bdebf[_0xb8f229]):0x0,'sellPrice':_0x51f357[_0x1628a0(0x8c5,'&v4y')](_0x5d9189,-0x1)?_0x51f357[_0x1628a0(0x90a,'V64C')](cleanNumber,_0x4bdebf[_0x5d9189]):0x0});}if(_0x45e636[_0x1628a0(0x218,'bC8p')+'h']===0x0)return showToast(_0x51f357[_0x1628a0(0xb01,'rDp@')]);if(_0x37a88c===_0x1628a0(0x984,'a4i]')+_0x1628a0(0xaed,'IhJl')+'L'){if(!confirm(_0x51f357['AQjtZ'](_0x51f357[_0x1628a0(0x72e,'gMHR')]+_0x45e636[_0x1628a0(0x7a6,'&!DG')+'h'],_0x51f357['ijbsA'])))return;items=_0x45e636[_0x1628a0(0x6d6,'VMgj')]((_0x584d84,_0x2372fd)=>Object[_0x1628a0(0x263,'KghS')+'n']({'id':String(Date[_0x1628a0(0x77a,'!HV9')]()+_0x2372fd)},_0x584d84));}else _0x45e636[_0x1628a0(0x830,'xb!o')+'ch']((_0x455c7f,_0x3ad089)=>{const _0x177a29=_0x1628a0,_0x39349f=items['find'](_0x1d9ebe=>_0x1d9ebe[_0x177a29(0x8b9,'ceYQ')][_0x177a29(0x831,'utxI')+_0x177a29(0x2fd,'&v4y')+'e']()===_0x455c7f[_0x177a29(0x3a7,'rDp@')]['toLow'+_0x177a29(0xa74,'a4i]')+'e']()||_0x1d9ebe[_0x177a29(0x900,'9)b9')][_0x177a29(0x373,'IdpO')+_0x177a29(0xab2,'VUa@')+'e']()===_0x455c7f[_0x177a29(0x727,'sa(9')][_0x177a29(0x246,'XucK')+_0x177a29(0x81a,'q3H^')+'e']());_0x39349f?(_0x39349f[_0x177a29(0xa38,'#HYV')]=_0x455c7f[_0x177a29(0x553,'sa(9')],_0x39349f[_0x177a29(0x777,'PRZ&')]=_0x455c7f[_0x177a29(0x5e3,'l&at')],_0x39349f[_0x177a29(0x5a0,'utxI')+'er']=_0x455c7f[_0x177a29(0x8c1,'!HV9')+'er'],_0x39349f[_0x177a29(0x76f,'*e]A')+_0x177a29(0x683,')cQA')]=_0x455c7f[_0x177a29(0x1d3,'Z55*')+_0x177a29(0x938,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')],_0x39349f[_0x177a29(0x3c8,'a4i]')+_0x177a29(0xa82,'1&H^')]=_0x455c7f[_0x177a29(0x3c8,'a4i]')+_0x177a29(0x98b,'w2w1')],_0x39349f[_0x177a29(0x5b6,'9)b9')]=_0x37a88c===_0x51f357[_0x177a29(0x453,'5Hqz')]?_0x39349f['qty']+_0x455c7f[_0x177a29(0x6e4,'eHms')]:_0x455c7f[_0x177a29(0x7ac,'rDp@')]):items[_0x177a29(0x96b,'1&H^')](Object[_0x177a29(0x3ce,'IdpO')+'n']({'id':_0x51f357[_0x177a29(0x9df,'zog4')](String,_0x51f357[_0x177a29(0x778,']*Uo')](Date['now'](),_0x3ad089))},_0x455c7f));});saveState(),renderInventory(),_0x51f357[_0x1628a0(0x85a,']4q%')](syncClusterDropdowns),renderPOSItems(),_0x2a6e48[_0x1628a0(0x6c1,'zog4')]='',showToast(_0x51f357[_0x1628a0(0x20b,'q3H^')](_0x51f357[_0x1628a0(0x817,'V[]2')],_0x45e636[_0x1628a0(0x6eb,'q3H^')+'h'])+('\x20item'+_0x1628a0(0x863,'VUa@')+_0x1628a0(0x237,'&v4y')));}catch(_0x165f73){_0x51f357['symCD'](showToast,'Gagal'+_0x1628a0(0x6e5,'XucK')+'roses'+_0x1628a0(0xa5c,'JSoZ')+_0x1628a0(0x427,'nrxl'));}},_0x4df3a1['onerr'+'or']=function(){const _0x17c1a1=_0x107fe8;showToast(_0x17c1a1(0xb14,'V[]2')+_0x17c1a1(0xb2a,']*Uo')+_0x17c1a1(0x207,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+'ile\x20C'+_0x17c1a1(0x1df,'Vabs'));},_0x4df3a1['readA'+'sText'](_0x3e2647,_0x107fe8(0x946,'*e]A'));}function renderMarginTab(){const _0x2f3452=_0xadf508,_0x5e7ab4={'KNtXN':_0x2f3452(0x4ed,'!HV9')+_0x2f3452(0x7ff,'](EQ')+'st','CYPZQ':function(_0x5ac47a,_0x7997a8){return _0x5ac47a(_0x7997a8);}};syncClusterDropdowns();const _0x5ec3a4=items[_0x2f3452(0x4f6,']4q%')+'e']((_0x4a368c,_0x2c5d23)=>_0x4a368c+_0x2c5d23[_0x2f3452(0xb04,'13TQ')+_0x2f3452(0x50b,'13TQ')]*_0x2c5d23[_0x2f3452(0x619,']4q%')],0x0),_0x3d6406=items[_0x2f3452(0x855,'V[]2')+'e']((_0x1af3b7,_0x3354f9)=>_0x1af3b7+_0x3354f9[_0x2f3452(0x5e8,'rDp@')+_0x2f3452(0x3fd,'5Hqz')]*_0x3354f9[_0x2f3452(0x6b2,'w2w1')],0x0);document[_0x2f3452(0x632,'KghS')+_0x2f3452(0x255,'utxI')+_0x2f3452(0x922,'gMHR')](_0x5e7ab4[_0x2f3452(0x4ac,'nrxl')])['textC'+'onten'+'t']=_0x5e7ab4['CYPZQ'](formatRp,_0x5ec3a4),document[_0x2f3452(0xa5f,'](EQ')+_0x2f3452(0x68a,'rDp@')+_0x2f3452(0x327,'$p9U')](_0x2f3452(0x4eb,'XucK')+_0x2f3452(0x7e0,')cQA')+'v')[_0x2f3452(0x905,'a4i]')+_0x2f3452(0x969,'KN]U')+'t']=formatRp(_0x3d6406);}function applyBulkMargin(){const _0x26d181=_0xadf508,_0x59cbd5={'kVHPV':function(_0x48d8ef,_0x20676a){return _0x48d8ef===_0x20676a;},'fQyLt':function(_0x1628b1,_0x1ff304){return _0x1628b1(_0x1ff304);},'MqFNn':function(_0x2ad300,_0x505118){return _0x2ad300(_0x505118);},'EfqFD':function(_0x150e42){return _0x150e42();},'ZJmul':function(_0x3e3d85){return _0x3e3d85();},'UwHXa':function(_0x133093,_0x22317c){return _0x133093(_0x22317c);},'KDzIw':function(_0x346dd8,_0x4c6d19){return _0x346dd8+_0x4c6d19;},'gbqDY':_0x26d181(0x6a9,'VMgj')+_0x26d181(0x79c,'VUa@')+'\x20'},_0x14d45d=document['getEl'+_0x26d181(0x304,'w2w1')+'ById'](_0x26d181(0x478,'&!DG')+_0x26d181(0x8b7,'IhJl')+'et')['value'],_0x45ab16=document[_0x26d181(0x70c,'VMgj')+_0x26d181(0x2a2,'khYj')+'ById'](_0x26d181(0x961,'Z55*')+'nType')['value'],_0x22fc4d=Number(document[_0x26d181(0x8e7,'5Hqz')+_0x26d181(0x849,'VUa@')+'ById'](_0x26d181(0x478,'&!DG')+_0x26d181(0x9e1,'5Hqz')+'nt')[_0x26d181(0x9f4,'gMHR')]),_0x27682b=Number(document[_0x26d181(0x83d,'utxI')+_0x26d181(0x304,'w2w1')+_0x26d181(0x986,'UbQ2')](_0x26d181(0xa1a,'nrxl')+_0x26d181(0x37e,'VMgj')+_0x26d181(0x90f,'E*G)'))[_0x26d181(0x3ef,'UbQ2')])||0x1;if(_0x59cbd5[_0x26d181(0x952,'13TQ')](isNaN,_0x22fc4d)||_0x22fc4d<0x0)return _0x59cbd5[_0x26d181(0x603,'khYj')](showToast,_0x26d181(0xb21,'E*G)')+_0x26d181(0x92c,'Vabs')+_0x26d181(0x873,']4q%')+_0x26d181(0x88e,'sa(9')+_0x26d181(0x1e7,'!HV9')+_0x26d181(0x2be,'l&at')+'id');let _0x3908af=0x0;items[_0x26d181(0x693,'dQtf')+'ch'](_0x506b29=>{const _0x3e92cc=_0x26d181;if(_0x14d45d===_0x3e92cc(0xb0c,'sa(9')||_0x59cbd5[_0x3e92cc(0x3be,'1&H^')](_0x506b29['clust'+'er'],_0x14d45d)){let _0x1ddf3b;if(_0x45ab16===_0x3e92cc(0x644,'!HV9')+'NT')_0x1ddf3b=_0x506b29['buyPr'+_0x3e92cc(0x77b,'!HV9')]+_0x506b29[_0x3e92cc(0xa02,'bC8p')+_0x3e92cc(0x361,'zog4')]*(_0x22fc4d/0x64);else _0x1ddf3b=_0x506b29[_0x3e92cc(0x23b,']*Uo')+_0x3e92cc(0x2f6,'q3H^')]+_0x22fc4d;_0x506b29[_0x3e92cc(0x3b7,'JSoZ')+'rice']=Math[_0x3e92cc(0xa19,'nrxl')](_0x1ddf3b/_0x27682b)*_0x27682b,_0x3908af++;}}),_0x59cbd5[_0x26d181(0xb28,'sa(9')](saveState),renderMarginTab(),_0x59cbd5['ZJmul'](renderPOSItems),renderInventory(),_0x59cbd5[_0x26d181(0xaf5,'a4i]')](showToast,_0x59cbd5[_0x26d181(0x62c,'l&at')](_0x59cbd5[_0x26d181(0x660,'*e]A')],_0x3908af)+(_0x26d181(0x66f,'q3H^')+_0x26d181(0x29f,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+'rbaru'+'i!'));}function _0x1683(_0x1593f4,_0x4a9cb2){const _0x5bafcf=_0x5a81();return _0x1683=function(_0x20956a,_0x51f655){_0x20956a=_0x20956a-0x1ca;let _0xb0c0a2=_0x5bafcf[_0x20956a];if(_0x1683['btsGog']===undefined){var _0x5209f3=function(_0x3aba7d){const _0x14e9e5='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let _0x480d84='',_0x192e01='',_0x5e6d8b=_0x480d84+_0x5209f3;for(let _0x1b055b=0x0,_0x32f37e,_0x3488ce,_0x3dc3f1=0x0;_0x3488ce=_0x3aba7d['charAt'](_0x3dc3f1++);~_0x3488ce&&(_0x32f37e=_0x1b055b%0x4?_0x32f37e*0x40+_0x3488ce:_0x3488ce,_0x1b055b++%0x4)?_0x480d84+=_0x5e6d8b['charCodeAt'](_0x3dc3f1+0xa)-0xa!==0x0?String['fromCharCode'](0xff&_0x32f37e>>(-0x2*_0x1b055b&0x6)):_0x1b055b:0x0){_0x3488ce=_0x14e9e5['indexOf'](_0x3488ce);}for(let _0x38a3cc=0x0,_0x45d8bf=_0x480d84['length'];_0x38a3cc<_0x45d8bf;_0x38a3cc++){_0x192e01+='%'+('00'+_0x480d84['charCodeAt'](_0x38a3cc)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0x192e01);};const _0x388e67=function(_0x44b7c6,_0x1b7ced){let _0x437bb9=[],_0x559208=0x0,_0x233c4c,_0x328f36='';_0x44b7c6=_0x5209f3(_0x44b7c6);let _0x376cab;for(_0x376cab=0x0;_0x376cab<0x100;_0x376cab++){_0x437bb9[_0x376cab]=_0x376cab;}for(_0x376cab=0x0;_0x376cab<0x100;_0x376cab++){_0x559208=(_0x559208+_0x437bb9[_0x376cab]+_0x1b7ced['charCodeAt'](_0x376cab%_0x1b7ced['length']))%0x100,_0x233c4c=_0x437bb9[_0x376cab],_0x437bb9[_0x376cab]=_0x437bb9[_0x559208],_0x437bb9[_0x559208]=_0x233c4c;}_0x376cab=0x0,_0x559208=0x0;for(let _0x31005d=0x0;_0x31005d<_0x44b7c6['length'];_0x31005d++){_0x376cab=(_0x376cab+0x1)%0x100,_0x559208=(_0x559208+_0x437bb9[_0x376cab])%0x100,_0x233c4c=_0x437bb9[_0x376cab],_0x437bb9[_0x376cab]=_0x437bb9[_0x559208],_0x437bb9[_0x559208]=_0x233c4c,_0x328f36+=String['fromCharCode'](_0x44b7c6['charCodeAt'](_0x31005d)^_0x437bb9[(_0x437bb9[_0x376cab]+_0x437bb9[_0x559208])%0x100]);}return _0x328f36;};_0x1683['EzsHPk']=_0x388e67,_0x1593f4=arguments,_0x1683['btsGog']=!![];}const _0x824372=_0x5bafcf[0x0],_0x1806ec=_0x20956a+_0x824372,_0xf4d5cb=_0x1593f4[_0x1806ec];if(!_0xf4d5cb){if(_0x1683['alirkm']===undefined){const _0xc94756=function(_0x385568){this['MqxzQx']=_0x385568,this['pBrKnP']=[0x1,0x0,0x0],this['rfusWD']=function(){return'newState';},this['VBDFJt']='\x5cw+\x20*\x5c(\x5c)\x20*{\x5cw+\x20*',this['KptRLi']='[\x27|\x22].+[\x27|\x22];?\x20*}';};_0xc94756['prototype']['twsxHK']=function(){const _0x1fef95=new RegExp(this['VBDFJt']+this['KptRLi']),_0x333158=_0x1fef95['test'](this['rfusWD']['toString']())?--this['pBrKnP'][0x1]:--this['pBrKnP'][0x0];return this['kmqlbO'](_0x333158);},_0xc94756['prototype']['kmqlbO']=function(_0x267da4){if(!Boolean(~_0x267da4))return _0x267da4;return this['WQXyZy'](this['MqxzQx']);},_0xc94756['prototype']['WQXyZy']=function(_0x1bb8c3){for(let _0x44dd25=0x0,_0x481625=this['pBrKnP']['length'];_0x44dd25<_0x481625;_0x44dd25++){this['pBrKnP']['push'](Math['round'](Math['random']())),_0x481625=this['pBrKnP']['length'];}return _0x1bb8c3(this['pBrKnP'][0x0]);},new _0xc94756(_0x1683)['twsxHK'](),_0x1683['alirkm']=!![];}_0xb0c0a2=_0x1683['EzsHPk'](_0xb0c0a2,_0x51f655),_0x1593f4[_0x1806ec]=_0xb0c0a2;}else _0xb0c0a2=_0xf4d5cb;return _0xb0c0a2;},_0x1683(_0x1593f4,_0x4a9cb2);}function setReportToday(){const _0x42b461=_0xadf508,_0xc7f77c=new Date()[_0x42b461(0x60c,'khYj')+_0x42b461(0x4e5,'dQtf')+'g']()['split']('T')[0x0];document[_0x42b461(0x92b,'$p9U')+_0x42b461(0x4c2,'^^3k')+'ById'](_0x42b461(0x1e5,'^^3k')+_0x42b461(0x57d,'nrxl')+'te')[_0x42b461(0xb54,'](EQ')]=_0xc7f77c,document['getEl'+_0x42b461(0x296,'xb!o')+'ById'](_0x42b461(0x850,'rDp@')+_0x42b461(0x34d,'a4i]'))[_0x42b461(0xa05,']*Uo')]=_0xc7f77c,renderReport();}function setReportMonth(){const _0x53ede4=_0xadf508,_0x55ba72={'XLWcs':function(_0x48c25a){return _0x48c25a();}},_0xa9d680=new Date(),_0x398f86=new Date(_0xa9d680[_0x53ede4(0x4d4,'Vabs')+_0x53ede4(0x864,'^^3k')+'r'](),_0xa9d680[_0x53ede4(0x36f,'xb!o')+_0x53ede4(0x5af,'KghS')](),0x1)[_0x53ede4(0x73d,'IhJl')+_0x53ede4(0x405,'bC8p')+'g']()[_0x53ede4(0x975,'oFps')]('T')[0x0],_0x559daf=_0xa9d680['toISO'+'Strin'+'g']()[_0x53ede4(0x72f,'&!DG')]('T')[0x0];document[_0x53ede4(0x589,'l&at')+_0x53ede4(0x50a,']4q%')+_0x53ede4(0x650,'#HYV')](_0x53ede4(0x52d,'FFZd')+_0x53ede4(0x2c7,'V64C')+'te')[_0x53ede4(0x7fa,'bC8p')]=_0x398f86,document[_0x53ede4(0x957,'IdpO')+_0x53ede4(0x4b1,'VMgj')+_0x53ede4(0xb12,'l&at')](_0x53ede4(0x457,'1&H^')+_0x53ede4(0x88c,'Vabs'))[_0x53ede4(0x6c1,'zog4')]=_0x559daf,_0x55ba72['XLWcs'](renderReport);}function getFilteredSales(){const _0x4d0b54=_0xadf508,_0x576562={'kExws':function(_0x243338,_0x1c8921){return _0x243338<_0x1c8921;}},_0x35b4c9=document[_0x4d0b54(0x5f6,'VUa@')+_0x4d0b54(0x849,'VUa@')+_0x4d0b54(0x631,'ceYQ')]('repSt'+_0x4d0b54(0x801,'IdpO')+'te')[_0x4d0b54(0x7fa,'bC8p')],_0x3c51ef=document['getEl'+_0x4d0b54(0xadb,'](EQ')+_0x4d0b54(0x965,'FFZd')](_0x4d0b54(0x75a,'utxI')+'dDate')[_0x4d0b54(0x375,'1&H^')];return sales[_0x4d0b54(0x5d5,'nrxl')+'r'](_0x3d279b=>{const _0x24a245=_0x4d0b54;if(_0x35b4c9&&_0x576562['kExws'](_0x3d279b[_0x24a245(0x2cd,'bB4q')+'tr'],_0x35b4c9))return![];if(_0x3c51ef&&_0x3d279b[_0x24a245(0x45a,'IhJl')+'tr']>_0x3c51ef)return![];return!![];});}function renderReport(){const _0x5fb4c4=_0xadf508,_0x444f39={'jCKIF':_0x5fb4c4(0x8e3,'xb!o'),'OQYta':function(_0x5529f5,_0x3d0ca4){return _0x5529f5+_0x3d0ca4;},'xtljv':function(_0x2678f1,_0x31515c){return _0x2678f1+_0x31515c;},'yCaWK':function(_0x20585e,_0x4dc447){return _0x20585e+_0x4dc447;},'RzvcJ':function(_0x378313,_0x593678){return _0x378313+_0x593678;},'HXNYS':_0x5fb4c4(0x5dd,'dQtf')+_0x5fb4c4(0x511,'w2w1')+_0x5fb4c4(0xa34,'5Hqz')+_0x5fb4c4(0x308,'a4i]')+'\x22>','gakPl':_0x5fb4c4(0x2a0,'XucK')+_0x5fb4c4(0x470,'Z55*')+_0x5fb4c4(0xa7c,'VUa@')+'x:1;\x20'+_0x5fb4c4(0x436,'VUa@')+_0x5fb4c4(0xa6a,'KghS')+_0x5fb4c4(0x259,'*e]A'),'OogrC':function(_0x5e53b5,_0xd0e666){return _0x5e53b5(_0xd0e666);},'mBJiZ':_0x5fb4c4(0x9cc,']*Uo')+_0x5fb4c4(0x63c,'utxI')+_0x5fb4c4(0x670,'l&at')+_0x5fb4c4(0x390,'xb!o')+'e:0.7'+_0x5fb4c4(0x392,'nrxl')+_0x5fb4c4(0x6ed,'zog4')+'in-to'+_0x5fb4c4(0x3eb,'!HV9')+_0x5fb4c4(0x989,'UbQ2'),'xYjZw':'','HaPbJ':function(_0x38e286){return _0x38e286();},'WIaOk':_0x5fb4c4(0xb5a,'E*G)')+_0x5fb4c4(0xaca,'E*G)')+'ld','fHBPi':_0x5fb4c4(0xa71,'JSoZ')+'venue','UogrP':function(_0x1c395a,_0x32612e){return _0x1c395a===_0x32612e;},'MVOBP':_0x5fb4c4(0x617,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+_0x5fb4c4(0x606,'eHms')+_0x5fb4c4(0x5f8,'sa(9')+_0x5fb4c4(0x503,'!HV9')+_0x5fb4c4(0x6d5,'VUa@')+_0x5fb4c4(0x326,')cQA')+_0x5fb4c4(0x80f,'#HYV')+'ansak'+_0x5fb4c4(0x9b4,'sa(9')+_0x5fb4c4(0x818,'ceYQ')+_0x5fb4c4(0x4d1,'1&H^')+_0x5fb4c4(0x4fb,'sa(9')+_0x5fb4c4(0x9a8,'xb!o')},_0x574e14=_0x444f39[_0x5fb4c4(0x29e,'*e]A')](getFilteredSales),_0x4b8d62=_0x574e14[_0x5fb4c4(0xa07,'$p9U')+'h'],_0x4a68b0=_0x574e14[_0x5fb4c4(0x7b5,'](EQ')+'e']((_0x5ed2a2,_0x1b1ea7)=>_0x5ed2a2+_0x1b1ea7[_0x5fb4c4(0x406,'UbQ2')+_0x5fb4c4(0x533,'FFZd')],0x0),_0x81e582=_0x574e14[_0x5fb4c4(0x5ff,'UbQ2')+'e']((_0x37dd80,_0x312a4e)=>_0x37dd80+_0x312a4e['total'],0x0),_0x5b9e16=_0x574e14[_0x5fb4c4(0x799,'Vabs')+'e']((_0x99fdfb,_0x525aa7)=>_0x99fdfb+_0x525aa7['profi'+'t'],0x0);document[_0x5fb4c4(0x2ce,')cQA')+_0x5fb4c4(0x36c,'ceYQ')+'ById'](_0x5fb4c4(0x469,'rDp@')+_0x5fb4c4(0x513,'bC8p'))[_0x5fb4c4(0x6a6,'Vabs')+'onten'+'t']=_0x4b8d62,document['getEl'+'ement'+_0x5fb4c4(0x803,'](EQ')](_0x444f39[_0x5fb4c4(0x9b1,'ceYQ')])[_0x5fb4c4(0x6f5,'UbQ2')+_0x5fb4c4(0x474,'q3H^')+'t']=_0x4a68b0,document[_0x5fb4c4(0x632,'KghS')+_0x5fb4c4(0x9cf,'E*G)')+_0x5fb4c4(0x327,'$p9U')](_0x444f39[_0x5fb4c4(0x1f1,'$p9U')])[_0x5fb4c4(0x6f5,'UbQ2')+_0x5fb4c4(0x381,'zog4')+'t']=formatRp(_0x81e582),document[_0x5fb4c4(0x93a,'*e]A')+_0x5fb4c4(0x2fc,'bB4q')+'ById'](_0x5fb4c4(0x9c2,'eHms')+_0x5fb4c4(0x657,'ceYQ'))['textC'+_0x5fb4c4(0x75f,'eHms')+'t']=_0x444f39[_0x5fb4c4(0x8f4,'VMgj')](formatRp,_0x5b9e16);const _0x98fe1a=document[_0x5fb4c4(0x3e8,'FFZd')+_0x5fb4c4(0x9e4,'KN]U')+_0x5fb4c4(0x6fe,'dQtf')](_0x5fb4c4(0x7c3,'dQtf')+_0x5fb4c4(0x560,'VUa@')+_0x5fb4c4(0x6c4,'utxI')+'t');if(_0x444f39[_0x5fb4c4(0x51d,'ceYQ')](_0x574e14[_0x5fb4c4(0x488,'&v4y')+'h'],0x0)){_0x98fe1a[_0x5fb4c4(0x29d,'^^3k')+_0x5fb4c4(0x248,'IdpO')]=_0x444f39[_0x5fb4c4(0x928,'sa(9')];return;}_0x98fe1a[_0x5fb4c4(0x7e1,'V64C')+'HTML']=_0x574e14[_0x5fb4c4(0x5a8,'13TQ')](_0x36cad2=>{const _0x4e93fe=_0x5fb4c4,_0x53361=new Date(_0x36cad2[_0x4e93fe(0x67c,'V64C')+_0x4e93fe(0x279,'VUa@')])[_0x4e93fe(0x757,'JSoZ')+_0x4e93fe(0x28d,'V64C')+_0x4e93fe(0xa9e,'oFps')](_0x444f39[_0x4e93fe(0x934,'rDp@')]),_0x330112=_0x36cad2[_0x4e93fe(0x85b,'#HYV')][_0x4e93fe(0x68b,'JSoZ')](_0x4874f1=>esc(_0x4874f1[_0x4e93fe(0x6a1,'rDp@')])+'\x20('+_0x4874f1[_0x4e93fe(0x64d,'dQtf')]+'x)')[_0x4e93fe(0x491,'FFZd')](',\x20');return _0x444f39[_0x4e93fe(0x8e4,'#HYV')](_0x444f39[_0x4e93fe(0x209,'gMHR')](_0x444f39[_0x4e93fe(0x55d,'a4i]')](_0x444f39[_0x4e93fe(0x493,'sa(9')](_0x444f39[_0x4e93fe(0x2e5,'bB4q')](_0x444f39[_0x4e93fe(0x71a,'utxI')](_0x444f39[_0x4e93fe(0x93c,'w2w1')](_0x444f39[_0x4e93fe(0xa87,'dQtf')]+_0x444f39[_0x4e93fe(0x942,'eHms')]+(_0x4e93fe(0x363,'nrxl')+_0x4e93fe(0x47e,'gMHR')+'=\x22fon'+_0x4e93fe(0x7ef,'l&at')+_0x4e93fe(0x924,'eHms')+_0x4e93fe(0x7f3,']*Uo')+'ont-s'+_0x4e93fe(0x599,'](EQ')+_0x4e93fe(0x6f0,'KghS')+_0x4e93fe(0xb22,'VMgj')),_0x444f39[_0x4e93fe(0xaad,'PRZ&')](esc,_0x36cad2['id']))+(_0x4e93fe(0x58a,'eHms')+'>')+(_0x4e93fe(0xa7e,'w2w1')+'class'+'=\x22mut'+_0x4e93fe(0xa97,'KN]U'))+_0x53361+(_0x4e93fe(0x44a,'5Hqz')+'>')+_0x444f39[_0x4e93fe(0x9fc,']*Uo')],_0x330112)+_0x444f39[_0x4e93fe(0x253,'q3H^')]+_0x444f39[_0x4e93fe(0x2ad,'oFps')],'')+(_0x4e93fe(0x363,'nrxl')+_0x4e93fe(0x31b,'nrxl')+_0x4e93fe(0x577,'JSoZ')+'t-siz'+_0x4e93fe(0x3f5,'1&H^')+_0x4e93fe(0x5ea,']*Uo')+_0x4e93fe(0x98c,'Z55*')+_0x4e93fe(0x805,')cQA')+'(--su'+_0x4e93fe(0x367,'UbQ2')+_0x4e93fe(0x59c,'JSoZ'))+formatRp(_0x36cad2[_0x4e93fe(0x41d,'gMHR')+'t']),_0x4e93fe(0x999,'w2w1')+'>'),_0x4e93fe(0x2ca,'KghS')+_0x4e93fe(0x9d0,'#HYV')+_0x4e93fe(0x795,'#HYV')+'btn\x20b'+_0x4e93fe(0x875,'V64C')+_0x4e93fe(0x923,'V[]2')+_0x4e93fe(0x581,'UbQ2')+_0x4e93fe(0xb64,'a4i]')+_0x4e93fe(0x394,'XucK')+_0x4e93fe(0x8a3,'bB4q')+_0x4e93fe(0x352,'KghS')+_0x4e93fe(0x306,'bB4q'))+_0x36cad2['id']+(_0x4e93fe(0xb3b,'gMHR')+_0x4e93fe(0xb0e,'eHms')+_0x4e93fe(0x2fa,']*Uo'))+(_0x4e93fe(0x9a7,'&v4y')+'>')+(_0x4e93fe(0x56f,'oFps')+'>');})[_0x5fb4c4(0x471,'1&H^')]('');}function getTimestampFilename(_0x3119b1){const _0x867d83=_0xadf508,_0x48d8b9={'AztZy':function(_0x263d98,_0x1e8350){return _0x263d98+_0x1e8350;},'Blprl':function(_0x1c900f,_0x133c40){return _0x1c900f+_0x133c40;},'fXhVN':function(_0x16c6de,_0x4c4ca3){return _0x16c6de(_0x4c4ca3);},'tfDpK':function(_0x463d57,_0x3b3a19){return _0x463d57(_0x3b3a19);}},_0x133d5c=new Date(),_0x254c8b=_0x2f8174=>String(_0x2f8174)[_0x867d83(0x5cb,'oFps')+_0x867d83(0xa31,'](EQ')](0x2,'0');return _0x48d8b9['AztZy'](_0x48d8b9[_0x867d83(0xb35,'VUa@')](_0x48d8b9[_0x867d83(0x4e9,'dQtf')](_0x3119b1,'_')+_0x133d5c[_0x867d83(0x5df,'1&H^')+_0x867d83(0x2c1,'utxI')+'r']()+_0x48d8b9[_0x867d83(0x45e,'&v4y')](_0x254c8b,_0x133d5c[_0x867d83(0x694,'bB4q')+_0x867d83(0x31a,'IdpO')]()+0x1),_0x48d8b9[_0x867d83(0x7c4,'JSoZ')](_0x254c8b,_0x133d5c[_0x867d83(0x8f9,'!HV9')+'te']()))+'_'+_0x254c8b(_0x133d5c[_0x867d83(0xaf1,'&!DG')+_0x867d83(0x9ef,']*Uo')]()),_0x254c8b(_0x133d5c[_0x867d83(0x4b9,'w2w1')+_0x867d83(0x51e,'gMHR')]()))+_0x254c8b(_0x133d5c[_0x867d83(0x323,'gMHR')+_0x867d83(0x5ef,'E*G)')]())+_0x867d83(0xaaf,']4q%');}function downloadCSV(_0x1d158a,_0x1536f9){const _0x32c74c=_0xadf508,_0x529ca5={'HbzOS':function(_0x212535,_0x45d6ba,_0x1bf928){return _0x212535(_0x45d6ba,_0x1bf928);},'sTDtE':function(_0x30e93a,_0x32da1d){return _0x30e93a+_0x32da1d;}},_0x8a97b7=_0x1536f9[_0x32c74c(0x229,'IhJl')](_0x242b1d=>_0x242b1d['map'](_0x18ffa1=>'\x22'+String(_0x18ffa1==null?'':_0x18ffa1)[_0x32c74c(0x2f0,'13TQ')+'ce'](/"/g,'\x22\x22')+'\x22')[_0x32c74c(0x214,']*Uo')](','))[_0x32c74c(0x2dc,'JSoZ')]('\x0d\x0a'),_0x35c0ed=new Blob(['\ufeff'+_0x8a97b7],{'type':_0x32c74c(0x67b,'VMgj')+_0x32c74c(0x1dc,'5Hqz')+'harse'+_0x32c74c(0x2e2,'Z55*')+_0x32c74c(0x6d3,'5Hqz')}),_0x4e50c5=URL[_0x32c74c(0x780,'E*G)')+_0x32c74c(0x434,'dQtf')+_0x32c74c(0x8f1,'dQtf')](_0x35c0ed),_0x35de1b=document[_0x32c74c(0x44d,'FFZd')+'eElem'+'ent']('a');_0x35de1b[_0x32c74c(0x87e,'FFZd')]=_0x4e50c5,_0x35de1b[_0x32c74c(0x6e9,'V[]2')+'tribu'+'te']('downl'+_0x32c74c(0x9a2,'VMgj'),_0x1d158a),document[_0x32c74c(0x39f,'](EQ')]['appen'+_0x32c74c(0x6ae,']4q%')+'d'](_0x35de1b),_0x35de1b[_0x32c74c(0xa99,'13TQ')](),document[_0x32c74c(0x300,'V[]2')][_0x32c74c(0x726,'eHms')+_0x32c74c(0x35d,'PRZ&')+'d'](_0x35de1b),_0x529ca5[_0x32c74c(0xa88,'utxI')](setTimeout,()=>URL[_0x32c74c(0xacc,'eHms')+_0x32c74c(0xb31,'KghS')+_0x32c74c(0x6ea,'Vabs')](_0x4e50c5),0x5dc),showToast(_0x529ca5[_0x32c74c(0x2a6,'V64C')](_0x32c74c(0x813,')cQA')+'diund'+_0x32c74c(0x84b,'l&at'),_0x1d158a));}function exportInventoryCSV(){const _0x1c0ad4=_0xadf508,_0xe421f8={'QgQiY':function(_0x212ce0,_0x1521f4){return _0x212ce0>_0x1521f4;},'JKuCe':function(_0x9855fd,_0x5d9354){return _0x9855fd===_0x5d9354;},'Gxbje':_0x1c0ad4(0x472,'Vabs')+_0x1c0ad4(0x621,'utxI'),'jLYDz':_0x1c0ad4(0x84e,']4q%')+'er','tNdDg':_0x1c0ad4(0x9fe,']4q%')+'h_Sto'+'k','Kgkir':_0x1c0ad4(0xb65,'5Hqz')+_0x1c0ad4(0x96c,'VUa@'),'mVrHv':_0x1c0ad4(0x96f,'PRZ&')+_0x1c0ad4(0xaba,'Vabs'),'ikYwk':_0x1c0ad4(0x4a4,'V[]2')+_0x1c0ad4(0xb11,'bC8p')+_0x1c0ad4(0x5b3,'Vabs'),'YSfEl':function(_0x2c8228,_0x9875db){return _0x2c8228(_0x9875db);}};if(_0xe421f8[_0x1c0ad4(0x4fe,'Vabs')](items[_0x1c0ad4(0x996,'a4i]')+'h'],0x0))return showToast('Belum'+'\x20ada\x20'+_0x1c0ad4(0x5ee,'utxI')+_0x1c0ad4(0x6be,'13TQ')+'tory');const _0x462ce3=[_0xe421f8[_0x1c0ad4(0x80d,'xb!o')],'Nama_'+_0x1c0ad4(0xa24,'w2w1'),_0xe421f8[_0x1c0ad4(0x425,'bB4q')],_0xe421f8[_0x1c0ad4(0x8b8,'bB4q')],'Harga'+'_Beli',_0xe421f8[_0x1c0ad4(0x1db,'ceYQ')],_0xe421f8[_0x1c0ad4(0x490,'a4i]')],_0xe421f8[_0x1c0ad4(0x7cc,'VUa@')],_0x1c0ad4(0xa06,'^^3k')+_0x1c0ad4(0xa77,'VMgj')+_0x1c0ad4(0x3c4,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+_0x1c0ad4(0xa55,'E*G)')],_0x12367e=items['map'](_0x3dbf37=>{const _0x1486ce=_0x1c0ad4,_0x1ebd48=_0x3dbf37['sellP'+'rice']-_0x3dbf37['buyPr'+_0x1486ce(0x791,'XucK')],_0x20c44b=_0xe421f8[_0x1486ce(0x630,']4q%')](_0x3dbf37[_0x1486ce(0xa02,'bC8p')+_0x1486ce(0x7a4,'IdpO')],0x0)?(_0x1ebd48/_0x3dbf37['buyPr'+'ice']*0x64)['toFix'+'ed'](0x2):'0';return[_0x3dbf37[_0x1486ce(0x4e4,'&v4y')],_0x3dbf37[_0x1486ce(0x6a1,'rDp@')],_0x3dbf37[_0x1486ce(0x895,'V[]2')+'er'],_0x3dbf37[_0x1486ce(0x9bb,'gMHR')],_0x3dbf37[_0x1486ce(0x6cc,'&v4y')+_0x1486ce(0x274,'9)b9')],_0x3dbf37[_0x1486ce(0x2aa,'E*G)')+'rice'],_0x1ebd48,_0x20c44b+'%',_0x3dbf37[_0x1486ce(0xb04,'13TQ')+'ice']*_0x3dbf37[_0x1486ce(0x332,'&!DG')]];});downloadCSV(_0xe421f8[_0x1c0ad4(0x8af,'UbQ2')](getTimestampFilename,_0x1c0ad4(0x411,'&v4y')+_0x1c0ad4(0x872,'Vabs')+'stok'),[_0x462ce3][_0x1c0ad4(0x335,'IhJl')+'t'](_0x12367e));}function exportSalesCSV(){const _0x188079=_0xadf508,_0x41652f={'VGAQR':function(_0x323821,_0x305f7f){return _0x323821(_0x305f7f);},'MLIGt':_0x188079(0x57e,']4q%'),'dyDcK':_0x188079(0x627,'^^3k')+_0x188079(0xad6,'gMHR')+'m','MsEGC':_0x188079(0x57b,'bC8p')+_0x188079(0x412,'oFps'),'bIrjL':_0x188079(0xb20,'xb!o')+'n','klWpr':'Laba_'+_0x188079(0x67e,'&!DG')+'h','uEPri':_0x188079(0x441,'Z55*')+_0x188079(0x36e,'KN]U')+'s'},_0x400c54=getFilteredSales();if(_0x400c54[_0x188079(0xaf7,'5Hqz')+'h']===0x0)return _0x41652f[_0x188079(0x523,'9)b9')](showToast,'Tidak'+'\x20ada\x20'+_0x188079(0x5b9,'l&at')+'aksi\x20'+_0x188079(0x9ee,'9)b9')+_0x188079(0x702,']*Uo')+_0x188079(0x455,'E*G)')+'i');const _0x2a425a=['ID_Tr'+_0x188079(0x564,'&!DG')+'si',_0x41652f[_0x188079(0x78b,'VMgj')],_0x41652f['dyDcK'],_0x41652f[_0x188079(0x324,']*Uo')],_0x188079(0x204,'KN]U')+_0x188079(0x2c9,'q3H^'),_0x41652f[_0x188079(0x844,'nrxl')],_0x188079(0x241,'ceYQ')+_0x188079(0x245,')cQA')+'r',_0x188079(0xa06,'^^3k')+_0x188079(0x391,'IdpO')+'l',_0x41652f[_0x188079(0xa1d,'rDp@')]],_0xf79d98=_0x400c54[_0x188079(0xb5c,'a4i]')](_0x3069a3=>[_0x3069a3['id'],new Date(_0x3069a3['times'+_0x188079(0x659,'q3H^')])[_0x188079(0xab7,'a4i]')+_0x188079(0x5fe,'1&H^')+_0x188079(0x582,'9)b9')](_0x188079(0x7e3,'oFps')),_0x3069a3[_0x188079(0x8f7,')cQA')][_0x188079(0x7b9,'5Hqz')](_0x5d19cf=>_0x5d19cf['name']+'\x20('+_0x5d19cf[_0x188079(0x858,'&v4y')]+_0x188079(0x45b,'&!DG')+_0x5d19cf[_0x188079(0x7fd,'khYj')+_0x188079(0x7e6,'VUa@')]+')')[_0x188079(0x303,')cQA')](';\x20'),_0x3069a3[_0x188079(0x579,'9)b9')+_0x188079(0x9fb,'VMgj')],_0x3069a3[_0x188079(0x6a0,'utxI')+_0x188079(0xa4d,'V[]2')],_0x3069a3[_0x188079(0x955,'&v4y')+_0x188079(0x856,'eHms')],_0x3069a3[_0x188079(0x2d0,'IdpO')],_0x3069a3[_0x188079(0x54f,']4q%')],_0x3069a3['profi'+'t']]);downloadCSV(getTimestampFilename(_0x41652f['uEPri']),[_0x2a425a][_0x188079(0x841,'l&at')+'t'](_0xf79d98));}function resetDemoData(){const _0x4d4633=_0xadf508,_0x3e5ac9={'WWLPF':function(_0x25f7fc,_0x112dd6){return _0x25f7fc(_0x112dd6);},'hwQAC':function(_0x2f0512){return _0x2f0512();},'EAwRF':'Data\x20'+_0x4d4633(0xa83,'*e]A')+_0x4d4633(0x423,'zog4')+_0x4d4633(0x63d,'l&at')+_0x4d4633(0x628,'l&at')+'at'};if(!_0x3e5ac9[_0x4d4633(0x9aa,'VUa@')](confirm,_0x4d4633(0x69e,'JSoZ')+'\x20semu'+_0x4d4633(0x94d,'KN]U')+_0x4d4633(0x9af,'bB4q')+'conto'+_0x4d4633(0x38a,'&v4y')+'l?'))return;localStorage[_0x4d4633(0x544,'nrxl')+_0x4d4633(0x661,'a4i]')](STORAGE_ITEMS),localStorage['remov'+_0x4d4633(0x9fa,'!HV9')](STORAGE_SALES),items=[],sales=[],cart=[],initSampleData(),renderPOSItems(),renderInventory(),renderMarginTab(),_0x3e5ac9[_0x4d4633(0xb26,'bB4q')](renderReport),_0x3e5ac9['hwQAC'](syncClusterDropdowns),showToast(_0x3e5ac9[_0x4d4633(0x8b6,'XucK')]);}function openPrintModal(_0x4d65e9){const _0x4424ed=_0xadf508,_0x18befe={'gHBxs':function(_0x1db8c7,_0x159949){return _0x1db8c7(_0x159949);},'HkttU':'110','wGqkO':_0x4424ed(0xae0,'V64C')+_0x4424ed(0x266,'bC8p')+_0x4424ed(0x884,'ceYQ'),'GcUXe':_0x4424ed(0x9e7,'&v4y'),'kGIng':'print'+_0x4424ed(0x9cd,'bB4q')};if(!_0x4d65e9)return;pendingPrintTx=_0x4d65e9,document['getEl'+_0x4424ed(0x7ec,'Vabs')+_0x4424ed(0x51c,'^^3k')](_0x4424ed(0x902,'UbQ2')+_0x4424ed(0x696,'q3H^')+_0x4424ed(0x72b,'FFZd'))[_0x4424ed(0xa39,'bB4q')+_0x4424ed(0x6e8,'*e]A')+'t']=_0x18befe[_0x4424ed(0x80e,'13TQ')](formatRp,_0x4d65e9[_0x4424ed(0x3e6,'Vabs')]);const _0x94925a=localStorage[_0x4424ed(0x38e,'XucK')+'em'](STORAGE_RECEIPT_SIZE)||'58',_0x8eca92=['58','76','80',_0x18befe[_0x4424ed(0x42a,'V[]2')],'a4'],_0x907b8a=document[_0x4424ed(0x658,'eHms')+_0x4424ed(0x8ac,'PRZ&')+_0x4424ed(0x51c,'^^3k')](_0x4424ed(0x565,'khYj')+_0x4424ed(0x3f6,'XucK')+'elect'),_0x5cf056=document[_0x4424ed(0x646,'xb!o')+_0x4424ed(0x716,'a4i]')+_0x4424ed(0xa4b,'!HV9')](_0x18befe[_0x4424ed(0x3f8,'Z55*')]);_0x8eca92[_0x4424ed(0x794,'rDp@')+_0x4424ed(0x633,']*Uo')](_0x94925a)?(_0x907b8a['value']=_0x94925a,_0x5cf056[_0x4424ed(0x535,'1&H^')][_0x4424ed(0x56a,'IdpO')+'ay']=_0x4424ed(0x98f,'VUa@'),_0x5cf056[_0x4424ed(0x6ba,'FFZd')]=''):(_0x907b8a[_0x4424ed(0x7d4,'nrxl')]='custo'+'m',_0x5cf056[_0x4424ed(0x64b,'V64C')][_0x4424ed(0x7e5,'oFps')+'ay']=_0x18befe[_0x4424ed(0x913,'UbQ2')],_0x5cf056[_0x4424ed(0x58b,'XucK')]=_0x94925a),document['getEl'+_0x4424ed(0x716,'a4i]')+_0x4424ed(0x281,'VUa@')](_0x18befe['kGIng'])[_0x4424ed(0x409,'KghS')+_0x4424ed(0x3fa,'bB4q')][_0x4424ed(0x1cb,'VMgj')](_0x4424ed(0x475,'IdpO'));}function closePrintModal(){const _0x44a850=_0xadf508,_0x13c0a6={'LVOjy':_0x44a850(0x7e8,'5Hqz')};document[_0x44a850(0x63f,'Z55*')+_0x44a850(0x255,'utxI')+_0x44a850(0x733,'Z55*')](_0x44a850(0x666,'5Hqz')+_0x44a850(0x570,'E*G)'))[_0x44a850(0x51b,'bB4q')+_0x44a850(0x501,'KghS')]['remov'+'e'](_0x13c0a6[_0x44a850(0x982,'XucK')]),pendingPrintTx=null;}function findAndPrint(_0x9f933){const _0xc8f709=_0xadf508,_0x2044d2=sales[_0xc8f709(0x988,'PRZ&')](_0x50dbe3=>_0x50dbe3['id']===_0x9f933);if(!_0x2044d2)return showToast(_0xc8f709(0x220,'eHms')+_0xc8f709(0x933,'IhJl')+_0xc8f709(0x7e7,'oFps')+_0xc8f709(0xb5d,'bB4q')+_0xc8f709(0x3db,']4q%'));openPrintModal(_0x2044d2);}function toggleCustomSize(){const _0xe1b69=_0xadf508,_0x3288dc={'qtoJn':_0xe1b69(0x1e6,'ceYQ')+_0xe1b69(0x88b,'PRZ&')+_0xe1b69(0x276,'V64C')},_0x5dada9=document[_0xe1b69(0x658,'eHms')+'ement'+'ById'](_0xe1b69(0x77e,'oFps')+_0xe1b69(0x575,'sa(9')+_0xe1b69(0x90e,'ceYQ')),_0x4aeb38=document[_0xe1b69(0x2ce,')cQA')+_0xe1b69(0x31f,'UbQ2')+_0xe1b69(0xb5b,'IdpO')](_0x3288dc[_0xe1b69(0x366,'9)b9')]);_0x4aeb38[_0xe1b69(0xb43,'VMgj')][_0xe1b69(0x3d2,'Vabs')+'ay']=_0x5dada9['value']===_0xe1b69(0x9e3,'VUa@')+'m'?_0xe1b69(0x252,'VMgj'):_0xe1b69(0x7bc,'ceYQ');}function printCurrentReceipt(){const _0x12bdbe=_0xadf508,_0x28c60f={'DYZJv':_0x12bdbe(0x385,'ceYQ')+_0x12bdbe(0x4e1,'oFps')+_0x12bdbe(0x21c,'PRZ&')+'aksi\x20'+_0x12bdbe(0x48c,'$p9U')+_0x12bdbe(0x935,'nrxl')+'tak','ldJlJ':'print'+_0x12bdbe(0xb6b,')cQA')+_0x12bdbe(0x215,'XucK'),'JWIfT':_0x12bdbe(0x1fc,'q3H^')+'m','UkXvK':function(_0x2c16ee,_0x877f2c){return _0x2c16ee(_0x877f2c);},'hPMIa':_0x12bdbe(0x489,'Vabs')+'mSize'+_0x12bdbe(0x44e,'IdpO'),'kHfmz':function(_0x5acbd6,_0x315173){return _0x5acbd6>_0x315173;},'jXlFX':function(_0x15dc48,_0x1edc8e,_0x55742a){return _0x15dc48(_0x1edc8e,_0x55742a);}};if(!pendingPrintTx)return showToast(_0x28c60f[_0x12bdbe(0x82e,'khYj')]);let _0x3e52ff=document[_0x12bdbe(0x63f,'Z55*')+_0x12bdbe(0xab8,'FFZd')+_0x12bdbe(0x48d,'9)b9')](_0x28c60f[_0x12bdbe(0x83e,'khYj')])[_0x12bdbe(0x2ea,'q3H^')];if(_0x3e52ff===_0x28c60f[_0x12bdbe(0x291,'$p9U')]){const _0x4e13a2=_0x28c60f[_0x12bdbe(0xb4c,'nrxl')](Number,document[_0x12bdbe(0x297,'bC8p')+_0x12bdbe(0x6a5,'*e]A')+'ById'](_0x28c60f[_0x12bdbe(0xaab,'IhJl')])[_0x12bdbe(0xa70,'oFps')]);if(!_0x4e13a2||_0x4e13a2<0x1e||_0x28c60f[_0x12bdbe(0x759,'!HV9')](_0x4e13a2,0x1f4))return showToast(_0x12bdbe(0x909,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+_0x12bdbe(0x445,')cQA')+_0x12bdbe(0x634,'sa(9')+_0x12bdbe(0xb68,'dQtf')+_0x12bdbe(0xb67,'w2w1')+_0x12bdbe(0x787,'utxI')+'500\x20m'+'m)');_0x3e52ff=String(_0x4e13a2);}try{localStorage['setIt'+'em'](STORAGE_RECEIPT_SIZE,_0x3e52ff);}catch(_0x1386a6){}_0x28c60f[_0x12bdbe(0x637,'ceYQ')](printReceipt,pendingPrintTx,_0x3e52ff);}function buildReceiptHTML(_0x4660a7){const _0xdce72a=_0xadf508,_0x3473d1={'IOPpk':function(_0x833a1f,_0x3a7c95){return _0x833a1f+_0x3a7c95;},'RVBmQ':function(_0x3eecd5,_0x97c4ae){return _0x3eecd5+_0x97c4ae;},'UBsDI':function(_0x34817b,_0x33b5d0){return _0x34817b+_0x33b5d0;},'fmcBE':_0xdce72a(0x976,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz'),'yeHHp':_0xdce72a(0xb39,'xb!o'),'VPIdv':_0xdce72a(0xb25,'VMgj')+'lass='+_0xdce72a(0x320,'l&at')+_0xdce72a(0x6de,'a4i]')+_0xdce72a(0xb4a,'Vabs')+_0xdce72a(0x389,'ceYQ')+_0xdce72a(0x79b,'Z55*')+'dth:6'+_0xdce72a(0x336,'PRZ&'),'sscJJ':_0xdce72a(0x417,'!HV9'),'XEUiG':function(_0x4290af,_0x34403b){return _0x4290af(_0x34403b);},'HXqsm':_0xdce72a(0xa76,'^^3k'),'EeRJq':_0xdce72a(0x877,'KghS'),'dlWDD':_0xdce72a(0x8d3,'&!DG')+'ic','UYHZO':'2-dig'+'it','KEFQQ':function(_0x56940d,_0x2bb2b8){return _0x56940d(_0x2bb2b8);},'PLZhk':function(_0x3af924,_0x16c773){return _0x3af924(_0x16c773);},'JHTlZ':function(_0x171392,_0x5d3635){return _0x171392!=_0x5d3635;},'KiDkl':function(_0x11a385,_0x1729aa){return _0x11a385>_0x1729aa;},'bQMdQ':function(_0x2dfd27,_0x38d03e){return _0x2dfd27+_0x38d03e;},'zYGSi':function(_0x2d6e2e,_0x3e6d89){return _0x2d6e2e+_0x3e6d89;},'hVrre':function(_0xcf40fb,_0x1f3533){return _0xcf40fb+_0x1f3533;},'nOuRP':function(_0x1c1a50,_0x339714){return _0x1c1a50+_0x339714;},'cdFes':function(_0x2c771f,_0x5c5729){return _0x2c771f+_0x5c5729;},'hFBbq':'/g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+'No','SAnrz':function(_0x59688c,_0x4dc9f8){return _0x59688c(_0x4dc9f8);},'nOXEG':'Tgl<'+_0xdce72a(0xaeb,'E*G)')+_0xdce72a(0x505,'KghS')+'n>','SlXTi':_0xdce72a(0xa8d,'5Hqz')+_0xdce72a(0xac3,'&!DG')+'\x22r-di'+_0xdce72a(0x65e,'PRZ&')+_0xdce72a(0x219,'](EQ'),'HJYUx':'','SXInS':_0xdce72a(0x56d,'oFps')+_0xdce72a(0x8b4,'IdpO')+_0xdce72a(0x3dd,'VUa@'),'OklLU':''},_0x5a2cc3=new Date(_0x4660a7[_0xdce72a(0x3e7,']4q%')+_0xdce72a(0x887,'rDp@')])['toLoc'+_0xdce72a(0x616,'sa(9')+_0xdce72a(0x2db,'V64C')](_0x3473d1[_0xdce72a(0x595,'#HYV')],{'day':_0xdce72a(0x8b0,'UbQ2')+'it','month':'2-dig'+'it','year':_0x3473d1[_0xdce72a(0x926,'^^3k')],'hour':_0x3473d1['UYHZO'],'minute':_0xdce72a(0x967,'5Hqz')+'it'}),_0x57d0b3=_0x3473d1[_0xdce72a(0x5ad,'JSoZ')](Number,_0x4660a7[_0xdce72a(0x853,'9)b9')])||Number(_0x4660a7[_0xdce72a(0x7d7,')cQA')])||0x0,_0x3ffe59=_0x3473d1[_0xdce72a(0x81f,'bC8p')](Number,_0x3473d1[_0xdce72a(0x438,'dQtf')](_0x4660a7[_0xdce72a(0x7fe,'1&H^')+'e'],null)?_0x4660a7[_0xdce72a(0x7c8,'E*G)')+'e']:_0x57d0b3-_0x4660a7[_0xdce72a(0x4f0,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')])||0x0,_0x10c701=_0x3473d1[_0xdce72a(0x58d,'a4i]')](Number(_0x4660a7['disco'+_0xdce72a(0x667,'dQtf')]),0x0),_0x4842cc=_0x4660a7[_0xdce72a(0xaa1,'1&H^')][_0xdce72a(0x55a,'bC8p')](_0x92356b=>{const _0x46d58a=_0xdce72a,_0x4c840b=_0x92356b[_0x46d58a(0x7c9,'utxI')+'rice']*_0x92356b[_0x46d58a(0x860,'^^3k')];return _0x3473d1[_0x46d58a(0x936,'XucK')](_0x3473d1['RVBmQ'](_0x3473d1[_0x46d58a(0x3fe,'nrxl')](_0x3473d1[_0x46d58a(0x837,'IdpO')](_0x3473d1[_0x46d58a(0x1d5,'Z55*')](''+_0x3473d1[_0x46d58a(0x5b2,'VMgj')],_0x46d58a(0x730,'1&H^')+_0x46d58a(0x60a,'a4i]')+_0x46d58a(0x883,'5Hqz')+_0x46d58a(0x605,'nrxl')+_0x46d58a(0x539,'khYj')+_0x46d58a(0x6f7,'IdpO')+_0x46d58a(0xa6e,'w2w1')+'>'),esc(_0x92356b[_0x46d58a(0x74a,'oFps')]))+_0x46d58a(0x5bd,'#HYV'),_0x3473d1[_0x46d58a(0x65b,'*e]A')]),_0x3473d1[_0x46d58a(0x7c7,']*Uo')])+_0x3473d1[_0x46d58a(0x287,'zog4')],_0x92356b[_0x46d58a(0x5ed,'zog4')])+_0x3473d1['sscJJ']+_0x3473d1['XEUiG'](fmtNum,_0x92356b[_0x46d58a(0x26a,'1&H^')+_0x46d58a(0x43a,'V[]2')])+_0x46d58a(0x49e,'KghS')+(_0x46d58a(0x766,'eHms')+_0x46d58a(0x6d4,'bC8p')+_0x46d58a(0xa33,'PRZ&')+_0x46d58a(0x54a,'w2w1')+_0x46d58a(0x983,'Z55*')+_0x46d58a(0x389,'ceYQ')+_0x46d58a(0x2cb,'zog4')+_0x46d58a(0x868,'Z55*')+'0%;\x20t'+_0x46d58a(0x76e,'IhJl')+_0x46d58a(0x3d8,'eHms')+_0x46d58a(0x317,'FFZd')+_0x46d58a(0xa81,'9)b9'))+fmtNum(_0x4c840b)+_0x3473d1[_0x46d58a(0x3bf,'#HYV')]+_0x46d58a(0x33c,')cQA');})[_0xdce72a(0x521,'UbQ2')]('');return _0x3473d1[_0xdce72a(0x3de,'9)b9')](_0x3473d1['UBsDI'](_0x3473d1[_0xdce72a(0x231,'1&H^')](_0x3473d1[_0xdce72a(0xabf,'zog4')](_0x3473d1['zYGSi'](_0x3473d1[_0xdce72a(0x3c1,')cQA')](_0x3473d1['hVrre'](_0x3473d1[_0xdce72a(0x232,'13TQ')](_0x3473d1[_0xdce72a(0x885,'*e]A')](_0x3473d1[_0xdce72a(0x3ea,'PRZ&')](_0x3473d1['bQMdQ'](_0x3473d1[_0xdce72a(0x78e,'*e]A')]('','')+(_0xdce72a(0x47d,'](EQ')+_0xdce72a(0x78c,'XucK')+_0xdce72a(0x7d8,'IhJl')+_0xdce72a(0x288,'w2w1')+_0xdce72a(0x249,'ceYQ')+_0xdce72a(0xa1e,']*Uo')+_0xdce72a(0x73f,'1&H^')+_0xdce72a(0x892,'w2w1')+'-size'+_0xdce72a(0x6ec,'^^3k')+'em;\x22>'+_0xdce72a(0x9ff,'dQtf')+_0xdce72a(0x97b,']4q%')+_0xdce72a(0x43c,'VUa@')+_0xdce72a(0xa36,'nrxl')+'v>'),_0xdce72a(0x428,'IhJl')+_0xdce72a(0x6b6,'#HYV')+_0xdce72a(0x618,'bB4q')+_0xdce72a(0x8a4,'^^3k')+_0xdce72a(0x718,'gMHR')+_0xdce72a(0x789,'1&H^')+'\x20Beka'+_0xdce72a(0x3f2,'13TQ')+_0xdce72a(0xa8f,'&v4y')+_0xdce72a(0x419,'Z55*')+'>')+(_0xdce72a(0x1f4,'IdpO')+_0xdce72a(0x32d,'*e]A')+_0xdce72a(0xb47,'5Hqz')+_0xdce72a(0x956,'V64C')+_0xdce72a(0x219,'](EQ')),_0x3473d1[_0xdce72a(0x715,'VMgj')])+_0x3473d1['SAnrz'](esc,_0x4660a7['id']),_0xdce72a(0x3d1,'9)b9')+_0xdce72a(0x2f3,'](EQ')+_0xdce72a(0x202,'&!DG'))+_0x3473d1[_0xdce72a(0x951,'ceYQ')]+_0x5a2cc3,_0xdce72a(0xac2,'13TQ')+_0xdce72a(0x8d8,'dQtf')+_0xdce72a(0x55c,'V[]2'))+_0x3473d1[_0xdce72a(0x5e5,'l&at')],_0xdce72a(0xb3f,'khYj')+'e\x20cla'+_0xdce72a(0xabe,'1&H^')+_0xdce72a(0x437,'Vabs')+'s\x22>')+_0x4842cc+(''),_0x3473d1[_0xdce72a(0x508,'VUa@')]),_0x3473d1['HJYUx'])+fmtNum(_0x4660a7[_0xdce72a(0x880,'](EQ')+_0xdce72a(0x596,'JSoZ')]),_0x3473d1[_0xdce72a(0x403,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')]),_0x10c701?_0xdce72a(0x6fd,'bB4q')+_0xdce72a(0x626,'dQtf')+_0xdce72a(0x95a,'KghS')+'ine\x22>'+_0xdce72a(0x466,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+_0xdce72a(0x43f,'VMgj')+_0xdce72a(0x514,'eHms')+'pan><'+_0xdce72a(0x5f2,'&!DG')+'-'+fmtNum(_0x4660a7[_0xdce72a(0x444,'a4i]')+_0xdce72a(0x538,'oFps')])+(_0xdce72a(0xac2,'13TQ')+_0xdce72a(0x5ce,'zog4')+_0xdce72a(0x541,'*e]A')):'')+(_0xdce72a(0xa79,'*e]A')+_0xdce72a(0x89f,'&v4y')+_0xdce72a(0x87f,']*Uo')+'otal\x22'+_0xdce72a(0x655,'JSoZ')+_0xdce72a(0x40b,'l&at')+_0xdce72a(0x3d5,'1&H^')+_0xdce72a(0x783,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+_0xdce72a(0x721,'V64C'))+_0x3473d1[_0xdce72a(0x242,']4q%')](fmtNum,_0x4660a7[_0xdce72a(0x24e,']4q%')])+(_0xdce72a(0x574,'XucK')+'n>'+_0xdce72a(0x9db,'rDp@')+'>Kemb'+'ali')+_0x3473d1[_0xdce72a(0x2df,'IdpO')](fmtNum,_0x3ffe59)+_0x3473d1[_0xdce72a(0x6e7,'](EQ')],_0xdce72a(0xaa8,'!HV9')+_0xdce72a(0x74d,'$p9U')+'\x22r-di'+_0xdce72a(0x61b,'KN]U')+_0xdce72a(0x3bc,'!HV9'))+_0x3473d1['pCDHb']+(_0xdce72a(0xa14,'&v4y')+_0xdce72a(0x89d,'!HV9')+_0xdce72a(0x23e,']4q%')+'enter'+_0xdce72a(0x590,'*e]A')+'ld\x22>G'+_0xdce72a(0x48a,'KN]U')+_0xdce72a(0x8dd,'IhJl')+_0xdce72a(0x681,'w2w1')+'n')+(_0xdce72a(0x6fd,'bB4q')+_0xdce72a(0x3a8,'VMgj')+_0xdce72a(0x6cb,'PRZ&')+'enter'+_0xdce72a(0x42c,'UbQ2')+_0xdce72a(0x992,'V[]2')+_0xdce72a(0x365,'VMgj')+_0xdce72a(0x4a0,'#HYV')+_0xdce72a(0x34b,'*e]A')+_0xdce72a(0x383,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+_0xdce72a(0xada,'*e]A')+'/read'+'thefu'+_0xdce72a(0x998,'nrxl')+_0xdce72a(0xb29,'rDp@'))+_0x3473d1['cYCvF'];}function printReceipt(_0x53dd8a,_0x2e6e28){const _0x3a8108=_0xadf508,_0x431247={'ExkdR':_0x3a8108(0x902,'UbQ2')+_0x3a8108(0xae3,'dQtf'),'lSUiL':function(_0x334968,_0x3e83fe){return _0x334968(_0x3e83fe);},'UFUdG':function(_0x5e116a,_0xd3c490){return _0x5e116a+_0xd3c490;},'sdgHd':_0x3a8108(0x26b,']*Uo')+_0x3a8108(0x70d,'JSoZ')+_0x3a8108(0x81b,'9)b9')+_0x3a8108(0x4ea,'sa(9')+_0x3a8108(0x656,'FFZd')+_0x3a8108(0x2ed,'KN]U'),'hXiDv':function(_0x3003e0,_0x16c82f){return _0x3003e0===_0x16c82f;},'hanCn':function(_0x4b2a2b,_0x2ee8cd){return _0x4b2a2b<=_0x2ee8cd;},'cumzc':function(_0x804480,_0x305292){return _0x804480<=_0x305292;},'gMXof':_0x3a8108(0x6d7,'E*G)')+'Area','gEYtf':_0x3a8108(0x9d6,'E*G)'),'NRfEo':function(_0x3f3424,_0x11d55b){return _0x3f3424+_0x11d55b;},'VPPLg':function(_0x37df48,_0x32384a){return _0x37df48+_0x32384a;},'IcxkE':function(_0x4cb36d,_0x2dce91){return _0x4cb36d+_0x2dce91;},'FqCId':_0x3a8108(0x2eb,'KN]U')+'\x20{\x20si'+_0x3a8108(0x907,'Vabs'),'VrcaL':_0x3a8108(0x30c,'q3H^')+_0x3a8108(0x1ca,'#HYV')+_0x3a8108(0x797,'l&at')},_0x128a2e=_0x431247['hXiDv'](_0x2e6e28,'a4'),_0x303146=_0x128a2e?'A4':_0x431247[_0x3a8108(0x6c5,'KghS')](_0x2e6e28,_0x3a8108(0xade,'eHms')+'to'),_0x4048a9=_0x128a2e?_0x3a8108(0x32a,'IdpO'):_0x3a8108(0x4b3,'1&H^'),_0x36b4d3=_0x128a2e?0xd2:Number(_0x2e6e28),_0x3292ca=_0x431247[_0x3a8108(0x4f5,'V64C')](_0x36b4d3,0x3a)?0xa:_0x431247[_0x3a8108(0xa2f,'xb!o')](_0x36b4d3,0x50)?0xb:_0x36b4d3<=0x6e?0xd:0xc,_0x5c741d=document['getEl'+_0x3a8108(0x9cf,'E*G)')+_0x3a8108(0x9ea,'5Hqz')](_0x431247[_0x3a8108(0x24d,'eHms')]);_0x5c741d[_0x3a8108(0x1ee,'dQtf')+_0x3a8108(0x516,'VMgj')]=_0x431247[_0x3a8108(0x4fc,'Vabs')](buildReceiptHTML,_0x53dd8a);if(!_0x5c741d[_0x3a8108(0x351,'VUa@')+_0x3a8108(0x854,'KghS')][_0x3a8108(0x3f3,'^^3k')]())return showToast('Konte'+_0x3a8108(0x6b4,'*e]A')+_0x3a8108(0x833,'gMHR')+_0x3a8108(0xa01,'a4i]'));let _0x154b3c=document[_0x3a8108(0x92b,'$p9U')+_0x3a8108(0x2fb,'13TQ')+_0x3a8108(0x208,'E*G)')](_0x3a8108(0x5ec,'5Hqz')+_0x3a8108(0x36b,'Z55*')+_0x3a8108(0x839,'a4i]')+'e');!_0x154b3c&&(_0x154b3c=document[_0x3a8108(0xafb,'sa(9')+_0x3a8108(0x334,'l&at')+_0x3a8108(0x9c3,'rDp@')](_0x431247[_0x3a8108(0x76d,'khYj')]),_0x154b3c['id']=_0x3a8108(0x52a,'sa(9')+_0x3a8108(0xab4,'V[]2')+'eStyl'+'e',document[_0x3a8108(0x267,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')]['appen'+'dChil'+'d'](_0x154b3c));_0x154b3c[_0x3a8108(0x33d,'nrxl')+_0x3a8108(0x75f,'eHms')+'t']=_0x431247[_0x3a8108(0x4dc,'xb!o')](_0x431247[_0x3a8108(0x515,'Z55*')](_0x431247['VPPLg'](_0x431247[_0x3a8108(0x61d,'a4i]')](_0x431247[_0x3a8108(0x723,'$p9U')]+_0x303146+(_0x3a8108(0x234,'khYj')+'gin:\x20')+_0x4048a9+_0x3a8108(0x585,'IdpO')+_0x431247[_0x3a8108(0x4ca,'VUa@')]+(_0x3a8108(0x226,'rDp@')+'rint-'+_0x3a8108(0x840,'V[]2')+_0x3a8108(0x75d,'bB4q')+'ipt\x20{'+_0x3a8108(0x645,'&!DG')+_0x3a8108(0x6bd,'IhJl')+':\x20'),_0x3292ca)+(_0x3a8108(0x1e4,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')+_0x3a8108(0x97d,'q3H^')+_0x3a8108(0x3b5,'*e]A')),_0x128a2e?_0x3a8108(0xa51,'1&H^')+_0x3a8108(0x382,'13TQ')+':\x2080m'+_0x3a8108(0x289,'XucK')+_0x3a8108(0x654,'Z55*')+_0x3a8108(0x99d,'13TQ')+_0x3a8108(0x9d8,']4q%'):''),_0x3a8108(0x25c,'PRZ&')),'\x20}');const _0x34e752=()=>{const _0x4fff64=_0x3a8108;window[_0x4fff64(0x5e2,'JSoZ')+_0x4fff64(0x8d1,'Z55*')+_0x4fff64(0x4c7,'&!DG')+_0x4fff64(0xa60,'UbQ2')](_0x4fff64(0xa8e,'!HV9')+_0x4fff64(0x5f5,'9)b9'),_0x34e752),document[_0x4fff64(0x342,'^^3k')+_0x4fff64(0x4b0,'q3H^')+_0x4fff64(0x545,'KN]U')](_0x431247[_0x4fff64(0x388,'V64C')])[_0x4fff64(0x8e9,'zog4')+'List']['conta'+_0x4fff64(0x9f1,'5Hqz')](_0x4fff64(0x814,'gMHR'))&&closePrintModal();};window[_0x3a8108(0x790,'sa(9')+_0x3a8108(0x4dd,'l&at')+_0x3a8108(0x973,']*Uo')+'r']('after'+_0x3a8108(0x902,'UbQ2'),_0x34e752),setTimeout(()=>{const _0x120ad2=_0x3a8108;try{window[_0x120ad2(0xa08,'bB4q')]();}catch(_0x576cbf){_0x431247['lSUiL'](showToast,_0x431247[_0x120ad2(0x8ff,'V[]2')](_0x431247[_0x120ad2(0x5a5,' -/* ============================================================ - STATE - ============================================================ */ -const STORAGE_ITEMS = 'pos_inv_items_v1'; -const STORAGE_SALES = 'pos_inv_sales_v1'; -const STORAGE_RECEIPT_SIZE = 'pos_inv_receipt_size_v1'; - -let items = []; -let sales = []; -let cart = []; -let pendingPrintTx = null; - -try { - items = JSON.parse(localStorage.getItem(STORAGE_ITEMS)) || []; - sales = JSON.parse(localStorage.getItem(STORAGE_SALES)) || []; -} catch (e) { items = []; sales = []; } - -function initSampleData() { - if (items.length === 0) { - items = [ - { id: '1', code: '8991002101111', name: 'Kopi Arabika Botol 250ml', cluster: 'Minuman', qty: 35, buyPrice: 10000, sellPrice: 15000 }, - { id: '2', code: 'MNM-02', name: 'Matcha Latte Kaleng', cluster: 'Minuman', qty: 20, buyPrice: 12000, sellPrice: 18000 }, - { id: '3', code: 'MKN-01', name: 'Croissant Butter', cluster: 'Makanan', qty: 15, buyPrice: 14000, sellPrice: 22000 }, - { id: '4', code: 'SNK-01', name: 'Keripik Kentang Truffle', cluster: 'Snack', qty: 4, buyPrice: 8000, sellPrice: 12000 } - ]; - saveState(); - } -} - -function saveState() { - try { - localStorage.setItem(STORAGE_ITEMS, JSON.stringify(items)); - localStorage.setItem(STORAGE_SALES, JSON.stringify(sales)); - } catch (e) { showToast('Penyimpanan lokal penuh / diblokir'); } -} - -/* ============================================================ - UTILITAS - ============================================================ */ -function formatRp(num) { return 'Rp ' + Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function fmtNum(num) { return Math.round(Number(num) || 0).toLocaleString('id-ID'); } -function esc(str) { - return String(str == null ? '' : str) - .replace(/&/g, '&').replace(//g, '>') - .replace(/"/g, '"').replace(/'/g, '''); -} -let toastTimer = null; -function showToast(msg) { - const t = document.getElementById('toast'); - t.textContent = msg; - t.style.display = 'block'; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { t.style.display = 'none'; }, 2800); -} - -/* ============================================================ - HEADER ROLLING - ============================================================ */ -function initHeaderRolling() { - const inner = document.getElementById('rollingInner'); - if (!inner) return; - const totalUnique = 3; - const stepEm = 1.35; - const displayMs = 4200; - const resetDelayMs = 800; - const transitionCss = 'transform 0.7s cubic-bezier(0.4, 0, 0.2, 1)'; - let idx = 0; - let paused = false; - const container = inner.parentElement; - container.addEventListener('pointerenter', () => { paused = true; }); - container.addEventListener('pointerleave', () => { paused = false; }); - - function tick() { - if (paused) return; - idx++; - inner.style.transform = 'translateY(-' + (idx * stepEm) + 'em)'; - if (idx >= totalUnique) { - setTimeout(() => { - inner.style.transition = 'none'; - inner.style.transform = 'translateY(0)'; - idx = 0; - void inner.offsetHeight; - inner.style.transition = transitionCss; - }, resetDelayMs); - } - } - inner.style.transition = transitionCss; - setInterval(tick, displayMs + 700); -} - -/* ============================================================ - BARCODE SCANNER - ============================================================ */ -let html5QrScanner = null; -let scannerMode = 'POS'; -let scannerRunning = false; -let lastScannedCode = ''; -let lastScannedTime = 0; -let scanSessionCount = 0; -const SCAN_DEBOUNCE_MS = 1800; - -function playBeep(isSuccess) { - try { - const Ctx = window.AudioContext || window.webkitAudioContext; - if (!Ctx) return; - const ctx = new Ctx(); - const osc = ctx.createOscillator(); - const gain = ctx.createGain(); - osc.type = isSuccess === false ? 'sawtooth' : 'sine'; - osc.frequency.value = isSuccess === false ? 320 : 880; - gain.gain.setValueAtTime(0.15, ctx.currentTime); - osc.connect(gain); gain.connect(ctx.destination); - osc.start(); - osc.stop(ctx.currentTime + (isSuccess === false ? 0.22 : 0.12)); - setTimeout(() => { try { ctx.close(); } catch (e) {} }, 500); - } catch (e) {} -} -function vibrate(pattern) { - if (navigator.vibrate) { try { navigator.vibrate(pattern); } catch (e) {} } -} -function showScanFeedback(message, isError) { - const bar = document.getElementById('scanFeedbackBar'); - const txt = document.getElementById('scanFeedbackText'); - if (!bar || !txt) return; - bar.style.display = 'flex'; - bar.classList.toggle('error', !!isError); - txt.textContent = message; -} -function isSecureCameraContext() { - if (window.isSecureContext) return true; - const h = location.hostname; - return location.protocol === 'https:' || - h === 'localhost' || h === '127.0.0.1' || h === '[::1]'; -} -async function requestCameraPermission() { - if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { - throw new Error('Browser tidak mendukung akses kamera.'); - } - try { - const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } }, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err1) { - try { - const s = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); - s.getTracks().forEach(t => t.stop()); - return true; - } catch (err2) { - throw new Error(err2.name + ': ' + (err2.message || 'Izin kamera ditolak')); - } - } -} -async function stopAndClearScanner() { - if (!html5QrScanner) { scannerRunning = false; return; } - const inst = html5QrScanner; - html5QrScanner = null; - scannerRunning = false; - try { if (inst.isScanning) await inst.stop(); } catch (e) {} - try { inst.clear(); } catch (e) {} - const reader = document.getElementById('barcodeReader'); - if (reader) reader.querySelectorAll('video, canvas, img').forEach(el => el.remove()); -} -async function closeScanner() { - const modal = document.getElementById('scannerModal'); - if (modal) modal.classList.remove('open'); - await stopAndClearScanner(); -} -async function openScanner(mode) { - if (typeof Html5Qrcode === 'undefined') return showToast('Library scanner gagal dimuat. Cek koneksi internet.'); - if (!isSecureCameraContext()) return showToast('Kamera memerlukan HTTPS atau localhost.'); - try { await requestCameraPermission(); } - catch (err) { return showToast('Izin kamera gagal: ' + (err.message || err.name)); } - await stopAndClearScanner(); - - scannerMode = mode; - scanSessionCount = 0; - lastScannedCode = ''; - lastScannedTime = 0; - document.getElementById('scanSessionBadge').textContent = '0 discan'; - document.getElementById('scanFeedbackBar').style.display = 'none'; - - const continuousCtrl = document.getElementById('continuousScanControl'); - const chk = document.getElementById('chkContinuousScan'); - if (mode === 'POS') { - continuousCtrl.style.display = 'flex'; - chk.checked = true; - document.getElementById('scannerTitle').textContent = 'Scan Barcode ke Keranjang'; - document.getElementById('scannerHint').textContent = 'Kamera tetap menyala jika Mode Scan Beruntun aktif'; - } else { - continuousCtrl.style.display = 'none'; - chk.checked = false; - document.getElementById('scannerTitle').textContent = 'Scan Barcode Produk'; - document.getElementById('scannerHint').textContent = 'Kode barcode akan mengisi kolom Kode / SKU'; - } - document.getElementById('scannerModal').classList.add('open'); - showScanFeedback('Menyiapkan kamera...', false); - - try { html5QrScanner = new Html5Qrcode('barcodeReader', { verbose: false }); } - catch (e) { return showToast('Gagal membuat scanner: ' + (e.message || e)); } - - const config = { - fps: 10, - qrbox: function (vw, vh) { - const min = Math.min(vw, vh); - const w = Math.floor(min * 0.85); - const h = Math.floor(Math.min(min * 0.45, w * 0.55)); - return { width: w, height: h }; - }, - aspectRatio: 1.3333 - }; - - try { - await html5QrScanner.start({ facingMode: 'environment' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai...', false); - return; - } catch (err1) { - try { - const cameras = await Html5Qrcode.getCameras(); - if (cameras && cameras.length > 0) { - let pick = cameras.find(c => /back|environment|rear|belakang/i.test(c.label)); - if (!pick) pick = cameras[cameras.length - 1]; - await html5QrScanner.start(pick.id, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera siap memindai (fallback)...', false); - return; - } - } catch (err2) {} - try { - await html5QrScanner.start({ facingMode: 'user' }, config, onScanSuccess); - scannerRunning = true; fixVideoStyle(); - showScanFeedback('Kamera depan dipakai (fallback)...', false); - return; - } catch (err3) {} - await stopAndClearScanner(); - document.getElementById('scannerModal').classList.remove('open'); - showToast('Gagal memulai kamera: ' + ((err1 && (err1.message || err1.name)) || 'Tidak diketahui')); - } -} -function fixVideoStyle() { - const reader = document.getElementById('barcodeReader'); - if (!reader) return; - const video = reader.querySelector('video'); - if (video) { - video.style.cssText = [ - 'display:block', 'width:100%', 'height:100%', 'object-fit:cover', - 'position:absolute', 'top:0', 'left:0', 'z-index:1', 'background:#000' - ].join(';'); - const tryPlay = () => { const p = video.play(); if (p && p.catch) p.catch(() => {}); }; - video.addEventListener('loadedmetadata', tryPlay, { once: true }); - tryPlay(); - } - reader.querySelectorAll(':scope > div').forEach(el => { - if (el.classList.contains('scan-frame')) return; - el.style.position = 'absolute'; - el.style.inset = '0'; - el.style.zIndex = '2'; - el.style.pointerEvents = 'none'; - el.style.background = 'transparent'; - }); -} -function onScanSuccess(decodedText) { - const now = Date.now(); - const cleanCode = String(decodedText || '').trim(); - if (!cleanCode) return; - if (cleanCode.toLowerCase() === lastScannedCode.toLowerCase() && - (now - lastScannedTime) < SCAN_DEBOUNCE_MS) return; - lastScannedCode = cleanCode; - lastScannedTime = now; - - if (scannerMode === 'POS') { - const isContinuous = document.getElementById('chkContinuousScan').checked; - const matched = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (matched) { - const added = addToCart(matched.id, true); - if (added) { - playBeep(true); vibrate(40); - scanSessionCount++; - document.getElementById('scanSessionBadge').textContent = scanSessionCount + ' discan'; - const cartItem = cart.find(c => c.id === matched.id); - const qtyInCart = cartItem ? cartItem.qty : 1; - showScanFeedback('✔ ' + matched.name + ' (' + qtyInCart + 'x)', false); - showToast('+1 ' + matched.name); - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Stok "' + matched.name + '" habis / maksimal!', true); - } - } else { - playBeep(false); vibrate([60, 40, 60]); - showScanFeedback('✖ Barcode "' + cleanCode + '" tidak terdaftar!', true); - if (!isContinuous) { - document.getElementById('posSearch').value = cleanCode; - renderPOSItems(); - showToast('Kode "' + cleanCode + '" tidak ditemukan'); - } - } - if (!isContinuous) closeScanner(); - return; - } - - if (scannerMode === 'INV') { - playBeep(true); vibrate(40); - document.getElementById('itemCode').value = cleanCode; - const existing = items.find(i => i.code.toLowerCase() === cleanCode.toLowerCase()); - if (existing) { - editItem(existing.id); - showToast('Kode sudah ada, buka mode edit: ' + existing.name); - } else { - showToast('Barcode terdeteksi: ' + cleanCode); - } - closeScanner(); - } -} - -/* ============================================================ - NAVIGASI TAB - ============================================================ */ -function switchTab(tabId, btn) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - const target = document.getElementById('tab-' + tabId); - if (target) target.classList.add('active'); - if (btn) btn.classList.add('active'); - - if (tabId === 'pos') renderPOSItems(); - if (tabId === 'inv') renderInventory(); - if (tabId === 'margin') renderMarginTab(); - if (tabId === 'report') renderReport(); -} - -/* ============================================================ - CLUSTER - ============================================================ */ -function getUniqueClusters() { - const set = new Set(items.map(i => (i.cluster || 'Umum').trim()).filter(Boolean)); - return Array.from(set).sort(); -} -function syncClusterDropdowns() { - const clusters = getUniqueClusters(); - const posFilter = document.getElementById('posClusterFilter'); - const currentPos = posFilter.value; - posFilter.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentPos)) posFilter.value = currentPos; - - const marginTarget = document.getElementById('marginTarget'); - const currentMargin = marginTarget.value; - marginTarget.innerHTML = '' + - clusters.map(c => '').join(''); - if (clusters.includes(currentMargin)) marginTarget.value = currentMargin; - - document.getElementById('clusterSuggestions').innerHTML = - clusters.map(c => '').join(''); -} - -/* ============================================================ - POS - ============================================================ */ -function renderPOSItems() { - syncClusterDropdowns(); - const query = (document.getElementById('posSearch').value || '').toLowerCase(); - const cluster = document.getElementById('posClusterFilter').value; - const filtered = items.filter(item => { - const matchText = item.name.toLowerCase().includes(query) || item.code.toLowerCase().includes(query); - const matchCluster = cluster === 'ALL' || item.cluster === cluster; - return matchText && matchCluster; - }); - document.getElementById('posItemCount').textContent = filtered.length + ' item'; - const container = document.getElementById('posProductList'); - if (filtered.length === 0) { - container.innerHTML = '

Barang tidak ditemukan

'; - return; - } - container.innerHTML = filtered.map(item => { - const outOfStock = item.qty <= 0; - return '
' + - '
' + - '
' + esc(item.name) + '
' + - '
' + esc(item.cluster) + ' • ' + - 'Kode: ' + esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
' + formatRp(item.sellPrice) + '
' + - '
' + - '' + - '
'; - }).join(''); -} -function addToCart(itemId, silent) { - const item = items.find(i => i.id === itemId); - if (!item || item.qty <= 0) { - if (!silent) showToast('Stok habis!'); - return false; - } - const existing = cart.find(c => c.id === itemId); - if (existing) { - if (existing.qty >= item.qty) { - if (!silent) showToast('Melebihi stok tersedia!'); - return false; - } - existing.qty += 1; - } else { - cart.push({ - id: item.id, code: item.code, name: item.name, cluster: item.cluster, - buyPrice: item.buyPrice, sellPrice: item.sellPrice, qty: 1 - }); - } - renderCart(); - return true; -} -function updateCartQty(itemId, delta) { - const idx = cart.findIndex(c => c.id === itemId); - if (idx === -1) return; - const stockItem = items.find(i => i.id === itemId); - const nextQty = cart[idx].qty + delta; - if (nextQty <= 0) cart.splice(idx, 1); - else if (stockItem && nextQty > stockItem.qty) return showToast('Stok tidak mencukupi'); - else cart[idx].qty = nextQty; - renderCart(); -} -function clearCart() { - cart = []; - document.getElementById('cartDiscount').value = 0; - document.getElementById('cartPaid').value = ''; - renderCart(); -} -function renderCart() { - const container = document.getElementById('cartList'); - if (cart.length === 0) { - container.innerHTML = '

Keranjang masih kosong

'; - } else { - container.innerHTML = cart.map(c => - '
' + - '
' + - '
' + esc(c.name) + '
' + - '
' + formatRp(c.sellPrice) + ' x ' + c.qty + - ' = ' + formatRp(c.sellPrice * c.qty) + '
' + - '
' + - '
' + - '' + - '' + c.qty + '' + - '' + - '
' + - '
' - ).join(''); - } - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const profit = total - totalCost; - const paid = Number(document.getElementById('cartPaid').value) || 0; - const change = Math.max(0, paid - total); - document.getElementById('summarySubtotal').textContent = formatRp(subtotal); - document.getElementById('summaryProfit').textContent = formatRp(profit); - document.getElementById('summaryTotal').textContent = formatRp(total); - document.getElementById('summaryChange').textContent = formatRp(change); -} -function checkout() { - if (cart.length === 0) return showToast('Pilih barang terlebih dahulu'); - const subtotal = cart.reduce((s, c) => s + c.sellPrice * c.qty, 0); - const totalCost = cart.reduce((s, c) => s + c.buyPrice * c.qty, 0); - const discount = Math.max(0, Number(document.getElementById('cartDiscount').value) || 0); - const total = Math.max(0, subtotal - discount); - const paid = Number(document.getElementById('cartPaid').value) || total; - if (paid < total) return showToast('Uang bayar kurang dari total!'); - - cart.forEach(c => { - const stockItem = items.find(i => i.id === c.id); - if (stockItem) stockItem.qty = Math.max(0, stockItem.qty - c.qty); - }); - - const now = new Date(); - const tx = { - id: 'TRX-' + now.getTime(), - timestamp: now.toISOString(), - dateStr: now.toISOString().split('T')[0], - items: JSON.parse(JSON.stringify(cart)), - totalQty: cart.reduce((s, c) => s + c.qty, 0), - subtotal, discount, total, paid, - change: paid - total, - cost: totalCost, - profit: total - totalCost - }; - sales.unshift(tx); - saveState(); - clearCart(); - renderPOSItems(); - openPrintModal(tx); - showToast('Transaksi berhasil disimpan!'); -} - -/* ============================================================ - INVENTORY - ============================================================ */ -function previewItemMargin() { - const buy = Number(document.getElementById('itemBuy').value) || 0; - const sell = Number(document.getElementById('itemSell').value) || 0; - const diff = sell - buy; - const pct = buy > 0 ? ((diff / buy) * 100).toFixed(1) : '0'; - document.getElementById('itemMarginPreview').textContent = - 'Margin: ' + formatRp(diff) + ' (' + pct + '%)'; -} -function saveItem() { - const id = document.getElementById('editItemId').value; - const code = document.getElementById('itemCode').value.trim() || ('SKU-' + Date.now().toString().slice(-5)); - const cluster = document.getElementById('itemCluster').value.trim() || 'Umum'; - const name = document.getElementById('itemName').value.trim(); - const qty = Math.max(0, Number(document.getElementById('itemQty').value) || 0); - const buyPrice = Math.max(0, Number(document.getElementById('itemBuy').value) || 0); - const sellPrice = Math.max(0, Number(document.getElementById('itemSell').value) || 0); - if (!name) return showToast('Nama item wajib diisi!'); - if (id) { - const idx = items.findIndex(i => i.id === id); - if (idx !== -1) { - items[idx] = { id, code, cluster, name, qty, buyPrice, sellPrice }; - showToast('Item diperbarui'); - } - } else { - items.push({ id: String(Date.now()), code, cluster, name, qty, buyPrice, sellPrice }); - showToast('Item baru ditambahkan'); - } - saveState(); - resetItemForm(); - renderInventory(); - syncClusterDropdowns(); -} -function editItem(id) { - const item = items.find(i => i.id === id); - if (!item) return; - document.getElementById('formTitle').textContent = 'Edit Item: ' + item.code; - document.getElementById('editItemId').value = item.id; - document.getElementById('itemCode').value = item.code; - document.getElementById('itemCluster').value = item.cluster; - document.getElementById('itemName').value = item.name; - document.getElementById('itemQty').value = item.qty; - document.getElementById('itemBuy').value = item.buyPrice; - document.getElementById('itemSell').value = item.sellPrice; - previewItemMargin(); - const invTab = document.getElementById('tab-inv'); - if (!invTab.classList.contains('active')) { - document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active')); - document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active')); - invTab.classList.add('active'); - document.querySelectorAll('.nav-btn')[1].classList.add('active'); - renderInventory(); - } - window.scrollTo({ top: 0, behavior: 'smooth' }); -} -function deleteItem(id) { - if (!confirm('Hapus item ini dari inventory?')) return; - items = items.filter(i => i.id !== id); - saveState(); - renderInventory(); - syncClusterDropdowns(); - showToast('Item dihapus'); -} -function resetItemForm() { - document.getElementById('formTitle').textContent = 'Tambah / Edit Item'; - document.getElementById('editItemId').value = ''; - document.getElementById('itemCode').value = ''; - document.getElementById('itemCluster').value = ''; - document.getElementById('itemName').value = ''; - document.getElementById('itemQty').value = ''; - document.getElementById('itemBuy').value = ''; - document.getElementById('itemSell').value = ''; - previewItemMargin(); -} -function renderInventory() { - const q = (document.getElementById('invSearch').value || '').toLowerCase(); - const filtered = items.filter(i => - i.name.toLowerCase().includes(q) || - i.code.toLowerCase().includes(q) || - (i.cluster || '').toLowerCase().includes(q) - ); - const container = document.getElementById('inventoryList'); - if (filtered.length === 0) { - container.innerHTML = '

Belum ada data barang

'; - return; - } - container.innerHTML = filtered.map(item => { - const marginVal = item.sellPrice - item.buyPrice; - const marginPct = item.buyPrice > 0 ? ((marginVal / item.buyPrice) * 100).toFixed(1) : '0'; - const lowBadge = item.qty <= 5 ? ' Stok Menipis' : ''; - return '
' + - '
' + - '
' + esc(item.name) + lowBadge + '
' + - '
' + esc(item.cluster) + ' • ' + - esc(item.code) + ' • Stok: ' + item.qty + '
' + - '
Beli: ' + formatRp(item.buyPrice) + - ' | Jual: ' + formatRp(item.sellPrice) + '
' + - '
' + - 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)
' + - '
' + - '
' + - '' + - '' + - '
' + - '
'; - }).join(''); -} - -/* ============================================================ - IMPORT CSV - ============================================================ */ -function parseCSVLine(line, delimiter) { - const result = []; let current = ''; let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const char = line[i]; - if (char === '"') { - if (inQuotes && line[i + 1] === '"') { current += '"'; i++; } - else inQuotes = !inQuotes; - } else if (char === delimiter && !inQuotes) { - result.push(current.trim()); current = ''; - } else current += char; - } - result.push(current.trim()); - return result; -} -function cleanNumber(val) { - if (!val) return 0; - let s = String(val).replace(/[^0-9.,-]/g, ''); - if (s.indexOf(',') > -1 && s.indexOf('.') > -1) s = s.replace(/\./g, '').replace(',', '.'); - else if (s.indexOf(',') > -1) { - const parts = s.split(','); - if (parts.length === 2 && parts[1].length <= 2) s = parts[0] + '.' + parts[1]; - else s = s.replace(/,/g, ''); - } - const n = Number(s); - return Math.max(0, isNaN(n) ? 0 : n); -} -function downloadTemplateCSV() { - const headers = ['Kode_Item', 'Nama_Item', 'Cluster', 'Jumlah_Stok', 'Harga_Beli', 'Harga_Jual']; - const samples = [ - ['MNM-10', 'Teh Tarik Botol 300ml', 'Minuman', 25, 7000, 12000], - ['MKN-10', 'Roti Bakar Cokelat', 'Makanan', 15, 9000, 16000] - ]; - downloadCSV('template_import_inventory.csv', [headers].concat(samples)); -} -function importInventoryCSV() { - const fileInput = document.getElementById('csvFileInput'); - const mode = document.getElementById('csvImportMode').value; - if (!fileInput.files || fileInput.files.length === 0) { - return showToast('Pilih file CSV terlebih dahulu!'); - } - const file = fileInput.files[0]; - const reader = new FileReader(); - reader.onload = function (e) { - try { - const text = String(e.target.result).replace(/^\uFEFF/, ''); - const lines = text.split(/\r?\n/).filter(l => l.trim() !== ''); - if (lines.length < 2) return showToast('File CSV kosong atau tidak memiliki baris data!'); - const semis = (lines[0].match(/;/g) || []).length; - const commas = (lines[0].match(/,/g) || []).length; - const delimiter = semis > commas ? ';' : ','; - const headers = parseCSVLine(lines[0], delimiter).map(h => h.toLowerCase().replace(/[^a-z0-9]/g, '')); - const idxCode = headers.findIndex(h => ['kodeitem','kode','sku','code','id','barcode'].includes(h)); - const idxName = headers.findIndex(h => ['namaitem','nama','name','barang','produk','item'].includes(h)); - const idxCluster = headers.findIndex(h => ['cluster','kategori','category','grup','group'].includes(h)); - const idxQty = headers.findIndex(h => ['jumlahstok','stok','qty','jumlah','stock','quantity'].includes(h)); - const idxBuy = headers.findIndex(h => ['hargabeli','beli','modal','buyprice','cost','hargapokok'].includes(h)); - const idxSell = headers.findIndex(h => ['hargajual','jual','harga','sellprice','price'].includes(h)); - if (idxName === -1) return showToast('Kolom Nama_Item tidak ditemukan pada header CSV!'); - const parsedRows = []; - for (let i = 1; i < lines.length; i++) { - const cols = parseCSVLine(lines[i], delimiter); - const name = (cols[idxName] || '').trim(); - if (!name) continue; - const code = (idxCode !== -1 && cols[idxCode]) ? cols[idxCode].trim() - : ('IMP-' + Date.now().toString().slice(-4) + '-' + i); - const cluster = (idxCluster !== -1 && cols[idxCluster]) ? cols[idxCluster].trim() || 'Umum' : 'Umum'; - parsedRows.push({ - code, name, cluster, - qty: idxQty !== -1 ? cleanNumber(cols[idxQty]) : 0, - buyPrice: idxBuy !== -1 ? cleanNumber(cols[idxBuy]) : 0, - sellPrice: idxSell !== -1 ? cleanNumber(cols[idxSell]) : 0 - }); - } - if (parsedRows.length === 0) return showToast('Tidak ada baris data valid untuk diimpor.'); - if (mode === 'REPLACE_ALL') { - if (!confirm('Ganti seluruh inventory saat ini dengan ' + parsedRows.length + ' item dari CSV?')) return; - items = parsedRows.map((r, idx) => Object.assign({ id: String(Date.now() + idx) }, r)); - } else { - parsedRows.forEach((r, idx) => { - const existing = items.find(it => - it.code.toLowerCase() === r.code.toLowerCase() || - it.name.toLowerCase() === r.name.toLowerCase() - ); - if (existing) { - existing.code = r.code; existing.name = r.name; existing.cluster = r.cluster; - existing.buyPrice = r.buyPrice; existing.sellPrice = r.sellPrice; - existing.qty = mode === 'UPSERT_ADD_STOCK' ? (existing.qty + r.qty) : r.qty; - } else { - items.push(Object.assign({ id: String(Date.now() + idx) }, r)); - } - }); - } - saveState(); - renderInventory(); - syncClusterDropdowns(); - renderPOSItems(); - fileInput.value = ''; - showToast('Berhasil mengimpor ' + parsedRows.length + ' item dari CSV!'); - } catch (err) { - showToast('Gagal memproses file CSV!'); - } - }; - reader.onerror = function () { showToast('Gagal membaca file CSV!'); }; - reader.readAsText(file, 'UTF-8'); -} - -/* ============================================================ - MARGIN MASSAL - ============================================================ */ -function renderMarginTab() { - syncClusterDropdowns(); - const totalCost = items.reduce((s, i) => s + i.buyPrice * i.qty, 0); - const totalRev = items.reduce((s, i) => s + i.sellPrice * i.qty, 0); - document.getElementById('valTotalCost').textContent = formatRp(totalCost); - document.getElementById('valTotalRev').textContent = formatRp(totalRev); -} -function applyBulkMargin() { - const target = document.getElementById('marginTarget').value; - const type = document.getElementById('marginType').value; - const amount = Number(document.getElementById('marginAmount').value); - const roundTo = Number(document.getElementById('marginRounding').value) || 1; - if (isNaN(amount) || amount < 0) return showToast('Masukkan nilai margin yang valid'); - let updatedCount = 0; - items.forEach(item => { - if (target === 'ALL' || item.cluster === target) { - let rawSell; - if (type === 'PERCENT') rawSell = item.buyPrice + (item.buyPrice * (amount / 100)); - else rawSell = item.buyPrice + amount; - item.sellPrice = Math.round(rawSell / roundTo) * roundTo; - updatedCount++; - } - }); - saveState(); - renderMarginTab(); - renderPOSItems(); - renderInventory(); - showToast('Harga jual ' + updatedCount + ' item diperbarui!'); -} - -/* ============================================================ - LAPORAN & EXPORT CSV - ============================================================ */ -function setReportToday() { - const today = new Date().toISOString().split('T')[0]; - document.getElementById('repStartDate').value = today; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function setReportMonth() { - const now = new Date(); - const firstDay = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().split('T')[0]; - const today = now.toISOString().split('T')[0]; - document.getElementById('repStartDate').value = firstDay; - document.getElementById('repEndDate').value = today; - renderReport(); -} -function getFilteredSales() { - const start = document.getElementById('repStartDate').value; - const end = document.getElementById('repEndDate').value; - return sales.filter(tx => { - if (start && tx.dateStr < start) return false; - if (end && tx.dateStr > end) return false; - return true; - }); -} -function renderReport() { - const filtered = getFilteredSales(); - const txCount = filtered.length; - const itemsSold = filtered.reduce((s, t) => s + t.totalQty, 0); - const revenue = filtered.reduce((s, t) => s + t.total, 0); - const profit = filtered.reduce((s, t) => s + t.profit, 0); - document.getElementById('repTxCount').textContent = txCount; - document.getElementById('repItemsSold').textContent = itemsSold; - document.getElementById('repRevenue').textContent = formatRp(revenue); - document.getElementById('repProfit').textContent = formatRp(profit); - - const list = document.getElementById('salesHistoryList'); - if (filtered.length === 0) { - list.innerHTML = '

Tidak ada transaksi pada periode ini

'; - return; - } - list.innerHTML = filtered.map(tx => { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID'); - const rincian = tx.items.map(i => esc(i.name) + ' (' + i.qty + 'x)').join(', '); - return '
' + - '
' + - '
' + esc(tx.id) + '
' + - '
' + waktu + '
' + - '
' + rincian + '
' + - '
' + - '
' + - '
' + formatRp(tx.total) + '
' + - '
+' + formatRp(tx.profit) + '
' + - '' + - '
' + - '
'; - }).join(''); -} -function getTimestampFilename(prefix) { - const now = new Date(); - const pad = n => String(n).padStart(2, '0'); - return prefix + '_' + now.getFullYear() + pad(now.getMonth() + 1) + pad(now.getDate()) + - '_' + pad(now.getHours()) + pad(now.getMinutes()) + pad(now.getSeconds()) + '.csv'; -} -function downloadCSV(filename, rows) { - const csvContent = rows.map(row => - row.map(cell => '"' + String(cell == null ? '' : cell).replace(/"/g, '""') + '"').join(',') - ).join('\r\n'); - const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' }); - const url = URL.createObjectURL(blob); - const link = document.createElement('a'); - link.href = url; - link.setAttribute('download', filename); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - setTimeout(() => URL.revokeObjectURL(url), 1500); - showToast('File diunduh: ' + filename); -} -function exportInventoryCSV() { - if (items.length === 0) return showToast('Belum ada data inventory'); - const headers = ['Kode_Item','Nama_Item','Cluster','Jumlah_Stok','Harga_Beli','Harga_Jual','Margin_Rp','Margin_Persen','Total_Valuasi_Modal']; - const rows = items.map(i => { - const mRp = i.sellPrice - i.buyPrice; - const mPct = i.buyPrice > 0 ? ((mRp / i.buyPrice) * 100).toFixed(2) : '0'; - return [i.code, i.name, i.cluster, i.qty, i.buyPrice, i.sellPrice, mRp, mPct + '%', i.buyPrice * i.qty]; - }); - downloadCSV(getTimestampFilename('inventory_stok'), [headers].concat(rows)); -} -function exportSalesCSV() { - const filtered = getFilteredSales(); - if (filtered.length === 0) return showToast('Tidak ada transaksi pada periode ini'); - const headers = ['ID_Transaksi','Waktu','Detail_Item','Total_Qty','Subtotal','Diskon','Total_Bayar','Total_Modal','Laba_Bersih']; - const rows = filtered.map(tx => [ - tx.id, - new Date(tx.timestamp).toLocaleString('id-ID'), - tx.items.map(i => i.name + ' (' + i.qty + 'x @' + i.sellPrice + ')').join('; '), - tx.totalQty, tx.subtotal, tx.discount, tx.total, tx.cost, tx.profit - ]); - downloadCSV(getTimestampFilename('laporan_pos'), [headers].concat(rows)); -} -function resetDemoData() { - if (!confirm('Reset semua data ke contoh awal?')) return; - localStorage.removeItem(STORAGE_ITEMS); - localStorage.removeItem(STORAGE_SALES); - items = []; sales = []; cart = []; - initSampleData(); - renderPOSItems(); - renderInventory(); - renderMarginTab(); - renderReport(); - syncClusterDropdowns(); - showToast('Data contoh berhasil dimuat'); -} - -/* ============================================================ - CETAK STRUK - ============================================================ */ -function openPrintModal(tx) { - if (!tx) return; - pendingPrintTx = tx; - document.getElementById('printTotalBadge').textContent = formatRp(tx.total); - - const savedSize = localStorage.getItem(STORAGE_RECEIPT_SIZE) || '58'; - const standardSizes = ['58', '76', '80', '110', 'a4']; - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - - if (standardSizes.includes(savedSize)) { - select.value = savedSize; - customInput.style.display = 'none'; - customInput.value = ''; - } else { - select.value = 'custom'; - customInput.style.display = 'block'; - customInput.value = savedSize; - } - document.getElementById('printModal').classList.add('open'); -} - -function closePrintModal() { - document.getElementById('printModal').classList.remove('open'); - pendingPrintTx = null; -} - -function findAndPrint(txId) { - const tx = sales.find(s => s.id === txId); - if (!tx) return showToast('Transaksi tidak ditemukan'); - openPrintModal(tx); -} - -function toggleCustomSize() { - const select = document.getElementById('printSizeSelect'); - const customInput = document.getElementById('customSizeInput'); - customInput.style.display = select.value === 'custom' ? 'block' : 'none'; -} - -function printCurrentReceipt() { - if (!pendingPrintTx) return showToast('Tidak ada transaksi untuk dicetak'); - let size = document.getElementById('printSizeSelect').value; - if (size === 'custom') { - const custom = Number(document.getElementById('customSizeInput').value); - if (!custom || custom < 30 || custom > 500) { - return showToast('Ukuran custom tidak valid (30–500 mm)'); - } - size = String(custom); - } - try { localStorage.setItem(STORAGE_RECEIPT_SIZE, size); } catch (e) {} - printReceipt(pendingPrintTx, size); -} - -function buildReceiptHTML(tx) { - const waktu = new Date(tx.timestamp).toLocaleString('id-ID', { - day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }); - - const paid = Number(tx.paid) || Number(tx.total) || 0; - const change = Number(tx.change != null ? tx.change : (paid - tx.total)) || 0; - const hasDiscount = Number(tx.discount) > 0; - - const itemsHTML = tx.items.map(i => { - const lineTotal = i.sellPrice * i.qty; - return '' + - '' + - '' + esc(i.name) + '' + - '' + - '' + - '' + i.qty + ' x ' + fmtNum(i.sellPrice) + '' + - '' + fmtNum(lineTotal) + '' + - ''; - }).join(''); - - return '' + - '
' + - '
TOKO DAMAR TUJUH
' + - '
Pekayon, Bekasi Selatan
' + - '
' + - '
No' + esc(tx.id) + '
' + - '
Tgl' + waktu + '
' + - '
' + - '' + itemsHTML + '
' + - '
' + - '
Subtotal' + fmtNum(tx.subtotal) + '
' + - (hasDiscount - ? '
Diskon-' + fmtNum(tx.discount) + '
' - : '') + - '
TOTAL' + fmtNum(tx.total) + '
' + - '
Bayar' + fmtNum(paid) + '
' + - '
Kembali' + fmtNum(change) + '
' + - '
' + - '
Terima kasih atas kunjungan Anda
' + - '
Galaxy Production
' + - '
lynk.id/readthefuture
' + - '
'; -} - -function printReceipt(tx, size) { - const isA4 = size === 'a4'; - const paperSize = isA4 ? 'A4' : (size + 'mm auto'); - const marginSize = isA4 ? '12mm' : '2mm'; - const sizeNum = isA4 ? 210 : Number(size); - const fontSize = sizeNum <= 58 ? 10 : (sizeNum <= 80 ? 11 : (sizeNum <= 110 ? 13 : 12)); - - // Isi area cetak (yang berada di luar .app-shell) - const printArea = document.getElementById('printArea'); - printArea.innerHTML = buildReceiptHTML(tx); - - if (!printArea.innerHTML.trim()) { - return showToast('Konten struk kosong'); - } - - // Suntik @page & ukuran font dinamis - let styleEl = document.getElementById('dynamicPageStyle'); - if (!styleEl) { - styleEl = document.createElement('style'); - styleEl.id = 'dynamicPageStyle'; - document.head.appendChild(styleEl); - } - styleEl.textContent = - '@page { size: ' + paperSize + '; margin: ' + marginSize + '; }' + - ' @media print {' + - ' .print-area .receipt { font-size: ' + fontSize + 'px !important;' + - (isA4 ? ' max-width: 80mm; margin: 0 auto;' : '') + - ' }' + - ' }'; - - const onAfter = () => { - window.removeEventListener('afterprint', onAfter); - if (document.getElementById('printModal').classList.contains('open')) { - closePrintModal(); - } - }; - window.addEventListener('afterprint', onAfter); - - setTimeout(() => { - try { window.print(); } - catch (e) { showToast('Gagal membuka dialog cetak: ' + e.message); } - }, 150); -} - -/* ============================================================ - INISIALISASI - ============================================================ */ -document.addEventListener('DOMContentLoaded', function () { - initSampleData(); - syncClusterDropdowns(); - setReportMonth(); - renderPOSItems(); - renderCart(); - previewItemMargin(); - initHeaderRolling(); - - document.addEventListener('visibilitychange', function () { - if (document.hidden && scannerRunning) closeScanner(); - }); -}); -Lz')],_0x576cbf[_0x120ad2(0x87c,'V[]2')+'ge']));}},0x96);}document[_0xadf508(0x623,'l&at')+_0xadf508(0x5fb,'FFZd')+_0xadf508(0x8de,'^^3k')+'r'](_0xadf508(0x345,'nrxl')+_0xadf508(0x5f3,'*e]A')+_0xadf508(0x450,'VUa@')+'d',function(){const _0x29b48e=_0xadf508,_0x44e829={'Trwzt':function(_0x3dfaee){return _0x3dfaee();},'wtFMj':function(_0x125209){return _0x125209();},'CteDm':function(_0x2ce55b){return _0x2ce55b();},'sxcXh':_0x29b48e(0x7e9,'UbQ2')+_0x29b48e(0x40a,'nrxl')+_0x29b48e(0x1d7,'nrxl')+'e'};_0x44e829[_0x29b48e(0x707,'9)b9')](initSampleData),syncClusterDropdowns(),setReportMonth(),renderPOSItems(),renderCart(),_0x44e829[_0x29b48e(0x50f,'!HV9')](previewItemMargin),initHeaderRolling(),document[_0x29b48e(0xaa3,')cQA')+'entLi'+_0x29b48e(0x4cf,'*e]A')+'r'](_0x44e829[_0x29b48e(0xb62,'KN]U')],function(){const _0x324c2c=_0x29b48e;if(document[_0x324c2c(0xaae,'VMgj')+'n']&&scannerRunning)_0x44e829['Trwzt'](closeScanner);});}); - - - \ No newline at end of file