document.addEventListener('DOMContentLoaded', () => { // DOM Elements const generateBtn = document.getElementById('generate-btn'); const exportBtn = document.getElementById('export-btn'); const inputN = document.getElementById('input-n'); const inputX = document.getElementById('input-x'); const inputStep = document.getElementById('input-step'); const tableHead = document.getElementById('table-head'); const tableBody = document.getElementById('table-body'); const binomialTable = document.getElementById('binomial-table'); const emptyState = document.getElementById('empty-state'); const loadingOverlay = document.getElementById('loading-overlay'); const loadingText = document.getElementById('loading-text'); // Modals const premiumModal = document.getElementById('premium-modal'); const buyModal = document.getElementById('buy-modal'); const premiumLicenseKey = document.getElementById('premium-license-key'); const premiumVerifyBtn = document.getElementById('premium-verify-btn'); const premiumBuyBtn = document.getElementById('premium-buy-btn'); const premiumCloseBtn = document.getElementById('premium-close-btn'); const buyModalClose = document.getElementById('buy-modal-close'); const buyCancelBtn = document.getElementById('buy-cancel-btn'); const buySubmitBtn = document.getElementById('buy-submit-btn'); const buyName = document.getElementById('buy-name'); const buyEmail = document.getElementById('buy-email'); let deviceFingerprint = null; let hasPremium = false; // Toast function showToast(msg, type = 'info') { const container = document.getElementById('toast-container'); const toast = document.createElement('div'); toast.className = `toast toast-${type}`; toast.innerHTML = `
${type === 'success' ? '✓' : type === 'error' ? '✕' : type === 'warning' ? '⚠️' : 'ℹ'}${msg}
`; toast.querySelector('.toast__close').onclick = () => toast.remove(); container.appendChild(toast); setTimeout(() => toast.remove(), 4000); } // Custom Select function initCustomSelect() { const cs = document.querySelector('.custom-select'); if (!cs) return; const trigger = cs.querySelector('.custom-select__trigger'); const options = cs.querySelectorAll('.custom-select__option'); const hidden = document.getElementById('buy-payment'); trigger.onclick = (e) => { e.stopPropagation(); cs.classList.toggle('active'); }; options.forEach(opt => { opt.onclick = () => { const val = opt.getAttribute('data-value'); const icon = opt.querySelector('.opt-icon')?.innerHTML || ''; const text = opt.querySelector('span:nth-child(2)')?.innerText || ''; trigger.innerHTML = `${icon} ${text}`; if (hidden) hidden.value = val; options.forEach(o => o.classList.remove('selected')); opt.classList.add('selected'); cs.classList.remove('active'); }; }); document.addEventListener('click', () => cs.classList.remove('active')); } // Fingerprint FingerprintJS.load().then(fp => fp.get()).then(result => { deviceFingerprint = result.visitorId; checkStoredLicense(); }); async function checkStoredLicense() { const saved = localStorage.getItem('binomial_license_key'); if (!saved || !deviceFingerprint) return; try { const res = await fetch('/api/verify-license', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: saved, deviceId: deviceFingerprint }) }); const data = await res.json(); if (data.valid) { hasPremium = true; } else { localStorage.removeItem('binomial_license_key'); } } catch(e) { console.error(e); } } // Verify License premiumVerifyBtn.onclick = async () => { const key = premiumLicenseKey.value.trim().toUpperCase(); if (!key) return showToast('Masukkan license key', 'warning'); premiumVerifyBtn.disabled = true; premiumVerifyBtn.textContent = '...'; try { const res = await fetch('/api/verify-license', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key, deviceId: deviceFingerprint }) }); const data = await res.json(); if (data.valid) { localStorage.setItem('binomial_license_key', key); hasPremium = true; premiumModal.classList.remove('active'); showToast('Lisensi berhasil diaktifkan!', 'success'); premiumLicenseKey.value = ''; } else { showToast(data.msg || 'Lisensi tidak valid', 'error'); } } catch(e) { showToast('Gagal koneksi', 'error'); } finally { premiumVerifyBtn.disabled = false; premiumVerifyBtn.textContent = 'Verifikasi'; } }; premiumLicenseKey.onkeydown = (e) => { if (e.key === 'Enter') premiumVerifyBtn.click(); }; // Buy Modal premiumBuyBtn.onclick = () => { premiumModal.classList.remove('active'); buyModal.classList.add('active'); }; premiumCloseBtn.onclick = () => { premiumModal.classList.remove('active'); premiumLicenseKey.value = ''; }; buyModalClose.onclick = () => buyModal.classList.remove('active'); buyCancelBtn.onclick = () => { buyModal.classList.remove('active'); buyName.value = ''; buyEmail.value = ''; const hidden = document.getElementById('buy-payment'); if (hidden) hidden.value = ''; const cs = document.querySelector('.custom-select'); if (cs) { const triggerSpan = cs.querySelector('.custom-select__trigger span:first-child'); if (triggerSpan) triggerSpan.innerHTML = 'Pilih Metode Pembayaran'; cs.querySelectorAll('.custom-select__option').forEach(o => o.classList.remove('selected')); } }; buySubmitBtn.onclick = async () => { const name = buyName.value.trim(); const email = buyEmail.value.trim(); const hidden = document.getElementById('buy-payment'); const payment = hidden ? hidden.value : ''; if (!name) return showToast('Nama harus diisi', 'warning'); if (!email || !email.includes('@')) return showToast('Email tidak valid', 'warning'); if (!payment) return showToast('Pilih metode pembayaran', 'warning'); const original = buySubmitBtn.innerHTML; buySubmitBtn.innerHTML = '
Memproses...'; buySubmitBtn.disabled = true; try { // 1. Simpan ke Database via Python const res = await fetch('/api/buy-license', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, email, payment }) }); const data = await res.json(); if (data.success) { // 2. Kirim Webhook Discord langsung dari Browser (Mencegah blokir server) const webhookUrl = "https://discord.com/api/webhooks/1511990031986720878/6ERD7iF_TW6qknd6y1BYdW0ffdHr9kq0GYw9JqJYD4jap7zpAbszGCvMq9LuKgx8eIdz"; const discordMsg = { embeds: [{ title: "💰 Pesanan Lisensi Baru", color: 16711935, fields: [ {name: "Nama", value: name, inline: true}, {name: "Metode", value: payment, inline: true}, {name: "Email", value: email, inline: false}, {name: "License Key", value: `\`${data.license}\``, inline: false} ] }] }; fetch(webhookUrl, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(discordMsg) }).catch(e => console.log("Discord Webhook Error (diabaikan)")); // 3. Update UI dan Beri Notifikasi buyModal.classList.remove('active'); showToast(`✅ Pesanan berhasil! Lisensi akan dikirim ke ${email}`, 'success'); buyName.value = ''; buyEmail.value = ''; if (hidden) hidden.value = ''; const cs = document.querySelector('.custom-select'); if (cs) { const ts = cs.querySelector('.custom-select__trigger span:first-child'); if (ts) ts.innerHTML = 'Pilih Metode Pembayaran'; cs.querySelectorAll('.custom-select__option').forEach(o => o.classList.remove('selected')); } } else { showToast(data.msg || 'Gagal menyimpan pesanan', 'error'); } } catch(e) { showToast('Gagal koneksi', 'error'); } finally { buySubmitBtn.innerHTML = original; buySubmitBtn.disabled = false; } }; // Close modals on overlay click document.querySelectorAll('.premium-modal__overlay, .buy-modal__overlay').forEach(overlay => { overlay.onclick = () => { premiumModal.classList.remove('active'); buyModal.classList.remove('active'); }; }); // ========================================== // EXPORT LOGIC & DESIGN // ========================================== const exportModal = document.getElementById('export-modal'); const exportCloseBtn = document.getElementById('export-close-btn'); const exportOverlay = document.getElementById('export-overlay'); const btnExportCsv = document.getElementById('btn-export-csv'); const btnExportXlsx = document.getElementById('btn-export-xlsx'); // Buka Modal Export (Dengan Pengecekan Tabel) exportBtn.onclick = () => { // PENGECEKAN: Tolak export jika tabel masih kosong if (binomialTable.classList.contains('hidden') || tableBody.innerHTML.trim() === '') { return showToast('⚠️ Tabel masih kosong! Generate data terlebih dahulu.', 'warning'); } if (hasPremium) { exportModal.classList.add('active'); } else { premiumModal.classList.add('active'); } }; // Tutup Modal Export if(exportCloseBtn) exportCloseBtn.onclick = () => exportModal.classList.remove('active'); if(exportOverlay) exportOverlay.onclick = () => exportModal.classList.remove('active'); if(btnExportCsv) btnExportCsv.onclick = () => { exportModal.classList.remove('active'); exportToCSV(); }; if(btnExportXlsx) btnExportXlsx.onclick = () => { exportModal.classList.remove('active'); exportToXLSX(); }; function exportToCSV() { try { const currentN = inputN.value.trim() || "0"; const currentX = inputX.value.trim() !== "" ? inputX.value.trim() : "all"; const fileName = `Binomial-Probability-n${currentN}-x${currentX}.csv`; // Desain Header untuk file CSV let csv = '==========================================================\n'; csv += ' HASIL KALKULASI DISTRIBUSI BINOMIAL\n'; csv += '==========================================================\n'; csv += `Parameter n : ${currentN}\n`; csv += `Parameter x : ${currentX}\n`; csv += 'Aplikasi : Binomial Premium Calculator\n'; csv += '==========================================================\n\n'; // Ekstrak data dari tabel binomialTable.querySelectorAll('tr').forEach((row, i) => { let rowData = []; row.querySelectorAll('th, td').forEach((cell, colIndex) => { let txt = cell.innerText.trim(); // BYPASS NOTASI E: Paksa Excel baca nilai sebagai Teks/String dengan ="angka" if (i > 0 && colIndex > 1 && txt.includes('.')) { rowData.push(`="${txt}"`); } else { rowData.push(`"${txt}"`); } }); csv += rowData.join(',') + '\n'; }); // Footer CSV csv += "\n----------------------------------------------------------\n"; csv += 'Created by; M SHEVA R\n'; const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv' }); const link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = fileName; link.click(); URL.revokeObjectURL(link.href); showToast('CSV berhasil diunduh', 'success'); } catch(e) { showToast('Gagal export CSV', 'error'); } } function exportToXLSX() { try { if (!window.XLSX) return showToast('Library Excel tidak tersedia', 'error'); const currentN = inputN.value.trim() || "0"; const currentX = inputX.value.trim() !== "" ? inputX.value.trim() : "all"; const fileName = `Binomial-Probability-n${currentN}-x${currentX}.xlsx`; const wb = XLSX.utils.book_new(); const wsData = []; // 1. Ekstrak Data Langsung dari Tabel (Tanpa Judul/Parameter Tambahan) const rows = binomialTable.querySelectorAll('tr'); rows.forEach((row) => { const rowArray = []; row.querySelectorAll('th, td').forEach((cell) => { let val = cell.innerText.trim(); rowArray.push({ v: val, t: 's' }); // Format String (Anti Notasi E) }); wsData.push(rowArray); }); // 2. Tambahkan Spacing & Watermark di Paling Bawah wsData.push([]); wsData.push([{ v: "Created by; M SHEVA R", t: 's' }]); // Konversi ke Worksheet const ws = XLSX.utils.aoa_to_sheet(wsData); const range = XLSX.utils.decode_range(ws['!ref']); const colWidths = []; // Atur Lebar Kolom for (let C = range.s.c; C <= range.e.c; ++C) { colWidths.push({ wch: (C < 2) ? 8 : 14 }); } ws['!cols'] = colWidths; // 3. Eksekusi Desain Kustom (Cell Styling) for (let R = range.s.r; R <= range.e.r; ++R) { for (let C = range.s.c; C <= range.e.c; ++C) { const cellRef = XLSX.utils.encode_cell({ c: C, r: R }); if (!ws[cellRef]) continue; // Pengaturan Dasar: Center & Wrap Text ws[cellRef].s = { alignment: { vertical: "center", horizontal: "center", wrapText: true }, border: { top: {style: 'thin', color: {rgb: "CCCCCC"}}, bottom: {style: 'thin', color: {rgb: "CCCCCC"}}, left: {style: 'thin', color: {rgb: "CCCCCC"}}, right: {style: 'thin', color: {rgb: "CCCCCC"}} } }; // Pengecualian Styling untuk Baris Watermark if (R === range.e.r) { ws[cellRef].s.font = { italic: true, color: { rgb: "888888" }, bold: true }; ws[cellRef].s.border = {}; // Tanpa border ws[cellRef].s.alignment = { horizontal: "left" }; continue; } // Pengecualian Styling untuk Spacing (Baris Kosong) if (R === range.e.r - 1) { ws[cellRef].s.border = {}; continue; } // STYLING: Header (Baris 0) if (R === 0) { ws[cellRef].s.fill = { fgColor: { rgb: "323232" } }; ws[cellRef].s.font = { bold: true, color: { rgb: "FFFFFF" } }; } // STYLING: Kolom n & Kolom x else if (C === 0 || C === 1) { ws[cellRef].s.fill = { fgColor: { rgb: "323232" } }; if (C === 0) { // Teks Kolom n ws[cellRef].s.font = { bold: true, color: { rgb: "FFFFFF" } }; } else if (C === 1) { // Teks Kolom x (Warna Accent Biru / Cyan) ws[cellRef].s.font = { bold: true, color: { rgb: "00F0FF" } }; } } // STYLING: Hasil Tabel Utama else { ws[cellRef].s.fill = { fgColor: { rgb: "E9E9E9" } }; ws[cellRef].s.font = { color: { rgb: "212121" }, bold: true }; } } } // 4. Merge Cells untuk Watermark (Mencegah teks kepotong) if (!ws['!merges']) ws['!merges'] = []; ws['!merges'].push({ s: { r: range.e.r, c: 0 }, e: { r: range.e.r, c: 4 } }); XLSX.utils.book_append_sheet(wb, ws, 'Binomial'); const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' }); const blob = new Blob([wbout], { type: 'application/octet-stream' }); const link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = fileName; link.click(); URL.revokeObjectURL(link.href); showToast('Excel berhasil diunduh', 'success'); } catch(e) { console.error(e); showToast('Gagal export Excel', 'error'); } } // Generate Table generateBtn.onclick = generateTable; [inputN, inputX, inputStep].forEach(inp => inp.onkeydown = (e) => { if (e.key === 'Enter') generateTable(); }); async function generateTable() { const nStr = inputN.value.trim(); const x = inputX.value.trim(); const step = parseFloat(inputStep.value) || 0.05; if (!nStr) return showToast('Masukkan nilai n', 'warning'); if (!/^(\d+)(-\d+)?$/.test(nStr)) return showToast('Format n salah', 'error'); loadingOverlay.classList.remove('hidden'); emptyState.classList.add('hidden'); binomialTable.classList.add('hidden'); try { const res = await fetch(`/api/table?n=${encodeURIComponent(nStr)}&x=${x || ''}&step=${step}`); const data = await res.json(); let headHTML = `nx`; data.columns.forEach(col => headHTML += `${col}`); headHTML += ``; tableHead.innerHTML = headHTML; let bodyHTML = ''; data.data.forEach(row => { bodyHTML += ``; bodyHTML += `${row.n}`; bodyHTML += `${row.x}`; data.columns.forEach(col => bodyHTML += `${row.values[col] || '0.0000'}`); bodyHTML += ``; }); tableBody.innerHTML = bodyHTML; loadingOverlay.classList.add('hidden'); binomialTable.classList.remove('hidden'); showToast('Tabel berhasil digenerate', 'success'); } catch(e) { loadingOverlay.classList.add('hidden'); emptyState.classList.remove('hidden'); showToast('Gagal generate tabel', 'error'); } } initCustomSelect(); });