const $ = (id) => document.getElementById(id);
let prospects = [];
let runs = [];
let activePoll = null;
async function api(path, options = {}) {
const response = await fetch(path, {
...options,
headers: { "Content-Type": "application/json", ...(options.headers || {}) },
});
const body = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(body.error || body.message || `Request failed (${response.status})`);
return body;
}
function esc(value) {
return String(value ?? "").replace(/[&<>"']/g, (char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[char]));
}
function formatDate(value) {
if (!value) return "—";
const date = new Date(value);
if (Number.isNaN(date.getTime())) return String(value).replace("T", " ").replace("+00:00", "");
return new Intl.DateTimeFormat(undefined, { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }).format(date);
}
function plural(count, word) { return `${count} ${word}${count === 1 ? "" : "s"}`; }
function renderStats(stats = {}) {
$("total").textContent = stats.total ?? prospects.length;
$("pending").textContent = stats.pending ?? prospects.filter((item) => item.review_status === "pending").length;
$("approved").textContent = stats.approved ?? prospects.filter((item) => item.review_status === "approved").length;
$("running").textContent = stats.running ?? runs.filter((item) => ["queued", "running"].includes(item.status)).length;
const latest = runs[0];
$("lastRun").textContent = latest ? `last #${latest.id} · ${formatDate(latest.created_at)}` : "no recent run";
}
function scoreClass(score) {
if (score >= 75) return "high";
if (score >= 55) return "medium";
return "low";
}
function renderExplorer() {
const query = $("search").value.trim().toLowerCase();
const status = $("status").value;
const rows = prospects.filter((item) => {
const haystack = [item.name, item.domain, item.category, item.address, item.phone, item.emails].join(" ").toLowerCase();
return (!query || haystack.includes(query)) && (!status || item.review_status === status);
});
$("resultCount").textContent = `${plural(rows.length, "place")} ${query || status ? "matching" : "in catalogue"}`;
$("explorerList").innerHTML = rows.length ? rows.map((item) => {
const score = Number(item.opportunity_score || 0);
const website = item.website ? `${esc(item.domain || item.website)} ↗` : `No website found`;
const maps = item.maps_url ? `Open Maps ↗` : "";
const contact = [item.phone && `☎ ${esc(item.phone)}`, item.emails && `✉ ${esc(item.emails)}`].filter(Boolean).join("");
return `${esc(item.name)}
${query || status ? "Try a different search or clear the status filter." : "Run your first discovery above to bring places into the explorer."}
${run && run.error ? esc(run.error) : "Start a search to see progress here."}
${esc(runStatusLabel(run))} · ${esc(run.found || 0)} places seen
No runs yet.
'; renderStats(); } async function loadProspects() { prospects = (await api("/api/prospects")).items || []; renderExplorer(); } async function loadRuns() { runs = (await api("/api/runs")).items || []; renderRuns(); } async function loadStats() { renderStats(await api("/api/stats")); } async function loadConfig() { const config = await api("/api/config"); $("backendLabel").textContent = config.backend === "gmaps" ? "Maps worker" : "Browser fallback"; $("sourceLabel").textContent = config.ready ? "Maps worker ready" : "Setup required"; $("sourceSub").textContent = config.ready ? "Google Maps scraper connected" : "Add your API key to continue"; $("sourceDot").classList.toggle("offline", !config.ready); $("setupNotice").hidden = Boolean(config.ready); if (!config.gmaps_url) $("setupText").textContent = "Start the bundled Maps worker with Docker, then reload this page."; else if (!config.gmaps_api_key) $("setupText").textContent = "Create an API key in the Maps worker admin screen, add it as GMAPS_API_KEY, then restart the stack."; } async function refreshAll() { $("updated").textContent = "Refreshing…"; try { await Promise.all([loadConfig(), loadProspects(), loadRuns(), loadStats()]); $("updated").textContent = `Updated ${new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}`; } catch (error) { $("updated").textContent = "Refresh failed"; $("discoverMessage").textContent = error.message; $("discoverMessage").className = "form-message error"; } } async function pollRun(runId) { if (activePoll) clearTimeout(activePoll); try { const run = await api(`/api/runs/${runId}`); const index = runs.findIndex((item) => item.id === run.id); if (index >= 0) runs[index] = run; else runs.unshift(run); renderRuns(); if (["queued", "running"].includes(run.status)) activePoll = setTimeout(() => pollRun(runId), 2000); else { await Promise.all([loadProspects(), loadStats()]); $("discoverBtn").disabled = false; $("discoverMessage").textContent = run.status === "succeeded" ? `Complete · ${run.added} new ${run.added === 1 ? "place" : "places"} added.` : `Run failed · ${run.error || "Unknown error"}`; $("discoverMessage").className = `form-message ${run.status === "succeeded" ? "success" : "error"}`; } } catch (error) { $("discoverMessage").textContent = error.message; $("discoverMessage").className = "form-message error"; $("discoverBtn").disabled = false; } } $("discoverForm").addEventListener("submit", async (event) => { event.preventDefault(); const button = $("discoverBtn"); const message = $("discoverMessage"); button.disabled = true; message.className = "form-message"; message.textContent = "Queueing Maps search…"; const payload = { category: $("category").value.trim(), keywords: $("keywords").value.trim(), location: $("location").value.trim(), max_results: Number($("max-results").value), include_email: $("include-email").checked, extra_reviews: $("extra-reviews").checked }; try { const run = await api("/api/discover", { method: "POST", body: JSON.stringify(payload) }); runs.unshift(run); renderRuns(); message.textContent = "Search queued · this can take a few minutes."; await pollRun(run.id); } catch (error) { button.disabled = false; message.textContent = `Could not start run · ${error.message}`; message.className = "form-message error"; } }); $("explorerList").addEventListener("change", async (event) => { const id = event.target.dataset.review; if (!id) return; event.target.disabled = true; try { const updated = await api(`/api/prospects/${id}/review`, { method: "PATCH", body: JSON.stringify({ status: event.target.value }) }); const index = prospects.findIndex((item) => item.id === updated.id); if (index >= 0) prospects[index] = updated; renderExplorer(); await loadStats(); } catch (error) { event.target.disabled = false; alert(error.message); } }); $("search").addEventListener("input", renderExplorer); $("status").addEventListener("change", renderExplorer); $("refresh").addEventListener("click", loadProspects); $("runsRefresh").addEventListener("click", loadRuns); $("refreshAll").addEventListener("click", refreshAll); $("showRuns").addEventListener("click", (event) => { event.preventDefault(); $("runs").scrollIntoView({ behavior: "smooth", block: "center" }); }); refreshAll().catch((error) => { $("explorerList").innerHTML = `${esc(error.message)}