Add Coremarket: Federated Core VM sizing and cloud pricing app

Dockerised FastAPI web app that sizes a VM for a selection of Federated
Computer apps (Base/Good/Better/Best tiers or custom) and prices it across
14 cloud providers and ~250 regions, grouped by continent.

- Sizing model per app with shared databases, headroom and disk growth
- Live pricing from Vultr, Akamai/Linode and Azure (DigitalOcean and
  Hetzner with tokens); dated catalog for the rest
- Hand-maintained Contabo price sheet with editor and table paste,
  including the one-time setup fee
- HIPAA/SOC2/PCI DSS/GDPR status, SMTP port 25, IPv4 and egress notes
- Estimated latency to 40 cities, real RTT via Globalping probes
- Versioned REST API (/api/v1) with OpenAPI docs and CSV export
- Accounts with admin/user roles, first admin from ADMIN_USERNAME /
  ADMIN_PASSWORD, per-account API keys, SQLite storage

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 21:36:51 -07:00
co-authored by Claude Opus 5.5
commit 1bb2a299c7
24 changed files with 3801 additions and 0 deletions
+621
View File
@@ -0,0 +1,621 @@
"use strict";
const $ = (s, el = document) => el.querySelector(s);
const $$ = (s, el = document) => [...el.querySelectorAll(s)];
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
const usd = (n) => (n == null ? "-" : "$" + Number(n).toFixed(2));
const S = {
cat: null, apps: new Set(), cont: new Set(), comp: new Set(), prov: new Set(),
cities: new Set(["nyc", "chi", "lax", "dfw"]), data: null, sort: { key: "total", dir: 1 },
override: {}, preset: null,
};
const COMP = [["hipaa", "HIPAA"], ["soc2", "SOC2"], ["pci", "PCI DSS"], ["gdpr", "GDPR"]];
const API = "/api/v1";
// Calls the Coremarket API with the browser session. The X-Coremarket header marks the request as
// coming from this page (the server rejects cookie-authenticated writes without it).
async function api(path, body, method) {
const r = await fetch(API + path, {
method: method || (body !== undefined ? "POST" : "GET"),
headers: { "Content-Type": "application/json", "X-Coremarket": "1" },
body: body !== undefined ? JSON.stringify(body) : undefined,
});
if (r.status === 401 && !path.startsWith("/auth/")) { // session expired
location.href = "/login?next=" + encodeURIComponent(location.pathname);
throw new Error("signed out");
}
if (!r.ok) {
let msg = (await r.text()).slice(0, 400);
try { const d = JSON.parse(msg).detail; msg = typeof d === "string" ? d : d.map((x) => x.msg).join("; "); } catch (_) {}
throw new Error(msg);
}
return r.json();
}
function chip(container, label, on, toggle, title = "") {
const c = document.createElement("span");
c.className = "chip" + (on ? " on" : "");
c.textContent = label;
c.title = title;
c.onclick = () => { toggle(); c.classList.toggle("on"); };
container.appendChild(c);
}
// ------------------------------------------------------------------ init
async function init() {
S.me = await api("/auth/me");
applyRole();
initAccountMenu();
S.cat = await api("/catalog");
$("#coreList").textContent = S.cat.core.join(", ");
renderLiveStatus();
const sel = $("#tierSelect");
sel.innerHTML = `<option value="">Custom selection</option>` + Object.entries(S.cat.presets).map(([k, p]) =>
`<option value="${esc(k)}" title="${esc(p.label)}">${esc(p.label.replace(/^Federated /, ""))} · ${p.apps.length} apps${p.federated_price ? ` · $${p.federated_price}/mo` : ""}</option>`).join("");
sel.onchange = () => {
S.preset = sel.value || null;
if (S.preset) S.apps = new Set(S.cat.presets[S.preset].apps);
renderApps(); requote();
};
$("#clearApps").onclick = () => { S.apps.clear(); setPreset(null); renderApps(); requote(); };
S.cat.continents.forEach((c) => chip($("#contFilter"), c, false, () => tog(S.cont, c)));
COMP.forEach(([k, l]) => chip($("#compFilter"), l, false, () => tog(S.comp, k)));
S.cat.providers.forEach((p) => chip($("#provFilter"), p.name.replace(/ \(.*\)/, ""), false, () => tog(S.prov, p.id)));
S.cat.cities.forEach((c) => chip($("#cityFilter"), c.name, S.cities.has(c.id), () => { tog(S.cities, c.id, false); render(); }));
$("#appSearch").oninput = renderApps;
$$("#concurrent,#named,#headroom,#growth,#extraDisk,#allowBurst,#dedicatedOnly,#allowArm,#allowPartial,#needSmtp")
.forEach((el) => (el.onchange = () => requote()));
$("#bestPerProvider").onchange = render;
$("#maxRtt").oninput = render;
$$(".tabs button[data-tab]").forEach((b) => (b.onclick = () => {
$$(".tabs button[data-tab]").forEach((x) => x.classList.toggle("active", x === b));
$$(".tab").forEach((t) => t.classList.toggle("hidden", t.id !== "tab-" + b.dataset.tab));
}));
$("#csvBtn").onclick = exportCsv;
$("#refreshBtn").onclick = refreshLive;
$("#editContaboBtn").onclick = () => openEditor("contabo");
S.apps = new Set(S.cat.presets.good.apps); setPreset("good");
renderApps();
renderNotes();
requote();
}
function setPreset(k) { S.preset = k; $("#tierSelect").value = k || ""; }
function tog(set, v, re = true) { set.has(v) ? set.delete(v) : set.add(v); if (re) requote(); }
function renderLiveStatus() {
const st = S.cat.live_status;
const live = S.cat.providers.filter((p) => p.price_source.startsWith("live")).map((p) => p.name.split(" ")[0]);
$("#liveStatus").textContent = live.length ? `Live prices: ${live.join(", ")}` : `Catalog prices as of ${S.cat.catalog_date}`;
$("#liveStatus").title = st ? Object.entries(st).map(([k, v]) => `${k}: ${v}`).join("\n") : "";
}
async function refreshLive() {
const b = $("#refreshBtn");
b.disabled = true; b.textContent = "Refreshing...";
try {
const r = await api("/prices/refresh", {});
S.cat = await api("/catalog");
renderLiveStatus(); renderNotes(); requote();
alert("Live price refresh:\n" + Object.entries(r.status).map(([k, v]) => `${k}: ${v}`).join("\n"));
} catch (e) { alert("Refresh failed: " + e.message); }
b.disabled = false; b.textContent = "Refresh live prices";
}
function renderApps() {
const q = $("#appSearch").value.toLowerCase();
const box = $("#appList");
box.innerHTML = "";
for (const cat of S.cat.categories) {
const apps = cat.apps.filter((a) => !q || a.name.toLowerCase().includes(q));
if (!apps.length) continue;
const d = document.createElement("details");
d.className = "cat";
const n = apps.filter((a) => S.apps.has(a.id)).length;
d.open = !!q || (cat.name !== "On Demand") ;
d.innerHTML = `<summary>${esc(cat.name)} <span class="muted small">${n}/${apps.length}</span></summary>`;
for (const a of apps) {
const l = document.createElement("label");
l.className = "app";
l.innerHTML = `<input type="checkbox" ${S.apps.has(a.id) ? "checked" : ""}><span>${esc(a.name)}${a.note ? `<small>${esc(a.note)}</small>` : ""}</span>`;
l.querySelector("input").onchange = (e) => { e.target.checked ? S.apps.add(a.id) : S.apps.delete(a.id); setPreset(null); requote(); };
d.appendChild(l);
}
box.appendChild(d);
}
}
// ------------------------------------------------------------------ quote
let qTimer;
function requote() { clearTimeout(qTimer); qTimer = setTimeout(doQuote, 150); }
async function doQuote() {
const body = {
apps: [...S.apps],
concurrent: +$("#concurrent").value || 5,
named: +$("#named").value || 10,
headroom: (+$("#headroom").value || 0) / 100,
disk_growth: (+$("#growth").value || 0) / 100,
extra_disk_gb: +$("#extraDisk").value || 0,
allow_burstable: $("#allowBurst").checked,
dedicated_only: $("#dedicatedOnly").checked,
allow_arm: $("#allowArm").checked,
allow_partial_compliance: $("#allowPartial").checked,
require_smtp: $("#needSmtp").checked,
continents: [...S.cont], compliance: [...S.comp], providers: [...S.prov],
override: S.override,
};
try { S.data = await api("/quote", body); } catch (e) { $("#sizing").textContent = "Error: " + e.message; return; }
renderSizing();
render();
}
function renderSizing() {
const { sizing, need } = S.data;
const preset = S.preset && S.cat.presets[S.preset];
const ovr = (k, v) => `<input class="ovr" data-k="${k}" type="number" min="1" placeholder="${v}" value="${S.override[k] ?? ""}" title="Override">`;
$("#sizing").innerHTML = `
<div>
<div class="spec">
<div>vCPU<b>${need.vcpu}</b>${ovr("vcpu", sizing.need.vcpu)}</div>
<div>RAM GB<b>${need.ram_gb}</b>${ovr("ram_gb", sizing.need.ram_gb)}</div>
<div>Disk GB<b>${need.disk_gb}</b>${ovr("disk_gb", sizing.need.disk_gb)}</div>
</div>
<p class="small">Raw demand ${sizing.raw.cpu} vCPU / ${sizing.raw.ram_gb} GB / ${sizing.raw.disk_gb} GB, plus headroom and growth.<br>
Shape: <b>${esc(sizing.family)}</b>. Nearest standard size: ${sizing.standard.vcpu} vCPU / ${sizing.standard.ram_gb} GB.</p>
${preset && preset.federated_price ? `<p class="cmp">Compare: <b>${esc(preset.label)}</b> hosted by Federated is <b>$${preset.federated_price}/mo</b> (${preset.storage_gb ? `${preset.storage_gb} GB storage, ` : ""}managed, backups included).</p>` : ""}
${sizing.needs_smtp ? `<div class="warn small">The email server needs outbound TCP 25. Check the SMTP column: "blocked" clouds need an external relay (e.g. SES, Postmark, Mailgun).</div>` : ""}
</div>
<div class="breakdown">
<table><thead><tr><th>Component</th><th class="num">RAM MB</th><th class="num">vCPU</th><th class="num">Disk GB</th></tr></thead><tbody>
${sizing.lines.map((l) => `<tr><td>${esc(l.name)} ${l.kind === "core" ? '<span class="muted small">core</span>' : l.kind === "shared" ? '<span class="muted small">shared</span>' : ""}</td>
<td class="num">${Math.round(l.ram_mb)}</td><td class="num">${l.cpu.toFixed(2)}</td><td class="num">${l.disk_gb.toFixed(1)}</td></tr>`).join("")}
</tbody></table>
${sizing.notes.length ? `<details class="small"><summary>Sizing notes (${sizing.notes.length})</summary><ul>${sizing.notes.map((n) => `<li>${esc(n)}</li>`).join("")}</ul></details>` : ""}
</div>`;
$$(".ovr").forEach((el) => (el.onchange = () => {
const v = +el.value; v ? (S.override[el.dataset.k] = v) : delete S.override[el.dataset.k]; requote();
}));
}
// ------------------------------------------------------------------ render
function latStats(r) {
const ids = [...S.cities];
if (!ids.length) return { avg: null, max: null };
const v = ids.map((id) => r.latency[id]);
return { avg: Math.round(v.reduce((a, b) => a + b, 0) / v.length), max: Math.max(...v) };
}
function filtered() {
if (!S.data) return [];
const max = +$("#maxRtt").value;
return S.data.results.map((r) => ({ ...r, ...latStats(r) })).filter((r) => !max || r.max == null || r.max <= max);
}
function sorted(rows) {
const { key, dir } = S.sort;
return [...rows].sort((a, b) => ((a[key] > b[key]) - (a[key] < b[key])) * dir || a.total - b.total);
}
const badges = (c) => COMP.map(([k, l]) => `<span class="badge ${c[k]}" title="${l}: ${c[k]}">${l.split(" ")[0]}</span>`).join("");
const latColor = (ms) => `hsl(${Math.max(0, 130 - ms * 0.6)}, 60%, 45%)`;
const COLS = [
["provider", "Provider"], ["location", "Location"], ["region", "Region code"], ["model", "VM model"],
["vcpu", "vCPU", 1], ["ram_gb", "RAM GB", 1], ["disk_gb", "Disk GB", 1], ["base_price", "VM $/mo", 1],
["extra_storage_cost", "+Storage $/mo", 1], ["ipv4", "IPv4 $/mo", 1], ["recurring", "Monthly $/mo", 1], ["setup_fee", "Setup $ (one-time)", 1],
["total", "Total $ (1st month)", 1],
["storage_price_gb", "Add'l storage $/GB-mo", 1], ["compliance", "Compliance"], ["smtp25", "SMTP 25"],
["avg", "RTT avg ms", 1], ["max", "RTT worst ms", 1],
];
function table(rows) {
const head = COLS.map(([k, l, n]) => `<th class="${n ? "num" : ""}" data-k="${k}">${l}${S.sort.key === k ? (S.sort.dir > 0 ? " ▲" : " ▼") : ""}</th>`).join("");
const body = rows.map((r, i) => `<tr class="row" data-i="${i}">
<td>${esc(r.provider)}</td><td>${esc(r.location)}, ${esc(r.country)}</td><td class="muted">${esc(r.region)}</td>
<td title="${esc(r.cpu_type)} ${esc(r.arch)} ${esc(r.plan_note)}">${esc(r.model)} <span class="muted small">${r.cpu_type === "dedicated" ? "ded" : r.cpu_type === "burstable" ? "burst" : ""}${r.arch !== "x86_64" ? " arm" : ""}</span></td>
<td class="num">${r.vcpu}</td><td class="num">${r.ram_gb}</td>
<td class="num">${r.disk_gb || "-"}${r.extra_storage_gb ? `<span class="muted"> +${r.extra_storage_gb}</span>` : ""}</td>
<td class="num">${usd(r.base_price)}</td><td class="num">${r.extra_storage_cost ? usd(r.extra_storage_cost) : "-"}</td>
<td class="num">${r.ipv4 ? usd(r.ipv4) : "-"}</td>
<td class="num">${usd(r.recurring)}</td><td class="num">${r.setup_fee ? usd(r.setup_fee) : "-"}</td>
<td class="num total ${"conf-" + r.price_confidence}" title="Price confidence: ${r.price_confidence}; source: ${esc(r.price_source)}">${usd(r.total)}${r.price_confidence === "low" ? "*" : ""}</td>
<td class="num">${r.storage_price_gb != null ? "$" + r.storage_price_gb.toFixed(3) : `<span class="muted" title="${esc(r.storage_name)}">n/a</span>`}</td>
<td>${badges(r.compliance)}</td><td>${esc(r.smtp25)}</td>
<td class="lat">${r.avg ?? "-"}</td><td class="lat" style="color:${r.max != null ? latColor(r.max) : ""}">${r.max ?? "-"}</td>
</tr>`).join("");
return `<table><thead><tr>${head}</tr></thead><tbody>${body}</tbody></table>`;
}
function wire(container, rows) {
$$("th[data-k]", container).forEach((th) => (th.onclick = () => {
const k = th.dataset.k;
S.sort = { key: k, dir: S.sort.key === k ? -S.sort.dir : 1 };
render();
}));
$$("tr.row", container).forEach((tr) => (tr.onclick = () => showDetail(rows[+tr.dataset.i])));
}
function render() {
const rows = filtered();
$("#count").textContent = `${rows.length} region options`;
// by region
const br = $("#tab-byregion");
br.innerHTML = "";
const onlyBest = $("#bestPerProvider").checked;
for (const cont of S.cat.continents) {
let rs = sorted(rows.filter((r) => r.continent === cont));
if (onlyBest) {
const seen = new Set();
rs = [...rs].sort((a, b) => a.total - b.total).filter((r) => !seen.has(r.provider_id) && seen.add(r.provider_id));
rs = sorted(rs);
}
const sec = document.createElement("div");
sec.innerHTML = `<h3>${esc(cont)} <span class="muted small">${rs.length ? `from ${usd(Math.min(...rs.map((r) => r.total)))} first month` : "no matching options"}</span></h3>${rs.length ? table(rs) : ""}`;
br.appendChild(sec);
wire(sec, rs);
}
if (S.cat.continents.includes("Asia")) {
br.insertAdjacentHTML("beforeend", `<p class="muted small">Asia includes the Middle East (Israel, UAE). * = low price confidence (estimate, verify with provider).</p>`);
}
// all
const all = sorted(rows);
$("#tab-all").innerHTML = table(all);
wire($("#tab-all"), all);
// matrix
const top = sorted(rows).slice(0, 120);
const cities = S.cat.cities;
$("#tab-matrix").innerHTML = `<p class="muted small">Estimated round-trip time (ms) from each VM region to each city. Model: great-circle distance x 1.3 route factor at 204 km/ms in fibre + 3 ms, plus per-market penalties and +35 ms across the mainland-China border. Use the detail view to measure real RTT for regions with a probe endpoint. Showing ${top.length} rows in current sort order.</p>
<table class="matrix"><thead><tr><th>Provider</th><th>Location</th><th class="num">$/mo</th>${cities.map((c) => `<th class="city">${esc(c.name)}</th>`).join("")}</tr></thead><tbody>
${top.map((r, i) => `<tr class="row" data-i="${i}"><td>${esc(r.provider.split(" (")[0])}</td><td>${esc(r.location)}</td><td class="num">${usd(r.total)}</td>
${cities.map((c) => { const v = r.latency[c.id]; return `<td class="lat" style="background:${latColor(v)};color:#fff">${v}</td>`; }).join("")}</tr>`).join("")}
</tbody></table>`;
$$("tr.row", $("#tab-matrix")).forEach((tr) => (tr.onclick = () => showDetail(top[+tr.dataset.i])));
}
// ------------------------------------------------------------------ detail
function showDetail(r) {
const p = S.cat.providers.find((x) => x.id === r.provider_id);
const cities = S.cat.cities;
$("#detailBody").innerHTML = `
<h2>${esc(r.provider)}: ${esc(r.location)}, ${esc(r.country)} <span class="muted">(${esc(r.region)})</span></h2>
<p><b>${esc(r.model)}</b> | ${r.vcpu} vCPU (${esc(r.cpu_type)}, ${esc(r.arch)}) | ${r.ram_gb} GB RAM | ${r.disk_gb || 0} GB included disk
${r.extra_storage_gb ? `+ ${r.extra_storage_gb} GB ${esc(r.storage_name)}` : ""}<br>
VM ${usd(r.base_price)} + storage ${usd(r.extra_storage_cost)} + IPv4 ${usd(r.ipv4)} = <b>${usd(r.recurring)}/month</b>
${r.setup_fee ? ` + ${usd(r.setup_fee)} one-time setup = <b>${usd(r.total)} first month</b>` : ""}
<span class="muted">(${(r.recurring * 12 + r.setup_fee).toFixed(0)} USD first year; price source: ${esc(r.price_source)}, confidence ${esc(r.price_confidence)})</span></p>
<p>Additional storage: ${r.storage_price_gb != null ? `$${r.storage_price_gb.toFixed(3)}/GB-month (${esc(r.storage_name)})` : esc(r.storage_name)}.
Egress: ${esc(r.egress.note || (r.egress.per_gb != null ? `$${r.egress.per_gb}/GB after ${r.egress.included_gb ?? 0} GB` : "-"))}. SMTP port 25: ${esc(r.smtp25)}.</p>
<p>${badges(r.compliance)} <span class="small">${esc(p.compliance_note)}</span></p>
${r.alternatives.length ? `<h3>Next-best plans in this region</h3><table><tr><th>Model</th><th class="num">vCPU</th><th class="num">RAM</th><th class="num">Disk</th><th class="num">Total $ (1st month)</th></tr>
${r.alternatives.map((a) => `<tr><td>${esc(a.model)} <span class="muted small">${esc(a.cpu_type)}</span></td><td class="num">${a.vcpu}</td><td class="num">${a.ram_gb}</td><td class="num">${a.disk_gb}${a.extra_storage_gb ? "+" + a.extra_storage_gb : ""}</td><td class="num">${usd(a.total)}</td></tr>`).join("")}</table>` : ""}
<h3>Latency to all cities (estimated RTT ms)</h3>
${r.ping_host ? `<p class="small muted">Real measurement uses Globalping community probes (TCP ping to ${esc(r.ping_host)}). Free tier is rate-limited.</p>` : `<p class="small muted">No public probe endpoint is configured for this region, so only estimates are shown.</p>`}
<table><tr><th>City</th><th class="num">Est. RTT</th>${r.ping_host ? "<th>Measured</th>" : ""}</tr>
${cities.map((c) => `<tr><td>${esc(c.name)}, ${esc(c.country)}</td><td class="lat" style="color:${latColor(r.latency[c.id])}">${r.latency[c.id]}</td>
${r.ping_host ? `<td><button class="ghost small meas" data-c="${c.id}">measure</button> <span id="m-${c.id}"></span></td>` : ""}</tr>`).join("")}
</table>`;
$$(".meas", $("#detailBody")).forEach((b) => (b.onclick = async () => {
const out = $("#m-" + b.dataset.c);
b.disabled = true; out.textContent = "measuring...";
try {
const m = await api("/latency/measure", { host: r.ping_host, city: b.dataset.c });
out.innerHTML = `<b>${m.min_ms} ms</b>${m.probe_scope === "country" ? ' <span class="small">(no probe in this city; country-level)</span>' : ""} <span class="muted small">${m.results.map((x) => esc(x.probe) + ": " + x.avg_ms).join("; ")}</span>`;
} catch (e) { out.textContent = "failed: " + e.message.slice(0, 120); }
b.disabled = false;
}));
$("#detail").showModal();
}
// ------------------------------------------------------------------ notes
function renderNotes() {
const ps = S.cat.providers;
$("#tab-notes").innerHTML = `<div class="notes">
<h3>Methodology</h3>
<ul>
<li><b>Sizing</b>: each app has an idle footprint plus per-concurrent-user RAM/CPU and per-named-user disk. Shared databases (PostgreSQL, MariaDB, Redis, etc.) are counted once. OS + Docker reserve 1 GB RAM and 30 GB disk (Federated reserves 30 GB). Headroom and growth are then applied, and the minimum is 2 vCPU / 2 GB / 40 GB.</li>
<li><b>Matching</b>: in every region, the cheapest plan with at least the required vCPU and RAM wins. If its bundled disk is too small, block storage is added at that provider's rate. Providers without block storage must fit the disk in the plan. Public IPv4 charges are included in the total.</li>
<li><b>Prices</b>: USD per month, on-demand. "Total (1st month)" adds any one-time setup fee (currently Contabo only) to the monthly cost, Linux, before tax/VAT, no commitment discounts (1-3 year reservations typically save 30-60% on AWS/Azure/GCP/OCI). Live API pricing is used where available (${ps.filter((p) => p.live).map((p) => esc(p.name)).join(", ")}). Otherwise the catalog is dated ${esc(S.cat.catalog_date)}. ${esc(S.cat.fx_note)}</li>
<li><b>Latency</b>: modelled from geography (see Latency matrix tab). Real routes vary by ISP. Use "measure" in the detail view for live probes.</li>
<li><b>Compliance</b>: provider-level attestations for IaaS compute. "yes" = attested, with a BAA available for HIPAA. "partial" = only some products/regions, or self-declared. You remain responsible for your own controls, and HIPAA requires a signed BAA.</li>
</ul>
<h3>Providers: API documentation and references</h3>
<table><thead><tr><th>Provider</th><th>API docs</th><th>Pricing API</th><th>Pricing page</th><th>Compliance</th><th>Price source</th><th>Add'l storage</th><th>IPv4</th><th>Egress</th><th>SMTP 25</th></tr></thead><tbody>
${ps.map((p) => `<tr>
<td><b>${esc(p.name)}</b><br><span class="muted small">${p.region_count} regions</span></td>
<td><a href="${esc(p.api_docs)}" target="_blank" rel="noopener">API reference</a>${p.api_docs_note ? `<br><span class="small muted">${esc(p.api_docs_note)}</span>` : ""}</td>
<td>${p.pricing_api ? `<a href="${esc(p.pricing_api)}" target="_blank" rel="noopener">pricing API</a>` : '<span class="muted">none public</span>'}</td>
<td><a href="${esc(p.pricing_url)}" target="_blank" rel="noopener">pricing</a></td>
<td>${badges(p.compliance)}<br><a class="small" href="${esc(p.compliance_url)}" target="_blank" rel="noopener">compliance page</a></td>
<td class="small">${esc(p.price_source)}<br><span class="conf-${p.price_confidence}">confidence: ${p.price_confidence}</span>${p.manual && isAdmin() ? `<br><button class="ghost small edit-manual" data-p="${esc(p.id)}">Edit prices</button>` : ""}</td>
<td class="small">${p.setup_fee ? `<b>Setup fee ${usd(p.setup_fee.usd)}</b>: ${esc(p.setup_fee.note)}<br>` : ""}${p.storage.price_gb != null ? `$${p.storage.price_gb}/GB-mo` : ""} ${esc(p.storage.name)}</td>
<td class="num">${p.ipv4_monthly ? usd(p.ipv4_monthly) : "incl."}</td>
<td class="small">${esc(p.egress.note || (p.egress.per_gb != null ? `$${p.egress.per_gb}/GB (${p.egress.included_gb ?? 0} GB free)` : ""))}</td>
<td>${esc(p.smtp25)}</td></tr>
<tr><td></td><td colspan="9" class="small muted" style="white-space:normal">${esc(p.compliance_note)}</td></tr>`).join("")}
</tbody></table></div>`;
$$(".edit-manual").forEach((b) => (b.onclick = () => openEditor(b.dataset.p)));
}
// ------------------------------------------------------------------ manual price editor
const num = (v) => { const m = String(v ?? "").replace(/,/g, ".").match(/-?\d+(\.\d+)?/); return m ? +m[0] : NaN; };
function parsePastedTable(text) {
// Accepts markdown/pipe, tab or CSV tables with a header row naming the columns.
const lines = text.split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !/^\|?\s*:?-{2,}/.test(l));
const split = (l) => (l.includes("|") ? l.replace(/^\|/, "").replace(/\|$/, "").split("|") : l.includes("\t") ? l.split("\t") : l.split(",")).map((c) => c.trim());
const hi = lines.findIndex((l) => /vcpu|cpu|core/i.test(l) && /ram|memory/i.test(l));
if (hi < 0) throw new Error("No header row with vCPU and RAM columns found.");
const hdr = split(lines[hi]).map((h) => h.toLowerCase());
const col = (re) => hdr.findIndex((h) => re.test(h));
const c = { code: col(/code|id|sku/), name: col(/name|plan|product/), vcpu: col(/vcpu|cpu|core/), ram: col(/ram|memory/),
disk: col(/storage|disk|ssd|nvme/), price: col(/price|€|\$|cost|month/), speed: col(/speed|port|bandwidth|network/) };
if (c.price < 0) throw new Error("No price column found.");
const plans = [];
for (const l of lines.slice(hi + 1)) {
const r = split(l);
const p = { code: c.code >= 0 ? r[c.code] : "", name: c.name >= 0 ? r[c.name] : "", vcpu: num(r[c.vcpu]), ram_gb: num(r[c.ram]),
disk_gb: c.disk >= 0 ? num(r[c.disk]) : 0, price: num(r[c.price]), cpu_type: "shared",
note: [c.disk >= 0 && /ssd|nvme/i.test(r[c.disk]) ? (r[c.disk].match(/ssd|nvme/i) || [""])[0].toUpperCase() : "", c.speed >= 0 ? r[c.speed] : ""].filter(Boolean).join(", ") };
if (!p.name) p.name = p.code || `Plan ${plans.length + 1}`;
if ([p.vcpu, p.ram_gb, p.price].some(isNaN)) continue;
plans.push(p);
}
if (!plans.length) throw new Error("No plan rows could be parsed.");
const cur = /€|eur/i.test(text) ? "EUR" : /\$|usd/i.test(text) ? "USD" : null;
return { plans, currency: cur };
}
async function openEditor(pid) {
const d = await api(`/providers/${pid}/price-sheet`);
const sh = d.sheet;
const body = $("#editorBody");
const planRow = (p = {}) => `<tr>
<td><input data-f="code" value="${esc(p.code ?? "")}"></td><td><input class="w-name" data-f="name" value="${esc(p.name ?? "")}"></td>
<td><input data-f="vcpu" type="number" min="1" value="${p.vcpu ?? ""}"></td><td><input data-f="ram_gb" type="number" min="0" step="any" value="${p.ram_gb ?? ""}"></td>
<td><input data-f="disk_gb" type="number" min="0" step="any" value="${p.disk_gb ?? ""}"></td><td><input data-f="price" type="number" min="0" step="0.01" value="${p.price ?? ""}"></td>
<td><select data-f="cpu_type"><option ${p.cpu_type !== "dedicated" ? "selected" : ""}>shared</option><option ${p.cpu_type === "dedicated" ? "selected" : ""}>dedicated</option></select></td>
<td><input class="w-note" data-f="note" value="${esc(p.note ?? "")}"></td><td><button class="ghost del" title="Remove">✕</button></td></tr>`;
body.innerHTML = `
<h2>Edit ${esc(d.provider)} prices</h2>
<p class="small muted">${d.is_default ? "Showing the built-in price sheet." : `Saved sheet, last updated ${esc(sh.updated_at)}.`}
Prices are per month before VAT. Saved changes apply to all quotes immediately.</p>
<div class="row-inline">
<label>Currency <select id="edCur"><option ${sh.currency === "EUR" ? "selected" : ""}>EUR</option><option ${sh.currency === "USD" ? "selected" : ""}>USD</option></select></label>
<label>USD per 1 EUR <input id="edFx" type="number" step="0.0001" min="0" value="${sh.fx}"></label>
<label>Setup fee (one-time, sheet currency) <input id="edSetup" type="number" step="0.01" min="0" value="${sh.setup_fee}"></label>
<label style="flex:1">Setup fee note <input id="edSetupNote" value="${esc(sh.setup_fee_note || "")}"></label>
</div>
<h3>Plans</h3>
<table id="edPlans"><thead><tr><th>Code</th><th>Name</th><th>vCPU</th><th>RAM GB</th><th>Disk GB</th><th>Price/mo</th><th>CPU</th><th>Note</th><th></th></tr></thead>
<tbody>${sh.plans.map(planRow).join("")}</tbody></table>
<button class="ghost" id="edAdd">+ Add plan</button>
<details style="margin-top:.6rem"><summary><b>Paste a table</b> <span class="small muted">(markdown, tab-separated or CSV, with a header row; replaces the plans above)</span></summary>
<textarea id="edPaste" placeholder="| Code | Name | vCPU | RAM | Storage | Speed | Price/mo |"></textarea>
<button class="ghost" id="edParse">Load pasted table</button> <span id="edParseMsg" class="small"></span>
</details>
<h3>Location surcharge per region (%)</h3>
<p class="small muted">Added to every plan price in that region. 0 = same price as the sheet.</p>
<table><thead><tr><th>Region</th><th>Code</th><th>Surcharge %</th></tr></thead><tbody>
${d.regions.map((r) => `<tr><td>${esc(r.label)}, ${esc(r.country)}</td><td class="muted">${esc(r.code)}</td>
<td><input class="edPct" data-r="${esc(r.code)}" type="number" step="any" value="${sh.region_surcharge_pct?.[r.code] ?? 0}" style="width:6em"></td></tr>`).join("")}
</tbody></table>
<p id="edErr" class="err small"></p>
<div class="actions"><button id="edSave">Save prices</button><button class="ghost" id="edCancel">Cancel</button>
<span class="spacer"></span><button class="ghost" id="edReset" title="Discard saved edits and use the built-in sheet">Reset to built-in</button></div>`;
const wireDel = () => $$(".del", body).forEach((b) => (b.onclick = () => b.closest("tr").remove()));
wireDel();
$("#edAdd").onclick = () => { $("#edPlans tbody").insertAdjacentHTML("beforeend", planRow()); wireDel(); };
$("#edParse").onclick = () => {
try {
const { plans, currency } = parsePastedTable($("#edPaste").value);
$("#edPlans tbody").innerHTML = plans.map(planRow).join(""); wireDel();
if (currency) $("#edCur").value = currency;
$("#edParseMsg").textContent = `Loaded ${plans.length} plans${currency ? ` (${currency})` : ""}. Review, then Save.`;
} catch (e) { $("#edParseMsg").textContent = e.message; }
};
$("#edCancel").onclick = () => $("#editor").close();
$("#edReset").onclick = async () => {
if (!confirm("Discard saved Contabo prices and go back to the built-in sheet?")) return;
try { await api(`/providers/${pid}/price-sheet`, undefined, "DELETE"); } catch (e) { alert("Not reset: " + e.message); return; }
$("#editor").close(); await afterPriceChange();
};
$("#edSave").onclick = async () => {
const plans = $$("#edPlans tbody tr").map((tr) => {
const o = {};
$$("[data-f]", tr).forEach((el) => { const f = el.dataset.f; o[f] = ["vcpu", "ram_gb", "disk_gb", "price"].includes(f) ? num(el.value) : el.value.trim(); });
return o;
});
const bad = plans.findIndex((p) => !p.name || [p.vcpu, p.ram_gb, p.price].some(isNaN));
if (bad >= 0) { $("#edErr").textContent = `Plan row ${bad + 1}: name, vCPU, RAM and price are required.`; return; }
plans.forEach((p) => { if (isNaN(p.disk_gb)) p.disk_gb = 0; });
const pct = {}; $$(".edPct", body).forEach((el) => (pct[el.dataset.r] = num(el.value) || 0));
const sheet = { currency: $("#edCur").value, fx: num($("#edFx").value), setup_fee: num($("#edSetup").value) || 0,
setup_fee_note: $("#edSetupNote").value.trim(), plans, region_surcharge_pct: pct };
try { await api(`/providers/${pid}/price-sheet`, sheet, "PUT"); }
catch (e) { $("#edErr").textContent = "Not saved: " + e.message; return; }
$("#editor").close(); await afterPriceChange();
};
$("#editor").showModal();
}
async function afterPriceChange() {
S.cat = await api("/catalog");
renderLiveStatus(); renderNotes(); requote();
}
// ------------------------------------------------------------------ accounts
const isAdmin = () => S.me?.role === "admin";
const when = (t) => (t ? new Date(t * 1000).toLocaleString() : "never");
function applyRole() {
$$(".admin-only").forEach((el) => el.classList.toggle("hidden", !isAdmin()));
$("#userBtn").textContent = `${S.me.username} ▾`;
$("#userInfo").textContent = `Signed in as ${S.me.username} (${S.me.role})`;
}
function initAccountMenu() {
const btn = $("#userBtn"), menu = $("#userMenu");
const close = () => { menu.classList.add("hidden"); btn.setAttribute("aria-expanded", "false"); };
btn.onclick = (e) => { e.stopPropagation(); menu.classList.toggle("hidden"); btn.setAttribute("aria-expanded", String(!menu.classList.contains("hidden"))); };
document.addEventListener("click", close);
document.addEventListener("keydown", (e) => e.key === "Escape" && close());
$$("#userMenu [data-act]").forEach((b) => (b.onclick = async () => {
close();
const act = b.dataset.act;
if (act === "keys") openKeys();
else if (act === "users") openUsers();
else if (act === "password") openPassword();
else if (act === "docs") window.open("/docs", "_blank", "noopener");
else if (act === "logout") { try { await api("/auth/logout", {}); } catch (_) {} location.href = "/login"; }
}));
}
function accountDialog(html) {
$("#accountBody").innerHTML = html;
if (!$("#account").open) $("#account").showModal();
return $("#accountBody");
}
async function openKeys(showAll = false, fresh = null) {
let keys, users = [];
try {
keys = await api(showAll ? "/keys?all=true" : "/keys");
if (isAdmin()) users = await api("/users");
} catch (e) { alert(e.message); return; }
const body = accountDialog(`
<h2>API keys</h2>
<p class="small muted">Send a key in the <code>X-API-Key</code> header (or <code>Authorization: Bearer</code>). A key acts with its
owner's role${isAdmin() ? "" : " (yours: user)"}. Keys are shown once, when created. Store them somewhere safe.</p>
${fresh ? `<div class="warn"><b>New key "${esc(fresh.name)}"${fresh.username ? ` for ${esc(fresh.username)}` : ""}: copy it now, it won't be shown again.</b>
<div class="newkey" id="newKey">${esc(fresh.key)}</div><button class="ghost small" id="copyKey">Copy</button> <span id="copyMsg" class="small"></span></div>` : ""}
<h3>Create a key</h3>
<div class="row-inline">
<label>Name <input id="kName" placeholder="e.g. CI pipeline" maxlength="100"></label>
<label>Expires after (days) <input id="kDays" type="number" min="1" max="3650" placeholder="never" style="width:8em"></label>
${isAdmin() ? `<label>For account <select id="kUser">${users.map((u) => `<option value="${u.id}" ${u.id === S.me.id ? "selected" : ""}>${esc(u.username)} (${u.role})</option>`).join("")}</select></label>` : ""}
<button id="kCreate">Create key</button>
</div>
<p id="kErr" class="err small"></p>
<h3>${showAll ? "All keys" : "Your keys"} ${isAdmin() ? `<label class="chk small" style="display:inline-flex;margin-left:1rem"><input type="checkbox" id="kAll" ${showAll ? "checked" : ""}> show every account's keys</label>` : ""}</h3>
${keys.length ? `<table><thead><tr><th>Name</th><th>Key</th>${showAll ? "<th>Account</th>" : ""}<th>Created</th><th>Expires</th><th>Last used</th><th></th></tr></thead><tbody>
${keys.map((k) => `<tr><td>${esc(k.name)}</td><td><code>${esc(k.prefix)}</code></td>${showAll ? `<td>${esc(k.username)}</td>` : ""}
<td>${when(k.created_at)}</td><td>${k.expires_at ? when(k.expires_at) + (k.expired ? ' <span class="tag">expired</span>' : "") : "never"}</td>
<td>${when(k.last_used)}</td><td><button class="ghost revoke" data-id="${k.id}" data-name="${esc(k.name)}">Revoke</button></td></tr>`).join("")}
</tbody></table>` : '<p class="muted">No keys yet.</p>'}`);
$("#copyKey")?.addEventListener("click", async () => {
try { await navigator.clipboard.writeText(fresh.key); $("#copyMsg").textContent = "Copied."; }
catch (_) { $("#copyMsg").textContent = "Select the key and copy it manually."; }
});
$("#kAll")?.addEventListener("change", (e) => openKeys(e.target.checked, fresh));
$("#kCreate").onclick = async () => {
const req = { name: $("#kName").value.trim() || "API key" };
const days = +$("#kDays").value; if (days) req.expires_days = days;
if (isAdmin()) req.user_id = +$("#kUser").value;
try { const k = await api("/keys", req); openKeys(showAll, k); }
catch (e) { $("#kErr").textContent = e.message; }
};
$$(".revoke", body).forEach((b) => (b.onclick = async () => {
if (!confirm(`Revoke API key "${b.dataset.name}"? Anything using it will stop working immediately.`)) return;
try { await api(`/keys/${b.dataset.id}`, undefined, "DELETE"); openKeys(showAll); } catch (e) { alert(e.message); }
}));
}
async function openUsers(note = "") {
let users;
try { users = await api("/users"); } catch (e) { alert(e.message); return; }
const body = accountDialog(`
<h2>Users</h2>
<p class="small muted">Admins manage accounts, all API keys and prices. Users can use Coremarket and manage their own API keys.
Disabled accounts can't sign in and their API keys stop working.</p>
<h3>Create an account</h3>
<div class="row-inline">
<label>Username <input id="uName" autocomplete="off" maxlength="64"></label>
<label>Password (min 10) <input id="uPass" type="password" autocomplete="new-password"></label>
<label>Role <select id="uRole"><option value="user">user</option><option value="admin">admin</option></select></label>
<button id="uCreate">Create account</button>
</div>
<p id="uMsg" class="small ${note.startsWith("Error") ? "err" : "ok"}">${esc(note)}</p>
<table><thead><tr><th>Username</th><th>Role</th><th>Status</th><th class="num">API keys</th><th>Last sign-in</th><th>Created</th><th></th></tr></thead><tbody>
${users.map((u) => {
const me = u.id === S.me.id;
return `<tr data-id="${u.id}" data-name="${esc(u.username)}">
<td>${esc(u.username)}${me ? ' <span class="tag">you</span>' : ""}</td>
<td>${me ? u.role : `<select class="uRoleSel"><option ${u.role === "user" ? "selected" : ""}>user</option><option ${u.role === "admin" ? "selected" : ""}>admin</option></select>`}</td>
<td>${u.disabled ? '<span class="tag">disabled</span>' : "active"}</td>
<td class="num">${u.api_keys}</td><td>${when(u.last_login)}</td><td>${when(u.created_at)}</td>
<td>${me ? "" : `<button class="ghost uToggle">${u.disabled ? "Enable" : "Disable"}</button>
<button class="ghost uReset">Reset password</button> <button class="ghost uDelete">Delete</button>`}</td></tr>`;
}).join("")}
</tbody></table>`);
const act = async (fn, okMsg) => { try { await fn(); openUsers(okMsg); } catch (e) { openUsers("Error: " + e.message); } };
$("#uCreate").onclick = () => act(() => api("/users", { username: $("#uName").value.trim(), password: $("#uPass").value, role: $("#uRole").value }),
`Created account "${$("#uName").value.trim()}".`);
$$("tr[data-id]", body).forEach((tr) => {
const id = tr.dataset.id, name = tr.dataset.name;
tr.querySelector(".uRoleSel")?.addEventListener("change", (e) => act(() => api(`/users/${id}`, { role: e.target.value }, "PATCH"), `${name} is now ${e.target.value}.`));
tr.querySelector(".uToggle")?.addEventListener("click", (e) => {
const dis = e.target.textContent === "Disable";
act(() => api(`/users/${id}`, { disabled: dis }, "PATCH"), `${name} ${dis ? "disabled" : "enabled"}.`);
});
tr.querySelector(".uReset")?.addEventListener("click", () => {
const pw = prompt(`New password for ${name} (min 10 characters). They will be signed out everywhere:`);
if (pw) act(() => api(`/users/${id}`, { password: pw }, "PATCH"), `Password for ${name} reset.`);
});
tr.querySelector(".uDelete")?.addEventListener("click", () => {
if (confirm(`Delete account "${name}" and all its API keys? This cannot be undone.`))
act(() => api(`/users/${id}`, undefined, "DELETE"), `Deleted ${name}.`);
});
});
}
function openPassword() {
accountDialog(`
<h2>Change password</h2>
<p class="small muted">Your other signed-in sessions will be signed out. API keys keep working.</p>
<div class="row-inline" style="flex-direction:column;align-items:stretch;max-width:320px">
<label>Current password <input id="pCur" type="password" autocomplete="current-password"></label>
<label>New password (min 10) <input id="pNew" type="password" autocomplete="new-password"></label>
<label>Repeat new password <input id="pNew2" type="password" autocomplete="new-password"></label>
<button id="pSave">Change password</button>
</div>
<p id="pMsg" class="small"></p>`);
$("#pSave").onclick = async () => {
const msg = $("#pMsg");
if ($("#pNew").value !== $("#pNew2").value) { msg.className = "small err"; msg.textContent = "The new passwords don't match."; return; }
try {
await api("/auth/password", { current_password: $("#pCur").value, new_password: $("#pNew").value });
msg.className = "small ok"; msg.textContent = "Password changed.";
$$("#accountBody input").forEach((i) => (i.value = ""));
} catch (e) { msg.className = "small err"; msg.textContent = e.message; }
};
}
// ------------------------------------------------------------------ csv
function exportCsv() {
const rows = sorted(filtered());
const cities = S.cat.cities;
const hdr = ["provider", "region", "location", "country", "continent", "model", "vcpu", "ram_gb", "disk_gb", "cpu_type", "arch",
"vm_usd_mo", "extra_storage_gb", "extra_storage_usd_mo", "ipv4_usd_mo", "monthly_usd", "setup_fee_usd", "total_first_month_usd", "addl_storage_usd_gb_mo",
"hipaa", "soc2", "pci_dss", "gdpr", "smtp25", "price_source", "price_confidence", ...cities.map((c) => "rtt_ms_" + c.name)];
const q = (v) => `"${String(v ?? "").replace(/"/g, '""')}"`;
const lines = [hdr.map(q).join(",")].concat(rows.map((r) => [r.provider, r.region, r.location, r.country, r.continent, r.model,
r.vcpu, r.ram_gb, r.disk_gb, r.cpu_type, r.arch, r.base_price, r.extra_storage_gb, r.extra_storage_cost, r.ipv4, r.recurring, r.setup_fee, r.total,
r.storage_price_gb, r.compliance.hipaa, r.compliance.soc2, r.compliance.pci, r.compliance.gdpr, r.smtp25, r.price_source,
r.price_confidence, ...cities.map((c) => r.latency[c.id])].map(q).join(",")));
const a = document.createElement("a");
a.href = URL.createObjectURL(new Blob([lines.join("\n")], { type: "text/csv" }));
a.download = `coremarket-${new Date().toISOString().slice(0, 10)}.csv`;
a.click();
}
init();
+113
View File
@@ -0,0 +1,113 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Coremarket: Federated Core VM sizing &amp; cloud pricing</title>
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<header>
<h1>Coremarket</h1>
<span class="sub">Size a Federated Core stack, then price the VM across clouds and regions</span>
<span class="spacer"></span>
<span id="liveStatus" class="muted"></span>
<button id="editContaboBtn" class="ghost admin-only hidden" title="Edit Contabo plans and prices by hand">Edit Contabo prices</button>
<button id="refreshBtn" class="ghost admin-only hidden" title="Pull current prices from provider APIs">Refresh live prices</button>
<div class="menu">
<button id="userBtn" class="ghost" aria-haspopup="true" aria-expanded="false">Account ▾</button>
<div id="userMenu" class="menu-list hidden" role="menu">
<div id="userInfo" class="muted small menu-info"></div>
<button role="menuitem" data-act="keys">API keys</button>
<button role="menuitem" data-act="users" class="admin-only hidden">Users</button>
<button role="menuitem" data-act="password">Change password</button>
<button role="menuitem" data-act="docs">API docs</button>
<button role="menuitem" data-act="logout">Sign out</button>
</div>
</div>
</header>
<div class="layout">
<aside>
<section>
<h2>1. Software</h2>
<div class="presets">
<label class="tier">Federated tier
<select id="tierSelect"></select>
</label>
<button id="clearApps" class="ghost" title="Untick all apps">Clear</button>
</div>
<input id="appSearch" type="search" placeholder="Filter apps...">
<p class="muted small">Always included (Federated Core): <span id="coreList"></span></p>
<div id="appList"></div>
</section>
</aside>
<main>
<section class="card">
<h2>2. Workload</h2>
<div class="grid4">
<label>Concurrent users <input id="concurrent" type="number" min="1" value="5"></label>
<label>Named users (accounts) <input id="named" type="number" min="1" value="10"></label>
<label>CPU/RAM headroom % <input id="headroom" type="number" min="0" value="25"></label>
<label>Disk growth % (12 mo) <input id="growth" type="number" min="0" value="30"></label>
<label>Extra disk GB <input id="extraDisk" type="number" min="0" value="0"></label>
<label class="chk"><input id="allowBurst" type="checkbox" checked> Allow burstable CPU</label>
<label class="chk"><input id="dedicatedOnly" type="checkbox"> Dedicated vCPU only</label>
<label class="chk"><input id="allowArm" type="checkbox"> Allow ARM64</label>
</div>
<div id="sizing" class="sizing"></div>
</section>
<section class="card">
<h2>3. Filters</h2>
<div class="filters">
<div><b>Regions</b><div id="contFilter" class="chips"></div></div>
<div><b>Must have compliance</b>
<div class="chips" id="compFilter"></div>
<label class="chk small"><input id="allowPartial" type="checkbox"> accept "partial"</label>
</div>
<div><b>Other</b>
<label class="chk small"><input id="needSmtp" type="checkbox"> exclude clouds that hard-block SMTP port 25</label>
<label class="chk small"><input id="bestPerProvider" type="checkbox" checked> cheapest region per provider only (by-region view)</label>
</div>
<div><b>Providers</b><div id="provFilter" class="chips"></div></div>
</div>
<div class="filters">
<div class="wide"><b>Latency focus cities</b> <span class="muted small">(columns show avg / worst estimated RTT to these)</span>
<div id="cityFilter" class="chips small"></div>
</div>
<div><b>Max RTT to focus cities</b>
<label>ms <input id="maxRtt" type="number" min="0" placeholder="no limit" style="width:7em"></label>
</div>
</div>
</section>
<section class="card">
<div class="tabs">
<button data-tab="byregion" class="active">Prices by region</button>
<button data-tab="all">All options</button>
<button data-tab="matrix">Latency matrix</button>
<button data-tab="notes">Notes &amp; API docs</button>
<span class="spacer"></span>
<span id="count" class="muted"></span>
<button id="csvBtn" class="ghost">Export CSV</button>
</div>
<div id="tab-byregion" class="tab"></div>
<div id="tab-all" class="tab hidden"></div>
<div id="tab-matrix" class="tab hidden"></div>
<div id="tab-notes" class="tab hidden"></div>
</section>
</main>
</div>
<dialog id="account"><form method="dialog" class="dlg-close top"><button>Close</button></form><div id="accountBody"></div></dialog>
<dialog id="editor"><div id="editorBody"></div></dialog>
<dialog id="detail">
<form method="dialog" class="dlg-close top"><button>Close</button></form>
<div id="detailBody"></div>
<form method="dialog" class="dlg-close"><button>Close</button></form>
</dialog>
<script src="/static/app.js"></script>
</body>
</html>
+45
View File
@@ -0,0 +1,45 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sign in: Coremarket</title>
<link rel="stylesheet" href="/static/style.css">
</head>
<body class="login-page">
<form id="loginForm" class="card login-card">
<h1>Coremarket</h1>
<p class="muted small">Sign in to size and price Federated Core VMs.</p>
<label>Username <input id="username" name="username" autocomplete="username" required autofocus></label>
<label>Password <input id="password" name="password" type="password" autocomplete="current-password" required></label>
<p id="loginErr" class="err small" role="alert"></p>
<button type="submit" id="loginBtn">Sign in</button>
<p class="muted small">No account? Ask your Coremarket administrator.</p>
</form>
<script>
"use strict";
const form = document.getElementById("loginForm");
form.onsubmit = async (e) => {
e.preventDefault();
const btn = document.getElementById("loginBtn"), err = document.getElementById("loginErr");
btn.disabled = true; err.textContent = "";
try {
const r = await fetch("/api/v1/auth/login", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: form.username.value.trim(), password: form.password.value }),
});
if (!r.ok) {
let msg = "Sign-in failed.";
try { msg = (await r.json()).detail || msg; } catch (_) {}
throw new Error(typeof msg === "string" ? msg : "Sign-in failed.");
}
const next = new URLSearchParams(location.search).get("next") || "/";
location.href = next.startsWith("/") && !next.startsWith("//") ? next : "/";
} catch (ex) {
err.textContent = ex.message.charAt(0).toUpperCase() + ex.message.slice(1);
form.password.value = ""; form.password.focus();
} finally { btn.disabled = false; }
};
</script>
</body>
</html>
+102
View File
@@ -0,0 +1,102 @@
:root {
--bg: #f6f7f9; --card: #fff; --fg: #1d2330; --muted: #6b7385; --line: #e2e5eb;
--accent: #2f6fde; --yes: #1f8a4c; --partial: #b7791f; --no: #b8bcc6;
}
@media (prefers-color-scheme: dark) {
:root { --bg: #14171d; --card: #1c2029; --fg: #e6e9ef; --muted: #98a0b3; --line: #2c3240;
--accent: #6b9cff; --yes: #4cc483; --partial: #e0a84a; --no: #555c6b; }
}
* { box-sizing: border-box; }
body { margin: 0; font: 14px/1.45 system-ui, -apple-system, Segoe UI, Roboto, sans-serif; background: var(--bg); color: var(--fg); }
header { display: flex; align-items: center; gap: 1rem; padding: .7rem 1.2rem; border-bottom: 1px solid var(--line); background: var(--card); position: sticky; top: 0; z-index: 5; }
header h1 { margin: 0; font-size: 1.3rem; }
.sub { color: var(--muted); }
.spacer { flex: 1; }
.layout { display: grid; grid-template-columns: 300px 1fr; gap: 1rem; padding: 1rem; }
aside { background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: .8rem; max-height: calc(100vh - 90px); overflow: auto; position: sticky; top: 70px; }
main { min-width: 0; }
.card { background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: .9rem 1rem; margin-bottom: 1rem; }
h2 { font-size: 1rem; margin: 0 0 .6rem; }
h3 { font-size: .95rem; margin: 1rem 0 .4rem; }
.muted { color: var(--muted); } .small { font-size: 12px; }
input[type=number], input[type=search] { padding: .3rem .4rem; border: 1px solid var(--line); border-radius: 5px; background: var(--bg); color: var(--fg); }
input[type=search] { width: 100%; margin: .4rem 0; }
label { display: flex; flex-direction: column; gap: .2rem; font-size: 12px; color: var(--muted); }
label.chk { flex-direction: row; align-items: center; gap: .35rem; color: var(--fg); }
button { cursor: pointer; border: 1px solid var(--accent); background: var(--accent); color: #fff; border-radius: 5px; padding: .3rem .7rem; font: inherit; }
button.ghost { background: transparent; color: var(--accent); }
button:disabled { opacity: .5; cursor: wait; }
.grid4 { display: grid; grid-template-columns: repeat(4, minmax(140px, 1fr)); gap: .6rem 1rem; }
.presets { display: flex; gap: .4rem; align-items: end; }
.presets .tier { flex: 1; }
.presets select { width: 100%; padding: .3rem .4rem; border: 1px solid var(--line); border-radius: 5px; background: var(--bg); color: var(--fg); font: inherit; font-size: 13px; }
.presets button { font-size: 12px; padding: .3rem .6rem; }
details.cat { margin: .3rem 0; }
details.cat summary { cursor: pointer; font-weight: 600; }
.app { display: flex; flex-direction: row; gap: .4rem; align-items: flex-start; padding: .1rem 0 .1rem .4rem; font-size: 13px; }
.app small { color: var(--muted); display: block; }
.sizing { margin-top: .8rem; display: grid; grid-template-columns: 300px 1fr; gap: 1rem; }
.spec { display: flex; gap: .6rem; }
.spec div { flex: 1; text-align: center; border: 1px solid var(--line); border-radius: 8px; padding: .5rem; }
.spec b { display: block; font-size: 1.5rem; }
.spec .ovr { width: 4.5em; text-align: center; margin-top: .2rem; }
.breakdown { max-height: 240px; overflow: auto; }
.filters { display: flex; flex-wrap: wrap; gap: 1rem 2rem; margin-bottom: .6rem; }
.filters .wide { flex: 1 1 600px; }
.chips { display: flex; flex-wrap: wrap; gap: .25rem; margin-top: .3rem; }
.chip { border: 1px solid var(--line); border-radius: 12px; padding: .1rem .55rem; cursor: pointer; user-select: none; font-size: 12px; }
.chip.on { background: var(--accent); border-color: var(--accent); color: #fff; }
.tabs { display: flex; gap: .3rem; align-items: center; border-bottom: 1px solid var(--line); padding-bottom: .5rem; margin-bottom: .6rem; }
.tabs button[data-tab] { background: transparent; color: var(--fg); border-color: transparent; }
.tabs button[data-tab].active { border-color: var(--accent); color: var(--accent); }
.hidden { display: none; }
.tab { overflow-x: auto; }
table { border-collapse: collapse; width: 100%; font-size: 12.5px; }
th, td { padding: .3rem .45rem; border-bottom: 1px solid var(--line); text-align: left; white-space: nowrap; }
th { position: sticky; top: 0; background: var(--card); cursor: pointer; font-weight: 600; }
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
tr.row:hover { background: color-mix(in srgb, var(--accent) 7%, transparent); cursor: pointer; }
.total { font-weight: 700; }
.badge { display: inline-block; min-width: 2.6em; text-align: center; border-radius: 4px; padding: 0 .25rem; margin-right: 2px; font-size: 11px; color: #fff; }
.badge.yes { background: var(--yes); } .badge.partial { background: var(--partial); } .badge.no { background: var(--no); }
.conf-low { color: var(--partial); } .conf-medium { color: var(--muted); }
.lat { font-variant-numeric: tabular-nums; text-align: right; }
.matrix td.lat { min-width: 2.6em; font-size: 11.5px; }
.matrix th.city { writing-mode: vertical-rl; transform: rotate(180deg); height: 8em; font-weight: 500; }
dialog { max-width: 1000px; width: 92vw; border: 1px solid var(--line); border-radius: 10px; background: var(--card); color: var(--fg); }
dialog::backdrop { background: rgba(0,0,0,.4); }
.notes p, .notes li { max-width: 1000px; }
.warn { border-left: 3px solid var(--partial); padding: .3rem .7rem; background: color-mix(in srgb, var(--partial) 10%, transparent); margin: .5rem 0; }
.cmp { margin-top: .5rem; font-size: 13px; }
@media (max-width: 1000px) { .layout { grid-template-columns: 1fr; } aside { position: static; max-height: none; } .sizing { grid-template-columns: 1fr; } .grid4 { grid-template-columns: repeat(2, 1fr); } }
#editor table select { min-width: 7.5em; }
#editor table input, #editor table select { width: 100%; min-width: 4em; padding: .2rem .3rem; border: 1px solid var(--line); border-radius: 4px; background: var(--bg); color: var(--fg); font: inherit; }
#editor table input.w-name { min-width: 9em; } #editor table input.w-note { min-width: 10em; }
#editor textarea { width: 100%; min-height: 7em; font: 12px ui-monospace, monospace; background: var(--bg); color: var(--fg); border: 1px solid var(--line); border-radius: 5px; }
#editor .row-inline { display: flex; gap: 1rem; flex-wrap: wrap; align-items: end; margin: .5rem 0; }
#editor .actions { display: flex; gap: .5rem; margin-top: 1rem; }
#editor .err { color: #c0392b; }
.dlg-close { display: flex; justify-content: flex-end; margin: .5rem 0 0; }
.dlg-close.top { float: right; margin: .9rem 0 0 1rem; }
/* account menu & dialogs */
.menu { position: relative; }
.menu-list { position: absolute; right: 0; top: calc(100% + 4px); background: var(--card); border: 1px solid var(--line); border-radius: 8px; box-shadow: 0 6px 20px rgba(0,0,0,.15); min-width: 190px; padding: .3rem; z-index: 10; display: flex; flex-direction: column; }
.menu-list.hidden { display: none; }
.menu-list button { background: transparent; color: var(--fg); border: 0; text-align: left; padding: .4rem .6rem; border-radius: 5px; }
.menu-list button:hover { background: color-mix(in srgb, var(--accent) 12%, transparent); }
.menu-info { padding: .3rem .6rem .4rem; border-bottom: 1px solid var(--line); margin-bottom: .2rem; }
#account { max-width: 900px; }
#account input, #account select { padding: .3rem .4rem; border: 1px solid var(--line); border-radius: 5px; background: var(--bg); color: var(--fg); font: inherit; }
#account .row-inline { display: flex; gap: .8rem; flex-wrap: wrap; align-items: end; margin: .6rem 0; }
#account td button { font-size: 12px; padding: .15rem .5rem; }
.newkey { font: 13px ui-monospace, monospace; padding: .6rem; border: 1px dashed var(--accent); border-radius: 6px; word-break: break-all; background: var(--bg); }
.err { color: #c0392b; } .ok { color: var(--yes); }
.tag { font-size: 11px; border: 1px solid var(--line); border-radius: 4px; padding: 0 .3rem; }
/* login page */
.login-page { display: grid; place-items: center; min-height: 100vh; }
.login-card { width: min(360px, 92vw); display: flex; flex-direction: column; gap: .7rem; padding: 1.6rem; }
.login-card h1 { margin: 0; }
.login-card input { padding: .5rem; border: 1px solid var(--line); border-radius: 6px; background: var(--bg); color: var(--fg); font: inherit; font-size: 14px; }
.login-card button { padding: .5rem; }