Spaces:
Running
Running
Delete posv1_bak2.html
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810<!DOCTYPE html><html lang="id"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /><meta name="theme-color" content="#2563eb" /><title>Smart POS & Inventory System</title><script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script><style> :root { --primary: #2563eb; --primary-dark: #1d4ed8; --bg: #f1f5f9; --card: #ffffff; --text: #0f172a; --muted: #64748b; --border: #e2e8f0; --success: #16a34a; --danger: #dc2626; --warning: #d97706; }
* { box-sizing: border-box; margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; -webkit-tap-highlight-color: transparent; }
body { background-color: #cbd5e1; color: var(--text); display: flex; justify-content: center; min-height: 100vh; }
.app-shell { width: 100%; max-width: 480px; background-color: var(--bg); min-height: 100vh; display: flex; flex-direction: column; box-shadow: 0 0 25px rgba(0, 0, 0, 0.12); position: relative; padding-bottom: 74px; }
header { background: linear-gradient(135deg, var(--primary), var(--primary-dark)); color: #fff; padding: 16px; position: sticky; top: 0; z-index: 20; } header h1 { font-size: 1.15rem; font-weight: 700; }
.rolling-container { height: 1.35em; overflow: hidden; position: relative; font-size: 0.78rem; opacity: 0.92; margin-top: 4px; user-select: none; -webkit-user-select: none; } .rolling-inner { display: flex; flex-direction: column; transition: transform 0.7s cubic-bezier(0.4, 0, 0.2, 1); will-change: transform; } .rolling-item { height: 1.35em; line-height: 1.35em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .rolling-item a { color: #fff; text-decoration: underline; font-weight: 600; text-decoration-thickness: 1px; text-underline-offset: 2px; }
main { padding: 14px; flex: 1; } .tab-content { display: none; } .tab-content.active { display: block; }
.card { background: var(--card); border-radius: 12px; padding: 14px; margin-bottom: 12px; border: 1px solid var(--border); box-shadow: 0 1px 3px rgba(0,0,0,0.04); } .card-title { font-size: 0.95rem; font-weight: 700; margin-bottom: 10px; color: var(--text); display: flex; justify-content: space-between; align-items: center; gap: 6px; flex-wrap: wrap; } .form-group { margin-bottom: 10px; } label { display: block; font-size: 0.78rem; font-weight: 600; color: var(--muted); margin-bottom: 4px; } input, select { width: 100%; padding: 10px 12px; border: 1px solid var(--border); border-radius: 8px; font-size: 0.9rem; background: #fff; color: var(--text); } input[type="file"] { padding: 8px; font-size: 0.82rem; } input[type="checkbox"] { width: auto; accent-color: var(--primary); } input:focus, select:focus { outline: none; border-color: var(--primary); }
.grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; } .input-with-btn { display: flex; gap: 6px; } .input-with-btn input { flex: 1; }
.btn { width: 100%; padding: 11px; border: none; border-radius: 8px; font-size: 0.9rem; font-weight: 600; cursor: pointer; transition: 0.15s; } .btn-primary { background: var(--primary); color: #fff; } .btn-primary:active { background: var(--primary-dark); } .btn-success { background: var(--success); color: #fff; } .btn-warning { background: var(--warning); color: #fff; } .btn-danger { background: var(--danger); color: #fff; } .btn-dark { background: #1e293b; color: #fff; } .btn-outline { background: #fff; color: var(--primary); border: 1px solid var(--primary); } .btn-sm { padding: 6px 10px; font-size: 0.78rem; width: auto; white-space: nowrap; } .btn:disabled { opacity: 0.5; cursor: not-allowed; }
.item-row { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; border-bottom: 1px solid var(--border); gap: 8px; } .item-row:last-child { border-bottom: none; }
.badge { display: inline-block; padding: 2px 7px; font-size: 0.7rem; font-weight: 600; border-radius: 999px; background: #e0e7ff; color: var(--primary-dark); } .badge-low { background: #fee2e2; color: var(--danger); } .badge-scan { background: #dcfce7; color: #15803d; }
.muted { color: var(--muted); font-size: 0.78rem; } .price-tag { font-weight: 700; color: var(--primary-dark); font-size: 0.92rem; } .empty-state { text-align: center; color: var(--muted); font-size: 0.82rem; padding: 14px 0; } .import-box { background: #f8fafc; border: 1px dashed #94a3b8; border-radius: 10px; padding: 10px; margin-bottom: 10px; } .cart-summary { background: #eff6ff; border: 1px solid #bfdbfe; border-radius: 10px; padding: 12px; margin-top: 10px; } .summary-line { display: flex; justify-content: space-between; font-size: 0.85rem; margin-bottom: 4px; } .summary-total { font-size: 1.05rem; font-weight: 800; color: var(--primary-dark); border-top: 1px dashed #93c5fd; padding-top: 6px; margin-top: 6px; } .stat-box { background: #f8fafc; border: 1px solid var(--border); border-radius: 10px; padding: 10px; text-align: center; } .stat-val { font-size: 1rem; font-weight: 800; color: var(--text); margin-top: 2px; }
.bottom-nav { position: fixed; bottom: 0; width: 100%; max-width: 480px; background: #ffffff; border-top: 1px solid var(--border); display: grid; grid-template-columns: repeat(4, 1fr); z-index: 30; } .nav-btn { background: none; border: none; padding: 10px 4px; font-size: 0.72rem; font-weight: 600; color: var(--muted); cursor: pointer; display: flex; flex-direction: column; align-items: center; gap: 3px; } .nav-btn.active { color: var(--primary); background: #eff6ff; } .nav-icon { font-size: 1.15rem; }
.toast { position: fixed; top: 72px; left: 50%; transform: translateX(-50%); background: #1e293b; color: #fff; padding: 8px 16px; border-radius: 999px; font-size: 0.8rem; z-index: 60; display: none; box-shadow: 0 4px 12px rgba(0,0,0,0.2); white-space: nowrap; max-width: 92vw; overflow: hidden; text-overflow: ellipsis; }
.scanner-modal { position: fixed; inset: 0; background: rgba(15, 23, 42, 0.92); z-index: 50; display: none; justify-content: center; align-items: center; padding: 16px; } .scanner-modal.open { display: flex; } .scanner-box { background: #fff; width: 100%; max-width: 420px; border-radius: 16px; padding: 16px; box-shadow: 0 10px 30px rgba(0,0,0,0.3); max-height: 96vh; overflow-y: auto; }
#barcodeReader { width: 100%; min-height: 260px; border-radius: 10px; overflow: hidden; position: relative; background: #0f172a; margin: 10px 0; border: 1px solid var(--border); } #barcodeReader video { display: block !important; width: 100% !important; height: 100% !important; object-fit: cover !important; position: absolute !important; top: 0; left: 0; z-index: 1; background: #000; } #barcodeReader > div { position: absolute !important; inset: 0; z-index: 2; pointer-events: none; } #barcodeReader canvas { display: none !important; }
.scan-frame { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 78%; height: 42%; border: 2px solid #22c55e; border-radius: 8px; box-shadow: 0 0 0 9999px rgba(15, 23, 42, 0.35); z-index: 3; pointer-events: none; } .scan-frame::before, .scan-frame::after { content: ''; position: absolute; width: 22px; height: 22px; border: 3px solid #22c55e; } .scan-frame::before { top: -3px; left: -3px; border-right: none; border-bottom: none; border-top-left-radius: 6px; } .scan-frame::after { bottom: -3px; right: -3px; border-left: none; border-top: none; border-bottom-right-radius: 6px; }
.continuous-toggle { display: flex; align-items: center; justify-content: space-between; background: #f1f5f9; padding: 9px 12px; border-radius: 8px; margin-bottom: 8px; border: 1px solid var(--border); } .continuous-toggle label { margin: 0; color: var(--text); font-size: 0.82rem; display: flex; align-items: center; gap: 8px; cursor: pointer; font-weight: 600; }
.scan-feedback-bar { background: #ecfdf5; border: 1px solid #a7f3d0; color: #065f46; border-radius: 8px; padding: 8px 10px; font-size: 0.8rem; margin-bottom: 10px; display: none; justify-content: space-between; align-items: center; font-weight: 600; gap: 8px; } .scan-feedback-bar.error { background: #fef2f2; border-color: #fecaca; color: #991b1b; }
.divider { height: 1px; background: var(--border); margin: 12px 0; } .hint-text { font-size: 0.72rem; color: var(--muted); line-height: 1.45; } code { background: #f1f5f9; padding: 1px 4px; border-radius: 3px; font-size: 0.85em; }
/* ============================================================ PRINT / STRUK — versi perbaikan ============================================================ */ .print-area { display: none; }
@media print { html, body { margin: 0 !important; padding: 0 !important; background: #fff !important; color: #000 !important; display: block !important; width: 100% !important; min-height: auto !important; box-shadow: none !important; }
/* Sembunyikan semua anak langsung body kecuali area cetak */ body > *:not(.print-area) { display: none !important; }
.print-area { display: block !important; visibility: visible !important; width: 100% !important; margin: 0 !important; padding: 0 !important; background: #fff !important; color: #000 !important; }
.print-area .receipt { font-family: 'Courier New', 'Courier', 'Lucida Console', monospace !important; color: #000 !important; font-size: 11px; line-height: 1.35; padding: 0; margin: 0; width: 100%; display: block !important; }
.print-area .r-center { text-align: center; } .print-area .r-bold { font-weight: 700; } .print-area .r-mt { margin-top: 4px; }
.print-area .r-line { display: flex; justify-content: space-between; gap: 4px; } .print-area .r-line > span:first-child { white-space: nowrap; } .print-area .r-line > span:last-child { text-align: right; }
.print-area .r-divider { border: none; border-top: 1px dashed #000; margin: 4px 0; height: 0; }
.print-area .r-items { width: 100%; border-collapse: collapse; } .print-area .r-items td { padding: 0; vertical-align: top; } .print-area .r-items td.r-item-name { font-weight: 600; padding-top: 3px; } .print-area .r-items td.r-item-detail { padding-bottom: 2px; }
.print-area .r-total { display: flex; justify-content: space-between; font-weight: 700; font-size: 1.15em; margin: 2px 0; } }</style></head><body>
<div class="app-shell"> <header> <h1>Kasir & Stok Mobile</h1> <div class="rolling-container" aria-live="off"> <div class="rolling-inner" id="rollingInner"> <div class="rolling-item">Sistem POS, Barcode Scanner & Import/Export CSV</div> <div class="rolling-item"> <a href="https://lynk.id/readthefuture" target="_blank" rel="noopener noreferrer">Galaxy Production</a> </div> <div class="rolling-item">Toko Damar Tujuh - Pekayon Bekasi Selatan</div> <div class="rolling-item">Sistem POS, Barcode Scanner & Import/Export CSV</div> </div> </div> </header>
<div id="toast" class="toast"></div>
<!-- MODAL SCANNER --> <div id="scannerModal" class="scanner-modal"> <div class="scanner-box"> <div class="card-title" style="margin-bottom:6px;"> <span id="scannerTitle">Scan Barcode Produk</span> <span class="badge badge-scan" id="scanSessionBadge">0 discan</span> </div> <p class="muted" id="scannerHint">Arahkan kamera ke barcode / QR code produk</p> <div class="continuous-toggle" id="continuousScanControl"> <label for="chkContinuousScan"> <input type="checkbox" id="chkContinuousScan" checked /> Mode Scan Beruntun </label> </div> <div class="scan-feedback-bar" id="scanFeedbackBar"> <span id="scanFeedbackText">Siap memindai...</span> </div> <div id="barcodeReader"><div class="scan-frame"></div></div> <p class="hint-text" style="text-align:center; margin-bottom:10px;"> Buka via <strong>HTTPS</strong> / <strong>localhost</strong>, di <strong>Chrome/Safari</strong>. </p> <button class="btn btn-danger" onclick="closeScanner()">Selesai & Tutup Kamera</button> </div> </div>
<!-- MODAL CETAK --> <div id="printModal" class="scanner-modal"> <div class="scanner-box"> <div class="card-title" style="margin-bottom: 6px;"> <span>🖨️ Cetak Struk Transaksi</span> <span class="badge badge-scan" id="printTotalBadge">Rp 0</span> </div> <p class="muted" style="margin-bottom: 10px;">Pilih ukuran kertas struk, lalu klik cetak.</p>
<div class="form-group"> <label>Ukuran Kertas Struk</label> <select id="printSizeSelect" onchange="toggleCustomSize()"> <option value="58">58mm (Thermal Kecil) — Default</option> <option value="76">76mm (Thermal)</option> <option value="80">80mm (Thermal Standar)</option> <option value="110">110mm (Thermal Besar)</option> <option value="a4">A4 (Kertas Biasa)</option> <option value="custom">Custom (mm)...</option> </select> <input type="number" id="customSizeInput" placeholder="Lebar mm (misal 90)" min="30" max="500" style="display:none; margin-top:6px;" /> </div>
<div class="grid-2" style="gap: 8px;"> <button class="btn btn-primary" onclick="printCurrentReceipt()">🖨️ Cetak Sekarang</button> <button class="btn btn-outline" onclick="closePrintModal()">Selesai</button> </div>
<p class="hint-text" style="margin-top: 10px; text-align: center;"> Pastikan printer thermal sudah dipilih di dialog cetak browser. </p> </div> </div>
<main> <!-- TAB POS --> <section id="tab-pos" class="tab-content active"> <div class="card"> <div class="card-title"> <span>Pilih Barang (POS)</span> <div style="display:flex; gap:6px; align-items:center;"> <span class="badge" id="posItemCount">0 item</span> <button class="btn btn-dark btn-sm" onclick="openScanner('POS')">📷 Scan</button> </div> </div> <div class="grid-2" style="margin-bottom: 8px;"> <input type="text" id="posSearch" placeholder="Cari nama / barcode..." oninput="renderPOSItems()" /> <select id="posClusterFilter" onchange="renderPOSItems()"> <option value="ALL">Semua Cluster</option> </select> </div> <div id="posProductList" style="max-height: 260px; overflow-y: auto;"></div> </div>
<div class="card"> <div class="card-title"> <span>Keranjang Transaksi</span> <button class="btn btn-outline btn-sm" onclick="clearCart()">Kosongkan</button> </div> <div id="cartList"><p class="empty-state">Keranjang masih kosong</p></div>
<div class="cart-summary"> <div class="grid-2" style="margin-bottom: 8px;"> <div> <label>Diskon Transaksi (Rp)</label> <input type="number" id="cartDiscount" value="0" min="0" inputmode="numeric" oninput="renderCart()" /> </div> <div> <label>Uang Bayar (Rp)</label> <input type="number" id="cartPaid" placeholder="0" min="0" inputmode="numeric" oninput="renderCart()" /> </div> </div> <div class="summary-line"><span>Subtotal</span><span id="summarySubtotal">Rp 0</span></div> <div class="summary-line"><span>Estimasi Profit</span><span id="summaryProfit">Rp 0</span></div> <div class="summary-line"><span>Kembalian</span><span id="summaryChange">Rp 0</span></div> <div class="summary-line summary-total"><span>TOTAL BAYAR</span><span id="summaryTotal">Rp 0</span></div> <button class="btn btn-success" style="margin-top:10px;" onclick="checkout()">Proses & Simpan Transaksi</button> </div> </div> </section>
<!-- TAB INVENTORY --> <section id="tab-inv" class="tab-content"> <div class="card"> <div class="card-title"> <span id="formTitle">Tambah / Edit Item</span> <button class="btn btn-outline btn-sm" onclick="resetItemForm()">Reset</button> </div> <input type="hidden" id="editItemId" value="" /> <div class="form-group"> <label>Kode / Barcode / SKU Item</label> <div class="input-with-btn"> <input type="text" id="itemCode" placeholder="Contoh: 8991002101111" /> <button class="btn btn-dark btn-sm" onclick="openScanner('INV')">📷 Scan</button> </div> </div> <div class="grid-2"> <div class="form-group"> <label>Cluster / Kategori</label> <input type="text" id="itemCluster" list="clusterSuggestions" placeholder="Minuman / Makanan" /> <datalist id="clusterSuggestions"></datalist> </div> <div class="form-group"> <label>Jumlah Stok</label> <input type="number" id="itemQty" min="0" inputmode="numeric" placeholder="0" /> </div> </div> <div class="form-group"> <label>Nama Item</label> <input type="text" id="itemName" placeholder="Nama produk" /> </div> <div class="grid-2"> <div class="form-group"> <label>Harga Beli / Modal (Rp)</label> <input type="number" id="itemBuy" min="0" inputmode="numeric" placeholder="0" oninput="previewItemMargin()" /> </div> <div class="form-group"> <label>Harga Jual (Rp)</label> <input type="number" id="itemSell" min="0" inputmode="numeric" placeholder="0" oninput="previewItemMargin()" /> </div> </div> <p class="muted" style="margin-bottom:10px; font-weight:600;" id="itemMarginPreview">Margin: Rp 0 (0%)</p> <button class="btn btn-primary" onclick="saveItem()">Simpan Item ke Inventory</button> </div>
<div class="card"> <div class="card-title"> <span>Impor Data CSV ke Inventory</span> <button class="btn btn-outline btn-sm" onclick="downloadTemplateCSV()">Unduh Template</button> </div> <div class="import-box"> <div class="form-group"> <label>Pilih File CSV (.csv)</label> <input type="file" id="csvFileInput" accept=".csv,text/csv" /> </div> <div class="form-group" style="margin-bottom:0;"> <label>Mode Impor Jika Kode / Nama Item Sama</label> <select id="csvImportMode"> <option value="UPSERT_OVERWRITE">Update Data & Timpa Stok (Direkomendasikan)</option> <option value="UPSERT_ADD_STOCK">Update Harga & Tambahkan ke Stok Lama</option> <option value="REPLACE_ALL">Ganti Seluruh Data Inventory (Hapus Lama)</option> </select> </div> </div> <button class="btn btn-warning" onclick="importInventoryCSV()">Proses Impor CSV</button> <p class="hint-text" style="margin-top:8px;"> Kolom CSV: <strong>Kode_Item, Nama_Item, Cluster, Jumlah_Stok, Harga_Beli, Harga_Jual</strong> (mendukung pemisah koma <code>,</code> atau titik koma <code>;</code>). </p> </div>
<div class="card"> <div class="card-title"> <span>Daftar Stok Barang</span> <button class="btn btn-success btn-sm" onclick="exportInventoryCSV()">Export CSV</button> </div> <input type="text" id="invSearch" placeholder="Cari nama / kode / cluster..." oninput="renderInventory()" style="margin-bottom:8px;" /> <div id="inventoryList" style="max-height: 420px; overflow-y: auto;"></div> </div> </section>
<!-- TAB MARGIN --> <section id="tab-margin" class="tab-content"> <div class="card"> <div class="card-title">Atur Margin Massal / Cluster</div> <p class="hint-text" style="margin-bottom:10px;">Perbarui harga jual secara otomatis berdasarkan harga beli untuk seluruh barang atau cluster tertentu.</p> <div class="form-group"> <label>Target Penerapan</label> <select id="marginTarget"><option value="ALL">Semua Item Sekaligus</option></select> </div> <div class="grid-2"> <div class="form-group"> <label>Tipe Margin</label> <select id="marginType"> <option value="PERCENT">Persentase (%)</option> <option value="NOMINAL">Nominal Tetap (Rp)</option> </select> </div> <div class="form-group"> <label>Nilai Margin</label> <input type="number" id="marginAmount" min="0" inputmode="numeric" placeholder="Contoh: 30" /> </div> </div> <div class="form-group"> <label>Pembulatan Harga Jual</label> <select id="marginRounding"> <option value="1">Tanpa Pembulatan</option> <option value="100">Bulatkan ke Rp 100 terdekat</option> <option value="500">Bulatkan ke Rp 500 terdekat</option> <option value="1000">Bulatkan ke Rp 1.000 terdekat</option> </select> </div> <button class="btn btn-primary" onclick="applyBulkMargin()">Terapkan Margin Sekarang</button> </div> <div class="card"> <div class="card-title">Ringkasan Valuasi Inventory</div> <div class="grid-2"> <div class="stat-box"><div class="muted">Total Modal Stok</div><div class="stat-val" id="valTotalCost">Rp 0</div></div> <div class="stat-box"><div class="muted">Potensi Omzet</div><div class="stat-val" id="valTotalRev">Rp 0</div></div> </div> </div> </section>
<!-- TAB LAPORAN --> <section id="tab-report" class="tab-content"> <div class="card"> <div class="card-title">Filter Laporan Periode</div> <div class="grid-2"> <div class="form-group"> <label>Dari Tanggal</label> <input type="date" id="repStartDate" onchange="renderReport()" /> </div> <div class="form-group"> <label>Sampai Tanggal</label> <input type="date" id="repEndDate" onchange="renderReport()" /> </div> </div> <div class="grid-2"> <button class="btn btn-outline btn-sm" onclick="setReportToday()">Hari Ini</button> <button class="btn btn-outline btn-sm" onclick="setReportMonth()">Bulan Ini</button> </div> </div> <div class="card"> <div class="card-title">Ringkasan Performa</div> <div class="grid-2" style="margin-bottom:8px;"> <div class="stat-box"><div class="muted">Total Transaksi</div><div class="stat-val" id="repTxCount">0</div></div> <div class="stat-box"><div class="muted">Item Terjual</div><div class="stat-val" id="repItemsSold">0</div></div> </div> <div class="grid-2"> <div class="stat-box"><div class="muted">Total Omzet</div><div class="stat-val" id="repRevenue">Rp 0</div></div> <div class="stat-box"><div class="muted">Laba Bersih</div><div class="stat-val" id="repProfit">Rp 0</div></div> </div> </div> <div class="card"> <div class="card-title">Export CSV (Nama Otomatis)</div> <p class="hint-text" style="margin-bottom:10px;">Format nama file: <code>jenis_YYYYMMDD_HHMMSS.csv</code></p> <div class="grid-2"> <button class="btn btn-success btn-sm" onclick="exportSalesCSV()">CSV Laporan Sales</button> <button class="btn btn-primary btn-sm" onclick="exportInventoryCSV()">CSV Stok Inventory</button> </div> <div class="divider"></div> <button class="btn btn-danger btn-sm" onclick="resetDemoData()">Muat Ulang Data Contoh</button> </div> <div class="card"> <div class="card-title">Riwayat Transaksi Periode Ini</div> <div id="salesHistoryList" style="max-height: 400px; overflow-y: auto;"></div> </div> </section> </main>
<nav class="bottom-nav"> <button class="nav-btn active" onclick="switchTab('pos', this)"><span class="nav-icon">🛒</span>Kasir POS</button> <button class="nav-btn" onclick="switchTab('inv', this)"><span class="nav-icon">📦</span>Inventory</button> <button class="nav-btn" onclick="switchTab('margin', this)"><span class="nav-icon">📈</span>Set Margin</button> <button class="nav-btn" onclick="switchTab('report', this)"><span class="nav-icon">📊</span>Laporan</button> </nav></div>
<!-- ============================================================ AREA CETAK — WAJIB DI LUAR .app-shell (anak langsung <body>) ============================================================ --><div id="printArea" class="print-area"></div>
<script>/* ============================================================ 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, '"').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 = '<option value="ALL">Semua Cluster</option>' + clusters.map(c => '<option value="' + esc(c) + '">' + esc(c) + '</option>').join(''); if (clusters.includes(currentPos)) posFilter.value = currentPos;
const marginTarget = document.getElementById('marginTarget'); const currentMargin = marginTarget.value; marginTarget.innerHTML = '<option value="ALL">Semua Item Sekaligus</option>' + clusters.map(c => '<option value="' + esc(c) + '">Cluster: ' + esc(c) + '</option>').join(''); if (clusters.includes(currentMargin)) marginTarget.value = currentMargin;
document.getElementById('clusterSuggestions').innerHTML = clusters.map(c => '<option value="' + esc(c) + '"></option>').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 = '<p class="empty-state">Barang tidak ditemukan</p>'; return; } container.innerHTML = filtered.map(item => { const outOfStock = item.qty <= 0; return '<div class="item-row">' + '<div style="flex:1; min-width:0;">' + '<div style="font-weight:600; font-size:0.88rem;">' + esc(item.name) + '</div>' + '<div class="muted"><span class="badge">' + esc(item.cluster) + '</span> • ' + 'Kode: ' + esc(item.code) + ' • Stok: <strong>' + item.qty + '</strong></div>' + '<div class="price-tag">' + formatRp(item.sellPrice) + '</div>' + '</div>' + '<button class="btn btn-primary btn-sm" ' + (outOfStock ? 'disabled' : '') + ' onclick="addToCart(\'' + item.id + '\')">+ Tambah</button>' + '</div>'; }).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 = '<p class="empty-state">Keranjang masih kosong</p>'; } else { container.innerHTML = cart.map(c => '<div class="item-row">' + '<div style="flex:1; min-width:0;">' + '<div style="font-weight:600; font-size:0.85rem;">' + esc(c.name) + '</div>' + '<div class="muted">' + formatRp(c.sellPrice) + ' x ' + c.qty + ' = <strong>' + formatRp(c.sellPrice * c.qty) + '</strong></div>' + '</div>' + '<div style="display:flex; align-items:center; gap:6px;">' + '<button class="btn btn-outline btn-sm" onclick="updateCartQty(\'' + c.id + '\', -1)">-</button>' + '<span style="font-weight:700; min-width:22px; text-align:center;">' + c.qty + '</span>' + '<button class="btn btn-outline btn-sm" onclick="updateCartQty(\'' + c.id + '\', 1)">+</button>' + '</div>' + '</div>' ).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 = '<p class="empty-state">Belum ada data barang</p>'; 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 ? ' <span class="badge badge-low">Stok Menipis</span>' : ''; return '<div class="item-row">' + '<div style="flex:1; min-width:0;">' + '<div style="font-weight:700; font-size:0.88rem;">' + esc(item.name) + lowBadge + '</div>' + '<div class="muted"><span class="badge">' + esc(item.cluster) + '</span> • ' + esc(item.code) + ' • Stok: <strong>' + item.qty + '</strong></div>' + '<div class="muted">Beli: ' + formatRp(item.buyPrice) + ' | Jual: <strong>' + formatRp(item.sellPrice) + '</strong></div>' + '<div style="font-size:0.75rem; color: var(--success); font-weight:600;">' + 'Margin: ' + formatRp(marginVal) + ' (' + marginPct + '%)</div>' + '</div>' + '<div style="display:flex; flex-direction:column; gap:4px;">' + '<button class="btn btn-outline btn-sm" onclick="editItem(\'' + item.id + '\')">Edit</button>' + '<button class="btn btn-danger btn-sm" onclick="deleteItem(\'' + item.id + '\')">Hapus</button>' + '</div>' + '</div>'; }).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 = '<p class="empty-state">Tidak ada transaksi pada periode ini</p>'; 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 '<div class="item-row">' + '<div style="flex:1; min-width:0;">' + '<div style="font-weight:700; font-size:0.84rem;">' + esc(tx.id) + '</div>' + '<div class="muted">' + waktu + '</div>' + '<div style="font-size:0.78rem; margin-top:2px;">' + rincian + '</div>' + '</div>' + '<div style="display:flex; flex-direction:column; gap:4px; text-align:right; align-items:flex-end;">' + '<div class="price-tag">' + formatRp(tx.total) + '</div>' + '<div style="font-size:0.74rem; color:var(--success);">+' + formatRp(tx.profit) + '</div>' + '<button class="btn btn-dark btn-sm" onclick="findAndPrint(\'' + tx.id + '\')">🖨️</button>' + '</div>' + '</div>'; }).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 '' + '<tr>' + '<td colspan="2" class="r-item-name">' + esc(i.name) + '</td>' + '</tr>' + '<tr>' + '<td class="r-item-detail" style="width:60%;">' + i.qty + ' x ' + fmtNum(i.sellPrice) + '</td>' + '<td class="r-item-detail" style="width:40%; text-align:right;">' + fmtNum(lineTotal) + '</td>' + '</tr>'; }).join('');
return '' + '<div class="receipt">' + '<div class="r-center r-bold" style="font-size:1.15em;">TOKO DAMAR TUJUH</div>' + '<div class="r-center">Pekayon, Bekasi Selatan</div>' + '<hr class="r-divider" />' + '<div class="r-line"><span>No</span><span>' + esc(tx.id) + '</span></div>' + '<div class="r-line"><span>Tgl</span><span>' + waktu + '</span></div>' + '<hr class="r-divider" />' + '<table class="r-items">' + itemsHTML + '</table>' + '<hr class="r-divider" />' + '<div class="r-line"><span>Subtotal</span><span>' + fmtNum(tx.subtotal) + '</span></div>' + (hasDiscount ? '<div class="r-line"><span>Diskon</span><span>-' + fmtNum(tx.discount) + '</span></div>' : '') + '<div class="r-total"><span>TOTAL</span><span>' + fmtNum(tx.total) + '</span></div>' + '<div class="r-line"><span>Bayar</span><span>' + fmtNum(paid) + '</span></div>' + '<div class="r-line"><span>Kembali</span><span>' + fmtNum(change) + '</span></div>' + '<hr class="r-divider" />' + '<div class="r-center r-mt">Terima kasih atas kunjungan Anda</div>' + '<div class="r-center r-bold">Galaxy Production</div>' + '<div class="r-center" style="font-size:0.85em;">lynk.id/readthefuture</div>' + '</div>';}
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(); });});</script></body></html>posv1_bak2.htmlDeleted-1810