Spaces:
Sleeping
Sleeping
File size: 20,721 Bytes
bcfb3fe 61b0478 19fc963 9e12c57 19fc963 fe66e2d 61b0478 fe66e2d 825ad18 61b0478 fe66e2d 19fc963 fe66e2d 61b0478 f26441b 825ad18 61b0478 f26441b 825ad18 f26441b 61b0478 825ad18 f26441b 61b0478 825ad18 61b0478 825ad18 61b0478 825ad18 f26441b 825ad18 f26441b 61b0478 ea2c7d7 19fc963 61b0478 fe66e2d 61b0478 fe66e2d 61b0478 19fc963 fe66e2d 19fc963 ea2c7d7 61b0478 ea2c7d7 61b0478 19fc963 61b0478 19fc963 61b0478 ea2c7d7 fe66e2d ea2c7d7 fe66e2d ea2c7d7 61b0478 19fc963 4ee1351 ea2c7d7 61b0478 ea2c7d7 61b0478 19fc963 61b0478 ea2c7d7 61b0478 ea2c7d7 61b0478 19fc963 61b0478 19fc963 61b0478 19fc963 4ee1351 61b0478 9e12c57 61b0478 825ad18 61b0478 f26441b 61b0478 f26441b 61b0478 ea2c7d7 625847e f26441b 61b0478 f26441b 61b0478 825ad18 625847e f26441b 61b0478 625847e 61b0478 625847e f26441b 61b0478 825ad18 61b0478 f26441b 625847e f26441b 625847e 61b0478 f26441b 4ee1351 61b0478 f26441b 9e12c57 61b0478 9e12c57 61b0478 9e12c57 825ad18 b194747 825ad18 61b0478 825ad18 4ee1351 b194747 a3f0fb6 4ee1351 ea2c7d7 61b0478 19fc963 b194747 825ad18 b194747 825ad18 b194747 19fc963 825ad18 61b0478 19fc963 825ad18 61b0478 825ad18 19fc963 61b0478 19fc963 9f8d3a8 825ad18 9f8d3a8 61b0478 19fc963 9f8d3a8 19fc963 61b0478 19fc963 4e9c0c1 19fc963 61b0478 9f8d3a8 825ad18 9f8d3a8 4e9c0c1 825ad18 4e9c0c1 825ad18 4e9c0c1 825ad18 4e9c0c1 825ad18 9f8d3a8 825ad18 4e9c0c1 825ad18 4e9c0c1 825ad18 4e9c0c1 825ad18 9f8d3a8 4e9c0c1 825ad18 4e9c0c1 825ad18 4e9c0c1 825ad18 4e9c0c1 825ad18 4e9c0c1 825ad18 4e9c0c1 825ad18 4e9c0c1 825ad18 4e9c0c1 825ad18 4e9c0c1 825ad18 4e9c0c1 825ad18 19fc963 9f8d3a8 19fc963 61b0478 825ad18 19fc963 61b0478 19fc963 5cc8aed 19fc963 61b0478 19fc963 61b0478 bcfb3fe 19fc963 61b0478 425d6d9 61b0478 425d6d9 61b0478 19fc963 61b0478 19fc963 9ff2f5c 19fc963 61b0478 19fc963 61b0478 bcfb3fe 9ff2f5c f26441b f2f2e4f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 | 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 = `<div class="toast__content"><span class="toast__icon">${type === 'success' ? '✓' : type === 'error' ? '✕' : type === 'warning' ? '⚠️' : 'ℹ'}</span><span>${msg}</span><button class="toast__close">✕</button></div>`;
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 = `<span>${icon} ${text}</span><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>`;
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 = '<div class="btn-spinner"></div> 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 = `<tr><th>n</th><th>x</th>`;
data.columns.forEach(col => headHTML += `<th>${col}</th>`);
headHTML += `</tr>`;
tableHead.innerHTML = headHTML;
let bodyHTML = '';
data.data.forEach(row => {
bodyHTML += `<tr>`;
bodyHTML += `<td><strong>${row.n}</strong></td>`;
bodyHTML += `<td style="color: var(--accent-cyan);">${row.x}</td>`;
data.columns.forEach(col => bodyHTML += `<td>${row.values[col] || '0.0000'}</td>`);
bodyHTML += `</tr>`;
});
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();
});
|