','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 + '
' +
- '
' +
- '
' +
- '
' +
- '
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 + '
' +
- '
' +
- '
' +
- '
' +
- '
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 + '
' +
- '
' +
- '
' +
- '
' +
- '
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 + '
' +
- '
' +
- '
' +
- '
' +
- '
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 + '
' +
- '
' +
- '
' +
- '
' +
- '
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 + '
' +
- '
' +
- '
' +
- '
' +
- '
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 + '
' +
- '
' +
- '
' +
- '
' +
- '
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 + '
' +
- '
' +
- '
' +
- '
' +
- '
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 + '
' +
- '
' +
- '
' +
- '
' +
- '
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 = '')+(_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 + '
' +
- '
' +
- '
' +
- '
' +
- '
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 + '
' +
- '
' +
- '
' +
- '
' +
- '
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 + '
' +
- '
' +
- '
' +
- '
' +
- '
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 + '
' +
- '
' +
- '
' +
- '
' +
- '
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'+_0xdce72a(0x294,'UbQ2')+_0xdce72a(0xb59,'khYj')+'>','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 + '
' +
- '
' +
- '
' +
- '
' +
- '
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 + '
' +
- '
' +
- '
' +
- '
' +
- '
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 + '
' +
- '
' +
- '
' +
- '
' +
- '
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 + '
' +
- '
' +
- '
' +
- '
' +
- '
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'+_0xdce72a(0x815,'rDp@')+'
')+_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 + '
' +
- '
' +
- '
' +
- '
' +
- '
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 + '
' +
- '
' +
- '
' +
- '
' +
- '
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 + '
' +
- '
' +
- '
' +
- '
' +
- '
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 + '
' +
- '
' +
- '
' +
- '
' +
- '
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