// Cek Harga: one question per step on phones, live result from the server renderer, lead sent without leaving the page. // Without JS the same form submits as GET and the server renders the result (progressive enhancement). import { api, store } from '/engine/engine.js'; import { sendQ } from '/js/q.mjs'; const form = document.getElementById('calc'); const result = document.getElementById('result'); const bar = document.getElementById('bar'); const all = [...form.querySelectorAll('fieldset[data-step]')]; // Owner #87: some questions only apply to some needs (data-need) or are skipped by an earlier answer (data-skip-unit). const val = (name) => form.querySelector(`input[name="${name}"]:checked`)?.value || ''; // Owner #88: a part the charger type does not have (11 kW: no safety kit priced) is skipped too (cx.skip from the server). let cx = {}; const applies = (f) => (!f.dataset.need || f.dataset.need.split(' ').includes(val('kebutuhan'))) && (!f.dataset.skipUnit || val('unit') !== f.dataset.skipUnit) && !(cx.skip || []).includes(f.dataset.step); const run = document.getElementById('run'); /** Checkout prices on every option (owner #88), from the JSON the result fragment carries. */ function prices() { const el = result.querySelector('#cx'); cx = el ? JSON.parse(el.textContent) : {}; for (const d of form.querySelectorAll('[data-d]')) d.textContent = cx[d.dataset.d] || ''; if (run) run.hidden = !cx.run || !['pasang', 'komplit', 'paket', 'portable'].includes(val('kebutuhan')); restep(); } /** Owner #92: the charging facts live in their own section under the calculator; the fragment carries them. */ const statsSec = document.getElementById('stats'), statsIn = document.getElementById('stats-in'); function stats() { const s = result.querySelector('[data-stats]'); if (!statsSec) return; statsIn.innerHTML = s && !result.hidden ? s.innerHTML : ''; statsSec.hidden = !statsIn.innerHTML; s?.remove(); } function restep() { const cur = steps[i]; steps = all.filter(applies); i = Math.max(0, steps.indexOf(cur)); } let steps = all.filter(applies); const back = form.querySelector('[data-back]'); const next = form.querySelector('[data-next]'); let i = 0, timer = 0, seq = 0; function show(n) { i = Math.max(0, Math.min(steps.length - 1, n)); all.forEach((s) => s.classList.toggle('on', s === steps[i])); bar.style.setProperty('--p', String((i + 1) / steps.length)); back.style.visibility = i === 0 ? 'hidden' : 'visible'; next.textContent = i === steps.length - 1 ? 'Lihat hasil' : 'Lanjut'; } function query() { const p = new URLSearchParams(); for (const [k, v] of new FormData(form)) if (v !== '') p.set(k, String(v)); return p.toString(); } async function refresh() { const q = query(); history.replaceState(null, '', q ? '/cek-harga?' + q : '/cek-harga'); const my = ++seq; try { const res = await fetch('/cek-harga/hasil?' + q, { signal: AbortSignal.timeout(6000) }); if (!res.ok) throw new Error('http ' + res.status); const html = await res.text(); // The result stays hidden until every question is answered (the server marks an unfinished one with ). if (my === seq) { result.innerHTML = html; result.hidden = html.startsWith(''); prices(); stats(); bindLead(); } } catch { if (my === seq) result.insertAdjacentHTML('afterbegin', '

Hasil belum bisa dimuat. Periksa koneksi lalu coba lagi.

'); } } form.addEventListener('change', (e) => { if (e.target.name === 'mobil') sendQ('cek-mobil', e.target.value); // which cars people price (owner #44) if (e.target.name === 'kota') sendQ('cek-kota', e.target.value); clearTimeout(timer); timer = setTimeout(refresh, 150); restep(); if (e.target.type === 'radio' && i < steps.length - 1) show(i + 1); // a choice moves on by itself else show(i); }); next.addEventListener('click', () => { if (i < steps.length - 1) return show(i + 1); const open = steps.find((f) => !answered(f)); if (open) return show(steps.indexOf(open)); // a question left open: go back to it instead of an empty result refresh(); result.scrollIntoView({ behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth', block: 'start' }); }); back.addEventListener('click', () => show(i - 1)); function bindLead() { const lead = document.getElementById('lead'); if (!lead || lead.dataset.bound) return; lead.dataset.bound = '1'; const err = document.getElementById('lead-err'); lead.addEventListener('submit', async (e) => { e.preventDefault(); err.hidden = true; const data = Object.fromEntries(new FormData(lead)); const btn = lead.querySelector('button[type=submit]'); btn.disabled = true; const r = await api('/api/lead', { method: 'POST', body: data, headers: { accept: 'application/json' }, timeout: 8000 }); btn.disabled = false; if (!r.ok) { err.textContent = r.data?.error || 'Gagal mengirim. Periksa koneksi lalu coba lagi.'; err.hidden = false; return; } const wa = document.querySelector('.sbar .btn-wa')?.getAttribute('href')?.split('?')[0] || 'https://wa.me/'; const text = encodeURIComponent(`Halo, saya ${data.nama}. Saya sudah isi cek harga (kode ${r.data.code}). Berikut 5 foto saya:`); lead.outerHTML = `
Terima kasih, data sudah kami terima.

Kode: ${r.data.code}. Dua langkah lagi untuk harga final, keduanya gratis:

1. Kirim 5 foto via WhatsApp2. Pilih jadwal video call
`; // Name + number wait on this device for the booking form (owner #71): never put in a URL. store.set('vc', { nama: data.nama, wa: data.wa, mobil: data.mobil, kota: data.kota, t: Date.now() }); }); } // Arriving from the home form (car + city already chosen): start at the first question not answered yet (owner #59). result.querySelector('[data-stats]')?.remove(); // the server already rendered the facts section const cx0 = result.querySelector('#cx'); if (cx0) { cx = JSON.parse(cx0.textContent); steps = all.filter(applies); } const answered = (f) => [...f.querySelectorAll('select,input')].some((x) => (x.type === 'radio' ? x.checked : x.type !== 'hidden' && x.value !== '')); const first = steps.findIndex((f) => !answered(f)); show(first < 0 ? 0 : first); bindLead();