Spaces:
Running

explication / js /admin.js
quantilimited's picture
Switch the shop from Stripe to PayPal
cecfe55
Raw History Blame Contribute Delete
34.2 kB
import { html, useEffect, useState } from "./runtime.js";
import { useCloud, money, DEVELOPER_EMAIL, DEFAULT_MODELS } from "./cloud.js";
import { useEditMode } from "./copy.js";
import { Icon, Notice, Pill } from "./components.js";
// ---------------------------------------------------------------------------
// Small form pieces
// ---------------------------------------------------------------------------
function Head({ kicker, title, subtitle, right }) {
return html`<div class="row between" style=${{ alignItems: "flex-start", gap: "16px" }}>
<div>
<div class="eyebrow">${kicker}</div>
<h1 class="page-title">${title}</h1>
${subtitle && html`<p class="subtitle">${subtitle}</p>`}
</div>
${right}
</div>`;
}
function Field({ label, hint, children }) {
return html`<div class="field">
<label>${label}${hint && html` <span class="hint">${hint}</span>`}</label>
${children}
</div>`;
}
function Text({ label, hint, value, onChange, placeholder, type = "text", mono = false }) {
return html`<${Field} label=${label} hint=${hint}>
<input class=${"input" + (mono ? " mono" : "")} type=${type} value=${value == null ? "" : value}
onInput=${(e) => onChange(e.target.value)} placeholder=${placeholder || ""} spellCheck=${false} />
<//>`;
}
function Area({ label, hint, value, onChange, placeholder, rows = 3 }) {
return html`<${Field} label=${label} hint=${hint}>
<textarea class="textarea plain" style=${{ minHeight: rows * 26 + "px" }} value=${value == null ? "" : value}
onInput=${(e) => onChange(e.target.value)} placeholder=${placeholder || ""} spellCheck=${false}></textarea>
<//>`;
}
function Select({ label, hint, value, onChange, options }) {
return html`<${Field} label=${label} hint=${hint}>
<select class="select" value=${value} onChange=${(e) => onChange(e.target.value)}>
${options.map((o) => html`<option key=${o.value} value=${o.value}>${o.label}</option>`)}
</select>
<//>`;
}
function Check({ label, hint, checked, onChange }) {
return html`<label class="check-row">
<input type="checkbox" checked=${!!checked} onChange=${(e) => onChange(e.target.checked)} />
<span><strong>${label}</strong>${hint && html`<span class="tiny faint" style=${{ display: "block" }}>${hint}</span>`}</span>
</label>`;
}
function Stat({ label, value, note }) {
return html`<div class="stat"><div class="head">${label}</div><div class="value">${value}</div><div class="note">${note}</div></div>`;
}
// ---------------------------------------------------------------------------
// Plans
// ---------------------------------------------------------------------------
const BLANK_PLAN = {
id: "",
name: "",
kind: "subscription",
price_cents: 0,
currency: "GBP",
interval: "month",
blurb: "",
features: [],
cost_limit_cents: 0,
download_tier: 0,
byok: true,
paypal_plan_id: "",
paypal_payment_link: "",
active: true,
sort: 0
};
function PlanEditor({ plan, onDone }) {
const cloud = useCloud();
const [draft, setDraft] = useState(plan || BLANK_PLAN);
const [price, setPrice] = useState(((plan || BLANK_PLAN).price_cents / 100).toFixed(2));
const [limit, setLimit] = useState(((plan || BLANK_PLAN).cost_limit_cents / 100).toFixed(2));
const [features, setFeatures] = useState((plan && plan.features ? plan.features : []).join("\n"));
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
const set = (patch) => setDraft((d) => ({ ...d, ...patch }));
const save = async () => {
setError("");
const id = (draft.id || draft.name || "").trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
if (!draft.name.trim()) return setError("Give the plan a name.");
if (!id) return setError("Give the plan an identifier, for example scholar.");
setBusy(true);
try {
await cloud.upsertPlan({
...draft,
id,
price_cents: Math.round((Number(price) || 0) * 100),
cost_limit_cents: Math.round((Number(limit) || 0) * 100),
interval: draft.kind === "subscription" ? draft.interval || "month" : null,
features: features.split("\n").map((f) => f.trim()).filter(Boolean),
sort: Number(draft.sort) || 0
});
cloud.flash("Plan saved.");
onDone();
} catch (err) {
setError(err && err.message ? err.message : "Could not save the plan.");
}
setBusy(false);
};
// A plan's identity is its id; keep it stable once it exists.
const lockedId = !!(plan && plan.id);
return html`<div class="card fade-in" style=${{ marginTop: "10px" }}>
<div class="row between"><strong>${lockedId ? "Edit " + plan.name : "New plan"}</strong>
<button class="btn small ghost" onClick=${onDone}>Close</button>
</div>
<div class="grid two" style=${{ marginTop: "10px" }}>
<${Text} label="Name" value=${draft.name} onChange=${(v) => set({ name: v, id: lockedId ? draft.id : draft.id || "" })} placeholder="Scholar" />
<${Text} label="Identifier" hint="used in links" value=${draft.id} onChange=${(v) => !lockedId && set({ id: v })} placeholder="scholar" mono=${true} />
<${Select} label="Type" value=${draft.kind} onChange=${(v) => set({ kind: v })}
options=${[{ value: "subscription", label: "Subscription" }, { value: "one_time", label: "One-off purchase" }]} />
${draft.kind === "subscription"
? html`<${Select} label="Billing period" value=${draft.interval || "month"} onChange=${(v) => set({ interval: v })}
options=${[{ value: "month", label: "Monthly" }, { value: "year", label: "Yearly" }]} />`
: html`<${Text} label="Sort order" value=${draft.sort} onChange=${(v) => set({ sort: Number(v) || 0 })} type="number" />`}
<${Text} label="Price" hint="in pounds" value=${price} onChange=${setPrice} type="number" />
<${Text} label="Included AI allowance" hint="pounds included in the price" value=${limit} onChange=${setLimit} type="number" />
<${Text} label="Download tier" hint="0–4 models unlocked" value=${draft.download_tier} onChange=${(v) => set({ download_tier: Number(v) || 0 })} type="number" />
<${Text} label="Sort order" value=${draft.sort} onChange=${(v) => set({ sort: Number(v) || 0 })} type="number" />
</div>
<div style=${{ marginTop: "10px" }}>
<${Area} label="Short description" value=${draft.blurb} onChange=${(v) => set({ blurb: v })} rows=${2} />
</div>
<div style=${{ marginTop: "10px" }}>
<${Area} label="Features" hint="one per line" value=${features} onChange=${setFeatures} rows=${4} />
</div>
<div class="grid two" style=${{ marginTop: "10px" }}>
<${Text} label="PayPal billing plan ID" hint="optional · P-… · API mode" value=${draft.paypal_plan_id} onChange=${(v) => set({ paypal_plan_id: v })} mono=${true} />
<${Text} label="PayPal payment link" hint="for payment-link mode" value=${draft.paypal_payment_link} onChange=${(v) => set({ paypal_payment_link: v })} mono=${true} />
</div>
<div class="row wrap" style=${{ marginTop: "10px" }}>
<${Check} label="Published" checked=${draft.active} onChange=${(v) => set({ active: v })} />
<${Check} label="Allow BYOK" checked=${draft.byok} onChange=${(v) => set({ byok: v })} />
</div>
${error && html`<div style=${{ marginTop: "10px" }}><${Notice} kind="error">${error}<//></div>`}
<div class="row" style=${{ marginTop: "12px" }}>
<button class="btn primary small" onClick=${save} disabled=${busy}>${busy ? html`<span class="spin"></span>` : "Save plan"}</button>
<button class="btn small ghost" onClick=${onDone}>Cancel</button>
</div>
</div>`;
}
function PlansTab() {
const cloud = useCloud();
const [editing, setEditing] = useState(null);
const [confirm, setConfirm] = useState("");
return html`<div>
<div class="row between">
<div class="tiny faint">Plans appear on the plans page the moment they are published.</div>
<button class="btn primary small" onClick=${() => setEditing(BLANK_PLAN)}><${Icon} name="plus" size=${12} /> New plan</button>
</div>
${editing && html`<${PlanEditor} plan=${editing === BLANK_PLAN ? null : editing} onDone=${() => setEditing(null)} />`}
<div class="card" style=${{ marginTop: "12px" }}>
<div class="list">
${cloud.plans.length === 0 && html`<div class="empty">No plans yet.</div>`}
${cloud.plans.map(
(p) => html`<div class="list-row" key=${p.id}>
<div class="main">
<div class="t">${p.name} <span class="pill ${p.kind === "subscription" ? "green" : "neutral"}" style=${{ marginLeft: "6px" }}>${p.kind === "subscription" ? "Subscription" : "One-off"}</span>
${p.active === false && html`<span class="pill danger" style=${{ marginLeft: "6px" }}>Hidden</span>`}</div>
<div class="s">${money(p.price_cents, p.currency)} ${p.kind === "subscription" ? "per " + (p.interval || "month") : "once"} · ${p.cost_limit_cents ? money(p.cost_limit_cents, p.currency) + " model usage" : "no hosted usage"} · ${p.download_tier} download${p.download_tier === 1 ? "" : "s"}</div>
</div>
<button class="btn small" onClick=${() => setEditing(p)}>Edit</button>
${confirm === p.id
? html`<span class="row"><button class="btn small" onClick=${() => setConfirm("")}>Keep</button>
<button class="btn small danger" onClick=${async () => { await cloud.deletePlan(p.id); setConfirm(""); }}>Delete</button></span>`
: html`<button class="icon-btn" title="Delete" onClick=${() => setConfirm(p.id)}><${Icon} name="trash" size=${13} /></button>`}
</div>`
)}
</div>
</div>
</div>`;
}
// ---------------------------------------------------------------------------
// Models
// ---------------------------------------------------------------------------
const BLANK_MODEL = {
id: "",
name: "",
host: "",
endpoint_url: "",
model_name: "",
cost_in_per_million: 0,
cost_out_per_million: 0,
min_tier: 1,
download_size: "",
note: "",
enabled: true,
sort: 0
};
function ModelEditor({ model, onDone }) {
const cloud = useCloud();
const [draft, setDraft] = useState(model || BLANK_MODEL);
const [apiKey, setApiKey] = useState("");
const [error, setError] = useState("");
const [saved, setSaved] = useState(false);
const [busy, setBusy] = useState(false);
const set = (patch) => setDraft((d) => ({ ...d, ...patch }));
const save = async () => {
setError("");
setBusy(true);
try {
const id = (draft.id || draft.model_name || draft.name || "").trim();
if (!draft.name.trim() || !id) throw new Error("The model needs a name and an identifier.");
await cloud.upsertModel({
...draft,
id,
cost_in_per_million: Number(draft.cost_in_per_million) || 0,
cost_out_per_million: Number(draft.cost_out_per_million) || 0,
min_tier: Number(draft.min_tier) || 0,
sort: Number(draft.sort) || 0
});
if (apiKey.trim()) {
await cloud.saveModelKey(id, apiKey.trim());
setApiKey("");
}
cloud.flash("Model saved.");
setSaved(true);
setTimeout(() => setSaved(false), 2000);
onDone();
} catch (err) {
setError(err && err.message ? err.message : "Could not save the model.");
}
setBusy(false);
};
return html`<div class="card fade-in" style=${{ marginTop: "10px" }}>
<div class="row between"><strong>${model ? "Edit " + model.name : "New model"}</strong>
<button class="btn small ghost" onClick=${onDone}>Close</button>
</div>
<div class="grid two" style=${{ marginTop: "10px" }}>
<${Text} label="Display name" value=${draft.name} onChange=${(v) => set({ name: v })} placeholder="Qwen2.5 7B" />
<${Text} label="Identifier" value=${draft.id} onChange=${(v) => set({ id: v })} placeholder="Qwen2.5-7B-Instruct-q4f16_1-MLC" mono=${true} />
<${Text} label="Host" hint="shown to students" value=${draft.host} onChange=${(v) => set({ host: v })} placeholder="OpenRouter" />
<${Text} label="Model name at the host" value=${draft.model_name} onChange=${(v) => set({ model_name: v })} placeholder="qwen/qwen-2.5-7b-instruct" mono=${true} />
<${Text} label="Endpoint base URL" hint="OpenAI-compatible" value=${draft.endpoint_url} onChange=${(v) => set({ endpoint_url: v })} placeholder="https://openrouter.ai/api/v1" mono=${true} />
<${Text} label="API key" hint="stored write-only" value=${apiKey} onChange=${setApiKey} placeholder=${model && model.id ? "Paste a new key to replace" : "sk-…"} type="password" />
<${Text} label="Input cost" hint="per million tokens" value=${draft.cost_in_per_million} onChange=${(v) => set({ cost_in_per_million: v })} type="number" />
<${Text} label="Output cost" hint="per million tokens" value=${draft.cost_out_per_million} onChange=${(v) => set({ cost_out_per_million: v })} type="number" />
<${Text} label="Minimum download tier" hint="0–4" value=${draft.min_tier} onChange=${(v) => set({ min_tier: Number(v) || 0 })} type="number" />
<${Text} label="Download size" value=${draft.download_size} onChange=${(v) => set({ download_size: v })} placeholder="~4.5 GB" />
</div>
<div style=${{ marginTop: "10px" }}">
<${Area} label="Note" value=${draft.note} onChange=${(v) => set({ note: v })} rows=${2} placeholder="What this model is good for." />
</div>
${error && html`<div style=${{ marginTop: "10px" }}><${Notice} kind="error">${error}<//></div>`}
<div class="row" style=${{ marginTop: "12px" }}>
<button class="btn primary small" onClick=${save} disabled=${busy}>${busy ? html`<span class="spin"></span>` : saved ? "Saved" : "Save model"}</button>
<${Check} label="Enabled" checked=${draft.enabled} onChange=${(v) => set({ enabled: v })} />
</div>
<div class="tiny faint" style=${{ marginTop: "8px" }}>
The key is used only by the hosted model function on Supabase. It is never sent to a browser.
</div>
</div>`;
}
function ModelsTab() {
const cloud = useCloud();
const [editing, setEditing] = useState(null);
const [confirm, setConfirm] = useState("");
return html`<div>
<div class="row between wrap">
<div class="tiny faint" style=${{ maxWidth: "560px" }}>
Each model has its own host, endpoint and key. Students download the ones their plan unlocks; the rest run through the hosted function using these keys.
</div>
<button class="btn primary small" onClick=${() => setEditing(BLANK_MODEL)}><${Icon} name="plus" size=${12} /> New model</button>
</div>
${editing && html`<${ModelEditor} model=${editing === BLANK_MODEL ? null : editing} onDone=${() => setEditing(null)} />`}
<div class="card" style=${{ marginTop: "12px" }}>
<div class="list">
${cloud.models.map(
(m) => html`<div class="list-row" key=${m.id}>
<div class="main">
<div class="t">${m.name} ${m.enabled === false && html`<span class="pill danger" style=${{ marginLeft: "6px" }}>Off</span>`}</div>
<div class="s">${m.host || "Browser"} · tier ${m.min_tier} · ${m.download_size || "no download"} · ${m.cost_in_per_million || 0}/${m.cost_out_per_million || 0} per M tokens</div>
</div>
<button class="btn small" onClick=${() => setEditing(m)}>Edit</button>
${confirm === m.id
? html`<span class="row"><button class="btn small" onClick=${() => setConfirm("")}>Keep</button>
<button class="btn small danger" onClick=${async () => { await cloud.deleteModel(m.id); setConfirm(""); }}>Delete</button></span>`
: html`<button class="icon-btn" title="Delete" onClick=${() => setConfirm(m.id)}><${Icon} name="trash" size=${13} /></button>`}
</div>`
)}
${cloud.models.length === 0 && html`<div class="empty">No models yet. <button class="btn link small" onClick=${() => setEditing(BLANK_MODEL)}>Add one</button></div>`}
</div>
</div>
</div>`;
}
// ---------------------------------------------------------------------------
// Wording / edit mode
// ---------------------------------------------------------------------------
function WordingTab() {
const cloud = useCloud();
const { editing, setEditing } = useEditMode();
const keys = Object.keys(cloud.content || {}).sort();
return html`<div>
<div class="card">
<div class="row between wrap">
<div style=${{ maxWidth: "560px" }}>
<div style=${{ fontWeight: 600 }}>Edit mode</div>
<div class="tiny faint" style=${{ marginTop: "3px", lineHeight: 1.55 }}>
Turn it on, then open any page and click the writing. Every change is saved and shown to everyone, in every browser.
</div>
</div>
<button class=${"btn small " + (editing ? "green" : "primary")} onClick=${() => setEditing(!editing)}>
${editing ? "Editing — click Done when finished" : "Turn on edit mode"}
</button>
</div>
</div>
<div class="section-head"><h2 class="section-title">Changed wording</h2></div>
<div class="card">
${keys.length === 0
? html`<div class="empty">Nothing has been reworded yet. Turn on edit mode and click a heading on the Today or Plans page.</div>`
: html`<div class="list">
${keys.map(
(key) => html`<div class="list-row" key=${key} style=${{ alignItems: "flex-start" }}>
<div class="main">
<div class="t mono" style=${{ fontSize: "11px" }}>${key}</div>
<div class="s" style=${{ whiteSpace: "pre-wrap" }}>${cloud.content[key]}</div>
</div>
<button class="btn small" onClick=${async () => { await cloud.clearContent(key); cloud.flash("Reverted to the original wording."); }}>Reset</button>
</div>`
)}
</div>`}
</div>
<div class="card" style=${{ marginTop: "12px" }}>
<div class="tiny faint" style=${{ lineHeight: 1.6 }}>
Every edit is stored by key, so it survives a refresh and reaches every visitor. Only the developer account can change it — row-level security in Supabase enforces that even if someone opens the developer page.
</div>
</div>
</div>`;
}
// ---------------------------------------------------------------------------
// PayPal
// ---------------------------------------------------------------------------
function PayPalTab() {
const cloud = useCloud();
const [client, setClient] = useState(cloud.settings.paypal_client_id || "");
const [mode, setMode] = useState(cloud.settings.paypal_mode || "live");
const [checkout, setCheckout] = useState(cloud.settings.checkout_mode || "function");
const [fn, setFn] = useState(cloud.settings.checkout_function || "paypal-checkout");
const [busy, setBusy] = useState(false);
const [saved, setSaved] = useState(false);
const save = async () => {
setBusy(true);
try {
await cloud.setSettings({
paypal_client_id: client.trim(),
paypal_mode: mode,
checkout_mode: checkout,
checkout_function: fn.trim() || "paypal-checkout"
});
setSaved(true);
setTimeout(() => setSaved(false), 2000);
} catch (err) {
cloud.flash(err && err.message ? err.message : "Could not save.");
}
setBusy(false);
};
return html`<div>
<div class="card">
<div class="section-title" style=${{ marginBottom: "10px" }}>PayPal</div>
<div class="grid two">
<${Text} label="Client ID" hint="live or sandbox app" value=${client} onChange=${setClient} mono=${true} />
<${Select} label="PayPal mode" value=${mode} onChange=${setMode}
options=${[{ value: "live", label: "Live" }, { value: "sandbox", label: "Sandbox" }]} />
<${Select} label="Checkout mode" value=${checkout} onChange=${setCheckout}
options=${[
{ value: "function", label: "PayPal API · automatic access" },
{ value: "payment_links", label: "PayPal payment links · manual access" }
]} />
<${Text} label="Checkout function" hint="deployed in Supabase" value=${fn} onChange=${setFn} mono=${true} />
</div>
<div class="row" style=${{ marginTop: "12px" }}>
<button class="btn primary small" onClick=${save} disabled=${busy}>${busy ? html`<span class="spin"></span>` : saved ? "Saved" : "Save payment settings"}</button>
</div>
</div>
<div class="card" style=${{ marginTop: "12px" }}>
<div class="section-title" style=${{ marginBottom: "8px" }}>Where the secrets go</div>
<div class="tiny muted" style=${{ lineHeight: 1.7 }}>
Never in this page. Add <span class="mono">PAYPAL_CLIENT_ID</span>, <span class="mono">PAYPAL_CLIENT_SECRET</span> and <span class="mono">PAYPAL_WEBHOOK_ID</span> in Supabase → Edge Functions → Secrets, then deploy <span class="mono">paypal-checkout</span> and <span class="mono">paypal-webhook</span>. Point a PayPal webhook at <span class="mono">https://YOUR-PROJECT.supabase.co/functions/v1/paypal-webhook</span>. Steps are in <span class="mono">supabase/SETUP.md</span>.
</div>
<div class="divider"></div>
<div class="tiny muted" style=${{ lineHeight: 1.7 }}>
${checkout === "function"
? "Prices and intervals come from the plans table. PayPal billing plans are created automatically the first time someone subscribes."
: "Paste a PayPal payment link on each plan in Plans. The site sends buyers there, but payment links do not say who paid — grant access in People after each sale."}
</div>
</div>
</div>`;
}
// ---------------------------------------------------------------------------
// Supabase + people
// ---------------------------------------------------------------------------
function SupabaseTab() {
const cloud = useCloud();
const [url, setUrl] = useState(cloud.config.url);
const [key, setKey] = useState(cloud.config.anonKey);
const [confirm, setConfirm] = useState(false);
const [error, setError] = useState("");
const apply = () => {
setError("");
const clean = url.trim().replace(/\/+$/, "");
if (!/^https?:\/\/.+/.test(clean) || key.trim().length < 20) {
setError("Both values are needed. The URL looks like https://yourproject.supabase.co and the key starts with eyJ.");
return;
}
cloud.connect({ url: clean, anonKey: key.trim() });
cloud.flash("Connection updated.");
};
return html`<div>
<div class="card">
<div class="row between wrap">
<div>
<div style=${{ fontWeight: 600 }}>Project</div>
<div class="tiny faint mono" style=${{ marginTop: "3px" }}>${cloud.configured ? cloud.config.url : "not connected"}</div>
</div>
<${Pill} tone=${cloud.configured ? "green" : "warn"}>${cloud.configured ? "Connected" : "Preview mode"}</${Pill}>
</div>
<div class="grid two" style=${{ marginTop: "12px" }}>
<${Text} label="Project URL" value=${url} onChange=${setUrl} placeholder="https://abcdefgh.supabase.co" mono=${true} />
<${Field} label="Anon public key" hint="safe to publish">
<textarea class="textarea plain" style=${{ minHeight: "64px" }} value=${key} onInput=${(e) => setKey(e.target.value)} placeholder="eyJhbGciOi…"></textarea>
<//>
</div>
${error && html`<div style=${{ marginTop: "8px" }}><${Notice} kind="error">${error}<//></div>`}
<div class="row wrap" style=${{ marginTop: "10px" }}>
<button class="btn primary small" onClick=${apply}>Save connection</button>
<a class="btn small" href="SETUP.html" target="_blank" rel="noreferrer">Open the picture guide</a>
</div>
<div class="tiny faint" style=${{ marginTop: "8px", lineHeight: 1.6 }}>
This is the same connection first-run visitors see. Once it is saved, the setup prompt disappears from the site permanently — it lives here from then on.
</div>
</div>
<div class="card" style=${{ marginTop: "12px" }}>
<div class="row between wrap">
<div style=${{ maxWidth: "520px" }}>
<div style=${{ fontWeight: 600 }}>Disconnect</div>
<div class="tiny faint" style=${{ marginTop: "3px", lineHeight: 1.55 }}>
Removes the connection from this browser and returns the site to preview mode. Nothing is deleted in Supabase.
</div>
</div>
${confirm
? html`<span class="row"><button class="btn small" onClick=${() => setConfirm(false)}>Keep it</button>
<button class="btn small danger" onClick=${() => { cloud.disconnect(); setConfirm(false); }}>Disconnect</button></span>`
: html`<button class="btn small danger" onClick=${() => setConfirm(true)}>Disconnect</button>`}
</div>
</div>
</div>`;
}
function PeopleTab() {
const cloud = useCloud();
const [email, setEmail] = useState("");
const [planId, setPlanId] = useState(cloud.plans[0] ? cloud.plans[0].id : "");
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
const grant = async () => {
setError("");
if (!/^\S+@\S+\.\S+$/.test(email.trim())) return setError("Type the buyer's email.");
if (!planId) return setError("Pick a plan.");
setBusy(true);
try {
await cloud.grantPlan(email.trim(), planId);
cloud.flash("Access granted to " + email.trim() + ".");
setEmail("");
} catch (err) {
setError(err && err.message ? err.message : "Could not grant access.");
}
setBusy(false);
};
return html`<div>
<div class="card">
<div class="section-title" style=${{ marginBottom: "8px" }}>Give someone a plan</div>
<div class="tiny faint" style=${{ marginBottom: "10px", lineHeight: 1.55 }}>
For payments taken outside PayPal, or to fix a webhook that missed. The plan stays until you revoke it.
</div>
<div class="grid two">
<${Text} label="Buyer's email" value=${email} onChange=${setEmail} placeholder="student@example.com" />
<${Select} label="Plan" value=${planId} onChange=${setPlanId}
options=${cloud.plans.map((p) => ({ value: p.id, label: p.name + " · " + money(p.price_cents, p.currency) }))} />
</div>
${error && html`<div style=${{ marginTop: "8px" }}><${Notice} kind="error">${error}<//></div>`}
<button class="btn primary small" style=${{ marginTop: "10px" }} onClick=${grant} disabled=${busy}>${busy ? html`<span class="spin"></span>` : "Grant access"}</button>
</div>
<div class="section-head"><h2 class="section-title">Access</h2></div>
<div class="card">
${cloud.entitlements.length === 0
? html`<div class="empty">No plans have been granted yet.</div>`
: html`<div class="list">
${cloud.entitlements.map(
(e) => html`<div class="list-row" key=${e.id}>
<div class="main">
<div class="t">${e.email || e.user_id || "—"} <span class="pill neutral" style=${{ marginLeft: "6px" }}>${e.plan_id}</span>
${e.revoked && html`<span class="pill danger" style=${{ marginLeft: "6px" }}>Revoked</span>`}</div>
<div class="s">${e.source || "grant"} · ${new Date(e.granted_at || Date.now()).toLocaleDateString("en-GB")}${e.expires_at ? " → " + new Date(e.expires_at).toLocaleDateString("en-GB") : ""}</div>
</div>
${!e.revoked && html`<button class="btn small danger" onClick=${() => cloud.revokeGrant(e.id)}>Revoke</button>`}
</div>`
)}
</div>`}
</div>
<div class="section-head"><h2 class="section-title">Recent model spend</h2></div>
<div class="card">
${cloud.usage.length === 0
? html`<div class="empty">No hosted model calls have been recorded yet.</div>`
: html`<div class="list">
${cloud.usage.slice(0, 12).map(
(u) => html`<div class="list-row" key=${u.id}>
<div class="main"><div class="t">${u.model_id}</div>
<div class="s">${new Date(u.created_at || Date.now()).toLocaleString("en-GB")} · ${u.tokens_in || 0} in / ${u.tokens_out || 0} out</div></div>
<span class="pill neutral">${money(u.cost_cents)}</span>
</div>`
)}
</div>`}
</div>
</div>`;
}
// ---------------------------------------------------------------------------
// Console
// ---------------------------------------------------------------------------
const TABS = [
{ id: "overview", label: "Overview" },
{ id: "plans", label: "Plans" },
{ id: "models", label: "Models & keys" },
{ id: "wording", label: "Wording" },
{ id: "paypal", label: "PayPal" },
{ id: "people", label: "People" },
{ id: "supabase", label: "Supabase" }
];
export function Developer() {
const cloud = useCloud();
const [tab, setTab] = useState("overview");
const { editing, setEditing } = useEditMode();
if (!cloud.isDev) {
return html`<main class="page narrow">
<${Head} kicker="Developer" title="This area is not yours." subtitle=${cloud.configured ? "Only " + DEVELOPER_EMAIL + " can change plans, prices, models or wording." : "Connect Supabase first."} />
<div class="card" style=${{ marginTop: "16px" }}>
${cloud.configured
? html`<${Notice} kind="warn">Signed in${cloud.user ? " as " + cloud.user.email : " as a guest"}. The developer console belongs to ${DEVELOPER_EMAIL}.<//>`
: html`<${Notice} kind="info">This copy is not connected to Supabase yet, so there is no developer account to check against. Connect it to lock this page down.<//>`}
<div class="row" style=${{ marginTop: "10px" }}>
<a class="btn small" href="#/account">Account</a>
<a class="btn small" href="#/pricing">Plans</a>
</div>
</div>
</main>`;
}
return html`<main class="page">
<${Head} kicker="Developer" title="Console"
subtitle=${cloud.configured ? "Signed in as " + cloud.user.email : "Preview mode — changes stay in this browser until Supabase is connected."}
right=${cloud.configured ? html`<${Pill} tone="green">Developer<//>` : html`<${Pill} tone="warn">Preview<//>`} />
<div class="tabs" style=${{ marginTop: "16px" }}>
${TABS.map((t) => html`<button key=${t.id} class=${"tab" + (tab === t.id ? " active" : "")} onClick=${() => setTab(t.id)}>${t.label}</button>`)}
</div>
<div style=${{ marginTop: "14px" }}>
${tab === "overview" &&
html`<div>
<div class="grid four">
<${Stat} label="Plans" value=${cloud.plans.length} note=${cloud.plans.filter((p) => p.active !== false).length + " published"} />
<${Stat} label="Models" value=${cloud.models.length} note=${cloud.models.filter((m) => m.enabled !== false).length + " enabled"} />
<${Stat} label="People" value=${cloud.entitlements.filter((e) => !e.revoked).length} note="with access" />
<${Stat} label="Spend" value=${money(cloud.usage.reduce((s, u) => s + Number(u.cost_cents || 0), 0))} note="recent model usage" />
</div>
<div class="grid two" style=${{ marginTop: "12px" }}>
<div class="card">
<div class="section-title" style=${{ marginBottom: "8px" }}>Payments</div>
<div class="row between"><span class="tiny muted">Mode</span><span class="tiny mono">${cloud.settings.paypal_mode}</span></div>
<div class="row between" style=${{ marginTop: "6px" }}><span class="tiny muted">Checkout</span><span class="tiny mono">${cloud.settings.checkout_mode}</span></div>
<div class="row between" style=${{ marginTop: "6px" }}><span class="tiny muted">Client ID</span><span class="tiny mono">${cloud.settings.paypal_client_id ? "set" : "missing"}</span></div>
<div class="row between" style=${{ marginTop: "6px" }}><span class="tiny muted">Plans with a link or plan ID</span><span class="tiny mono">${cloud.plans.filter((p) => p.paypal_payment_link || p.paypal_plan_id).length}/${cloud.plans.length}</span></div>
<button class="btn small" style=${{ marginTop: "10px" }} onClick=${() => setTab("paypal")}>Open PayPal settings</button>
</div>
<div class="card">
<div class="section-title" style=${{ marginBottom: "8px" }}>The page itself</div>
<div class="tiny muted" style=${{ lineHeight: 1.6 }}>Change any wording a visitor reads, without editing code. Turn edit mode on, then click the text.</div>
<div class="row" style=${{ marginTop: "10px" }}>
<button class=${"btn small " + (editing ? "green" : "primary")} onClick=${() => setEditing(!editing)}>${editing ? "Editing" : "Turn on edit mode"}</button>
<button class="btn small" onClick=${() => setTab("wording")}>Changed wording</button>
</div>
</div>
</div>
${!cloud.configured &&
html`<div class="card" style=${{ marginTop: "12px" }}>
<div class="row between wrap">
<div style=${{ maxWidth: "560px" }}>
<div style=${{ fontWeight: 600 }}>Connect Supabase to share any of this</div>
<div class="tiny faint" style=${{ marginTop: "3px", lineHeight: 1.55 }}>
In preview mode plans, models and wording live in this browser only. Connecting a project puts logins and shared content in place.
</div>
</div>
<a class="btn primary small" href="#/connect">Connect Supabase</a>
</div>
</div>`}
</div>`}
${tab === "plans" && html`<${PlansTab} />`}
${tab === "models" && html`<${ModelsTab} />`}
${tab === "wording" && html`<${WordingTab} />`}
${tab === "paypal" && html`<${PayPalTab} />`}
${tab === "people" && html`<${PeopleTab} />`}
${tab === "supabase" && html`<${SupabaseTab} />`}
</div>
</main>`;
}