ci/woodpecker/push/woodpecker Pipeline was successful
Fixing portal_post only closed half of it: portal_get still turned any non-200 from the portal into a 502, so a refusal or a rate limit on a read path would have arrived as a gateway error as well. Both helpers now pass the portal's own status and detail through.
1272 lines
61 KiB
Python
1272 lines
61 KiB
Python
"""Admin Panel — co-op-wide member overview, spend, and balance management.
|
|
|
|
Security model:
|
|
- Authentication is done by Cloudron's proxyAuth wall (SSO). Cloudron injects
|
|
the authenticated user's username via X-Remote-User.
|
|
- Access is further restricted to a small ADMIN_USERNAMES allowlist (checked
|
|
against the injected username), so only designated admins see this panel.
|
|
- This app calls the member portal's /admin/overview and /admin/set-balance
|
|
endpoints, authenticated with the portal's dedicated ADMIN_TOKEN (the
|
|
X-Admin-Token header — NOT the webhook's URL token, which cannot unlock
|
|
/admin/*).
|
|
|
|
Environment (Cloudron env vars):
|
|
PORTAL_BASE — base URL of the member portal
|
|
ADMIN_TOKEN — the portal's admin/webhook token (for /admin/* endpoints)
|
|
ADMIN_USERNAMES — comma-separated list of allowed Cloudron usernames
|
|
"""
|
|
|
|
import os
|
|
import logging
|
|
from pathlib import Path
|
|
|
|
import httpx
|
|
from fastapi import FastAPI, Request, HTTPException
|
|
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
|
|
|
|
from app import oidc
|
|
|
|
# The oidc module is SHARED (byte-identical copy of the canonical
|
|
# ops-docs: scripts/shared/oidc_client.py — see tests/test_oidc_sync.py);
|
|
# this app's identity (logger name, session cookie, session salt) is set
|
|
# here. The cookie name and salt are the app's historical values, so
|
|
# existing sessions survive the consolidation.
|
|
oidc.configure("admin-panel", "admin_oidc_session", "admin-panel-oidc-session")
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
logger = logging.getLogger("admin-panel")
|
|
|
|
PORTAL_BASE = os.environ.get("PORTAL_BASE", "").rstrip("/")
|
|
ADMIN_TOKEN = os.environ.get("ADMIN_TOKEN", "")
|
|
ADMIN_USERNAMES = {
|
|
u.strip().lower()
|
|
for u in os.environ.get("ADMIN_USERNAMES", "").split(",")
|
|
if u.strip()
|
|
}
|
|
|
|
app = FastAPI()
|
|
|
|
|
|
def get_identity(request: Request) -> str:
|
|
"""Return the authenticated user's identity (Cloudron username).
|
|
|
|
Reads the validated OIDC session cookie. No header fallback — the app no
|
|
longer trusts a client-supplied identity header (that path existed only
|
|
during the proxyAuth → OIDC transition and is now removed).
|
|
"""
|
|
if not oidc.is_oidc_configured():
|
|
return ""
|
|
token = request.cookies.get(oidc.SESSION_COOKIE)
|
|
if not token:
|
|
return ""
|
|
return oidc.read_session(token) or ""
|
|
|
|
|
|
def is_admin(request: Request) -> bool:
|
|
identity = get_identity(request)
|
|
if not identity:
|
|
return False
|
|
return identity.lower() in ADMIN_USERNAMES
|
|
|
|
|
|
async def portal_get(path: str) -> dict:
|
|
async with httpx.AsyncClient(timeout=20.0) as client:
|
|
r = await client.get(f"{PORTAL_BASE}{path}", headers={"X-Admin-Token": ADMIN_TOKEN})
|
|
if r.status_code != 200:
|
|
# Same rule as portal_post: the portal's own status and words, never a
|
|
# blanket 502. A rate limit or a refusal is not a gateway failure, and
|
|
# reporting one as the other tells the operator nothing they can act on.
|
|
try:
|
|
detail = r.json().get("detail", r.text)
|
|
except Exception:
|
|
detail = r.text
|
|
raise HTTPException(r.status_code, f"Portal error {r.status_code}: {detail}")
|
|
return r.json()
|
|
|
|
|
|
async def portal_post(path: str, payload: dict) -> dict:
|
|
async with httpx.AsyncClient(timeout=20.0) as client:
|
|
r = await client.post(f"{PORTAL_BASE}{path}", json=payload, headers={"X-Admin-Token": ADMIN_TOKEN})
|
|
if r.status_code not in (200, 201):
|
|
try:
|
|
detail = r.json().get("detail", r.text)
|
|
except Exception:
|
|
detail = r.text
|
|
# Pass the portal's OWN status through. Collapsing every upstream failure
|
|
# into 502 turned a plain rate limit ("Too many requests. Slow down.")
|
|
# into "Could not send guest access (502)" — a gateway error the operator
|
|
# cannot act on, for a condition that clears in a minute and says so.
|
|
raise HTTPException(r.status_code, f"Portal error {r.status_code}: {detail}")
|
|
return r.json()
|
|
|
|
|
|
@app.get("/healthz")
|
|
async def healthz():
|
|
return {"status": "ok"}
|
|
|
|
|
|
@app.get("/")
|
|
async def index(request: Request):
|
|
identity = get_identity(request)
|
|
# Unauthenticated + OIDC configured → send to the OIDC login.
|
|
if not identity:
|
|
if oidc.is_oidc_configured():
|
|
return RedirectResponse("/auth/openid/login", status_code=302)
|
|
return HTMLResponse(
|
|
"<h1>Forbidden</h1><p>This panel is restricted to administrators.</p>",
|
|
status_code=403,
|
|
)
|
|
# Authenticated but not an admin → forbid.
|
|
if identity.lower() not in ADMIN_USERNAMES:
|
|
return HTMLResponse(
|
|
"<h1>Forbidden</h1><p>This panel is restricted to administrators.</p>",
|
|
status_code=403,
|
|
)
|
|
# no-store: the page is one inline script with no validators, so a cached
|
|
# copy runs the PREVIOUS deploy's JS and makes a working app look broken
|
|
# (it did, 2026-11-13).
|
|
return HTMLResponse(render_page(), headers={"Cache-Control": "no-store"})
|
|
|
|
|
|
@app.get("/api/overview")
|
|
async def api_overview(request: Request):
|
|
if not is_admin(request):
|
|
return JSONResponse({"error": "forbidden"}, status_code=403)
|
|
return await portal_get("/admin/overview")
|
|
|
|
|
|
@app.get("/api/model-usage")
|
|
async def api_model_usage(request: Request):
|
|
if not is_admin(request):
|
|
return JSONResponse({"error": "forbidden"}, status_code=403)
|
|
try:
|
|
return await portal_get("/admin/model-usage")
|
|
except HTTPException as e:
|
|
return JSONResponse({"error": e.detail}, status_code=e.status_code)
|
|
|
|
|
|
@app.get("/api/metrics")
|
|
async def api_metrics(request: Request, days: int = 730):
|
|
"""Daily metrics series from the portal (members + usage history).
|
|
|
|
The portal owns this data (metrics_daily, refreshed 03:15 UTC); the panel
|
|
only reads it. Fetched once at the widest range and sliced client-side, so
|
|
the period toggle never refetches.
|
|
"""
|
|
if not is_admin(request):
|
|
return JSONResponse({"error": "forbidden"}, status_code=403)
|
|
try:
|
|
return await portal_get(f"/admin/metrics/series?days={max(1, min(int(days), 730))}")
|
|
except HTTPException as e:
|
|
return JSONResponse({"error": e.detail}, status_code=e.status_code)
|
|
|
|
|
|
@app.get("/api/money-series")
|
|
async def api_money_series(request: Request):
|
|
"""Revenue / token spend / OC balance series (portal /admin/money-series).
|
|
|
|
The portal owns this data and caches it hourly (the OC queries are slow);
|
|
the panel only reads it. The full history comes back in one payload — the
|
|
period and spend-mode toggles slice client-side and never refetch.
|
|
"""
|
|
if not is_admin(request):
|
|
return JSONResponse({"error": "forbidden"}, status_code=403)
|
|
try:
|
|
return await portal_get("/admin/money-series")
|
|
except HTTPException as e:
|
|
return JSONResponse({"error": e.detail}, status_code=e.status_code)
|
|
|
|
|
|
@app.post("/api/set-balance")
|
|
async def api_set_balance(request: Request):
|
|
if not is_admin(request):
|
|
return JSONResponse({"error": "forbidden"}, status_code=403)
|
|
body = await request.json()
|
|
email = (body.get("email") or "").strip().lower()
|
|
if not email:
|
|
return JSONResponse({"error": "Missing email"}, status_code=400)
|
|
payload = {"email": email}
|
|
if "add" in body:
|
|
payload["add"] = float(body["add"])
|
|
elif "balance" in body:
|
|
payload["balance"] = float(body["balance"])
|
|
else:
|
|
return JSONResponse({"error": "Provide 'balance' or 'add'"}, status_code=400)
|
|
try:
|
|
return await portal_post("/admin/set-balance", payload)
|
|
except HTTPException as e:
|
|
return JSONResponse({"error": e.detail}, status_code=e.status_code)
|
|
|
|
|
|
@app.post("/api/set-credits")
|
|
async def api_set_credits(request: Request):
|
|
if not is_admin(request):
|
|
return JSONResponse({"error": "forbidden"}, status_code=403)
|
|
body = await request.json()
|
|
email = (body.get("email") or "").strip().lower()
|
|
if not email:
|
|
return JSONResponse({"error": "Missing email"}, status_code=400)
|
|
payload = {"email": email, "reason": body.get("reason") or "admin adjustment"}
|
|
if "add" in body:
|
|
payload["add"] = float(body["add"])
|
|
elif "set" in body:
|
|
payload["set"] = float(body["set"])
|
|
else:
|
|
return JSONResponse({"error": "Provide 'set' or 'add'"}, status_code=400)
|
|
try:
|
|
return await portal_post("/admin/set-credits", payload)
|
|
except HTTPException as e:
|
|
return JSONResponse({"error": e.detail}, status_code=e.status_code)
|
|
|
|
|
|
def guest_duplicate_refusal(gq: dict, email: str) -> str | None:
|
|
"""Server-side duplicate-guest guard (pure — testable without FastAPI).
|
|
|
|
Decided from the portal's guests ledger BEFORE any provisioning call, so
|
|
a double submit from ANY client (the panel form, a retry, a script)
|
|
cannot create a second account for the same recipient. Refuses when an
|
|
ACTIVE guest account for the email already exists (guests ledger row with
|
|
status 'active' — an expired/depleted row is not a live account, so it
|
|
falls through to the portal's authoritative one-guest-per-recipient-ever
|
|
refusal).
|
|
|
|
Returns the refusal message, or None when the request may proceed. The
|
|
portal's own recipient-side guard (one guest per recipient ever, no
|
|
existing portal row) remains the last authority behind this.
|
|
"""
|
|
recipient = (email or "").strip().lower()
|
|
if not recipient:
|
|
return None
|
|
for row in (gq.get("ledger") or []):
|
|
if ((row.get("recipient") or "").strip().lower() == recipient
|
|
and (row.get("status") or "").strip().lower() == "active"):
|
|
return (f"A guest account for {recipient} already exists — "
|
|
"no second account was created")
|
|
return None
|
|
|
|
|
|
@app.post("/api/provision-guest")
|
|
async def api_provision_guest(request: Request):
|
|
"""Provision a guest account via the portal's /admin/provision-guest.
|
|
|
|
The standard guest-invite form: the guest's email (required) plus an
|
|
OPTIONAL display name — passed through as the guest's initial display
|
|
name; when empty, nothing is derived (the guest chooses their own name
|
|
at Cloudron setup and the invitation greets neutrally). The portal
|
|
records the co-op's ADMIN account as the inviter — admins are not bound
|
|
by the member's one-per-30-days cap, and the recipient-side guards (one
|
|
guest per recipient ever, no existing portal row) still run there. A
|
|
refusal is surfaced to the operator as-is.
|
|
|
|
A server-side duplicate guard runs HERE, before the portal call: an
|
|
active guest for the same email is refused with a specific message
|
|
instead of a second account being created (the form's
|
|
disable-while-sending only guards this one page; this guard holds for
|
|
any client).
|
|
"""
|
|
if not is_admin(request):
|
|
return JSONResponse({"error": "forbidden"}, status_code=403)
|
|
body = await request.json()
|
|
email = (body.get("email") or "").strip().lower()
|
|
name = (body.get("name") or "").strip()
|
|
if not email or "@" not in email:
|
|
return JSONResponse({"error": "A valid recipient email is required"}, status_code=400)
|
|
try:
|
|
gq = await portal_get("/admin/guest-ledger")
|
|
except HTTPException:
|
|
gq = {} # ledger unreadable — fall through; the portal's own guard still runs
|
|
refusal = guest_duplicate_refusal(gq, email)
|
|
if refusal:
|
|
return JSONResponse({"error": refusal}, status_code=409)
|
|
try:
|
|
return await portal_post("/admin/provision-guest", {"email": email, "name": name})
|
|
except HTTPException as e:
|
|
return JSONResponse({"error": e.detail}, status_code=e.status_code)
|
|
|
|
|
|
@app.get("/api/guest-ledger")
|
|
async def api_guest_ledger(request: Request):
|
|
"""The guests ledger (portal /admin/guest-ledger).
|
|
|
|
Every guest access sent and what became of it — the feed behind the
|
|
duplicate-send guard. (The member guest-request queue is GONE with the
|
|
approval gate, removed 2026-11-08: member invitations provision
|
|
immediately, so there is nothing to approve.)
|
|
"""
|
|
if not is_admin(request):
|
|
return JSONResponse({"error": "forbidden"}, status_code=403)
|
|
try:
|
|
return await portal_get("/admin/guest-ledger")
|
|
except HTTPException as e:
|
|
return JSONResponse({"error": e.detail}, status_code=e.status_code)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# OIDC routes — authorization-code flow against Cloudron's OIDC provider.
|
|
# Active only when the `oidc` addon is configured (CLOUDRON_OIDC_* present).
|
|
# During the transition the legacy proxyAuth header still works as a fallback.
|
|
# ---------------------------------------------------------------------------
|
|
|
|
@app.get("/auth/openid/login")
|
|
async def oidc_login(request: Request):
|
|
if not oidc.is_oidc_configured():
|
|
raise HTTPException(404, "OIDC not configured")
|
|
login_url, state, nonce = oidc.build_login_url(request.headers.get("host", ""))
|
|
resp = RedirectResponse(login_url, status_code=302)
|
|
# Short-lived, HttpOnly, SameSite=Lax cookies to carry state/nonce.
|
|
resp.set_cookie("oidc_state", state, max_age=600, httponly=True, samesite="lax")
|
|
resp.set_cookie("oidc_nonce", nonce, max_age=600, httponly=True, samesite="lax")
|
|
return resp
|
|
|
|
|
|
@app.get("/auth/openid/callback")
|
|
async def oidc_callback(request: Request):
|
|
if not oidc.is_oidc_configured():
|
|
raise HTTPException(404, "OIDC not configured")
|
|
code = request.query_params.get("code")
|
|
state = request.query_params.get("state")
|
|
expected_state = request.cookies.get("oidc_state")
|
|
nonce = request.cookies.get("oidc_nonce")
|
|
|
|
if not code or not state or not expected_state or not nonce:
|
|
return HTMLResponse("<h1>Login failed</h1><p>Incomplete OIDC callback.</p>", status_code=400)
|
|
if state != expected_state:
|
|
return HTMLResponse("<h1>Login failed</h1><p>State mismatch (possible CSRF).</p>", status_code=400)
|
|
|
|
try:
|
|
identity = await oidc.exchange_code(code, request.headers.get("host", ""), nonce)
|
|
except ValueError as e:
|
|
logger.warning("OIDC login failed: %s", e)
|
|
return HTMLResponse("<h1>Login failed</h1><p>Could not complete sign-in.</p>", status_code=400)
|
|
|
|
session = oidc.write_session(identity)
|
|
resp = RedirectResponse("/", status_code=302)
|
|
resp.set_cookie(oidc.SESSION_COOKIE, session, max_age=oidc.SESSION_MAX_AGE, httponly=True, samesite="lax")
|
|
resp.delete_cookie("oidc_state")
|
|
resp.delete_cookie("oidc_nonce")
|
|
return resp
|
|
|
|
|
|
@app.get("/logout")
|
|
async def logout():
|
|
resp = RedirectResponse("/", status_code=302)
|
|
resp.delete_cookie(oidc.SESSION_COOKIE)
|
|
return resp
|
|
|
|
|
|
def _esc(s: str) -> str:
|
|
return s.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """)
|
|
|
|
|
|
def render_page() -> str:
|
|
return PAGE_HTML
|
|
|
|
|
|
# The shared chart module (canonical: ops-docs scripts/shared/coop_chart.js,
|
|
# byte-identical copy at app/coop_chart.js — tests/test_chart_sync.py pins it)
|
|
# is spliced into the page's single <script> block at import time, above the
|
|
# page JS, which destructures CoOpChart into bare function names.
|
|
CHART_MODULE_JS = (Path(__file__).resolve().parent / "coop_chart.js").read_text()
|
|
|
|
PAGE_HTML = """<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>Inference Cooperative · Admin</title>
|
|
<style>
|
|
:root {
|
|
--cream: #faf8f5; --ink: #2d3327; --muted: #6b7a62;
|
|
--green-deep: #5b8c5a; --green-mid: #6ba86b; --border: #e4e0d8; --danger: #b3543a;
|
|
}
|
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
body { font-family: 'Figtree', -apple-system, 'Segoe UI', system-ui, sans-serif; background: var(--cream); color: var(--ink); line-height: 1.5; }
|
|
.wrap { max-width: 1120px; margin: 0 auto; padding: 32px 24px 48px; }
|
|
header { display: flex; align-items: center; gap: 14px; margin-bottom: 24px; }
|
|
.brand h1 { font-size: 20px; font-weight: 700; }
|
|
.brand .sub { color: var(--muted); font-size: 13px; }
|
|
.totals { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 16px; margin-bottom: 24px; }
|
|
.tot { background: #fff; border: 1px solid var(--border); border-radius: 12px; padding: 16px 20px; }
|
|
.tot .num { font-size: 24px; font-weight: 700; color: var(--green-deep); }
|
|
.tot .lbl { font-size: 12px; color: var(--muted); }
|
|
.tot .sub { font-size: 11px; color: var(--muted); margin-top: 3px; }
|
|
table { width: 100%; border-collapse: collapse; background: #fff; border: 1px solid var(--border); border-radius: 12px; overflow: hidden; }
|
|
th, td { text-align: left; padding: 10px 14px; border-bottom: 1px solid #f0ede6; font-size: 13px; }
|
|
th { background: #f6f4ee; color: var(--muted); font-weight: 600; font-size: 12px; }
|
|
tr:last-child td { border-bottom: none; }
|
|
.pill { display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: 11px; font-weight: 600; }
|
|
.pill.active { background: #eaf3ea; color: #2f5c30; }
|
|
.pill.inactive { background: #f6e9e5; color: var(--danger); }
|
|
.pill.manual { background: #f1e8da; color: #a97a4a; }
|
|
.pill.org { background: #e7edf5; color: #4a6a8a; }
|
|
.pill.grace { background: #fdf3e3; color: #a97a2a; }
|
|
.pill.guest { background: #efe7f2; color: #7a5a92; }
|
|
.pill.invited { background: #e7edf5; color: #4a6a8a; }
|
|
/* Standard guest-invite form (shared with the member dashboard): ONE field,
|
|
plain labels, fits a narrow frame. */
|
|
.guest-invite-card { background: #fff; border: 1px solid var(--border); border-radius: 12px; padding: 16px 20px; margin-top: 20px; }
|
|
.guest-invite-title { font-size: 14px; font-weight: 700; color: var(--ink); }
|
|
.guest-invite-sub { color: var(--muted); font-size: 12px; margin: 4px 0 12px; }
|
|
.guest-invite-form { display: flex; flex-direction: column; gap: 8px; max-width: 420px; }
|
|
.guest-invite-label { font-size: 12px; font-weight: 600; color: var(--muted); }
|
|
.guest-invite-form input { width: 100%; min-width: 0; padding: 9px 12px; border: 1px solid var(--border); border-radius: 8px; font-size: 14px; font-family: inherit; background: #fff; color: var(--ink); }
|
|
.guest-invite-form input:focus { outline: none; border-color: var(--green-mid); }
|
|
.guest-invite-btn { cursor: pointer; border: none; border-radius: 8px; background: var(--green-deep); color: #fff; font-size: 13px; font-weight: 600; padding: 10px 16px; align-self: flex-start; }
|
|
.guest-invite-btn:hover { background: #4e7a4d; }
|
|
.guest-invite-btn:disabled { opacity: 0.6; cursor: default; }
|
|
/* Outcome of a submit, shown INSIDE the card (the top flash sits above the
|
|
tabs — off-screen from a mid-page form — so an outcome only there is one
|
|
the operator never sees). Same palette as the .flash styles. */
|
|
.guest-invite-status { display: none; margin-top: 10px; padding: 10px 14px; border-radius: 8px; font-size: 13px; max-width: 420px; }
|
|
.guest-invite-status.ok { display: block; background: #eaf3ea; color: #2f5c30; }
|
|
.guest-invite-status.err { display: block; background: #f6e9e5; color: var(--danger); }
|
|
@media (max-width: 600px) { .guest-invite-btn { align-self: stretch; } }
|
|
/* Trends tab (charts). Colours come from the same vars as the rest of the
|
|
panel; the SVG is inline so there is no chart library and no CDN. */
|
|
.trend-controls { display: flex; gap: 22px; flex-wrap: wrap; margin: 14px 0 0; }
|
|
.trend-controls .range-group { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
|
.trend-card { background: #fff; border: 1px solid var(--border); border-radius: 12px; padding: 14px 16px 12px; margin-top: 12px; }
|
|
.trend-head { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; margin-bottom: 8px; }
|
|
.trend-title { font-weight: 700; font-size: 14px; color: var(--ink); }
|
|
.trend-body svg { display: block; width: 100%; height: auto; overflow: visible; }
|
|
.trend-empty { color: var(--muted); font-size: 13px; margin: 28px 0; text-align: center; }
|
|
/* Chart hover tooltip: one shared box for every chart, positioned near the
|
|
pointer and clamped inside the viewport. pointer-events:none so it can
|
|
never intercept a click on the chart underneath. */
|
|
.chart-tip { position: fixed; display: none; z-index: 60; pointer-events: none; background: #fff; border: 1px solid var(--border); border-radius: 8px; box-shadow: 0 2px 10px rgba(45,51,39,0.16); padding: 7px 10px; font-size: 12px; max-width: 280px; }
|
|
.chart-tip .tip-day { color: var(--muted); font-size: 11px; margin-bottom: 3px; }
|
|
.chart-tip .tip-row { display: flex; justify-content: space-between; gap: 14px; }
|
|
.chart-tip .tip-row span { color: var(--muted); }
|
|
.chart-tip .tip-row b { color: var(--ink); font-variant-numeric: tabular-nums; }
|
|
/* Money chart: legend keys. No caption — charts carry no explanatory text
|
|
under them (the chart rule). */
|
|
.money-legend { display: inline-flex; gap: 14px; flex-wrap: wrap; font-size: 12px; color: var(--muted); font-weight: 600; }
|
|
.money-legend .key { display: inline-flex; align-items: center; gap: 5px; }
|
|
.money-legend .sw { display: inline-block; width: 10px; height: 10px; border-radius: 3px; flex-shrink: 0; }
|
|
@media (max-width: 600px) { .trend-controls { gap: 10px; } .trend-card { padding: 12px 10px; } }
|
|
.num { font-variant-numeric: tabular-nums; }
|
|
.remaining-col { font-weight: 700; color: var(--green-deep); background: #eaf3ea; }
|
|
.flash { padding: 12px 16px; border-radius: 8px; margin: 16px 0; font-size: 14px; display: none; }
|
|
.flash.show { display: block; }
|
|
.flash.ok { background: #eaf3ea; color: #2f5c30; }
|
|
.flash.err { background: #f6e9e5; color: var(--danger); }
|
|
.adjust { display: inline-flex; gap: 6px; align-items: center; white-space: nowrap; }
|
|
.adjust input { width: 56px; padding: 4px 6px; border: 1px solid var(--border); border-radius: 6px; font-size: 12px; flex-shrink: 0; }
|
|
.adjust button { cursor: pointer; border: none; border-radius: 6px; background: var(--green-deep); color: #fff; font-size: 11px; font-weight: 600; padding: 4px 8px; flex-shrink: 0; }
|
|
.adjust button:hover { background: #4e7a4d; }
|
|
.adjust .credits-btn { background: var(--bronze, #a97a4a); }
|
|
.adjust .credits-btn:hover { background: #92693c; }
|
|
td:last-child, th:last-child { white-space: nowrap; }
|
|
.tabs { display: flex; gap: 8px; margin: 28px 0 12px; align-items: center; flex-wrap: wrap; }
|
|
.tabs h2 { font-size: 17px; font-weight: 700; margin-right: 8px; }
|
|
.tab-btn { cursor: pointer; border: 1px solid var(--border); background: #fff; color: var(--muted); border-radius: 8px; font-size: 13px; font-weight: 600; padding: 6px 14px; }
|
|
.tab-btn.active { background: var(--green-deep); color: #fff; border-color: var(--green-deep); }
|
|
.range-group { display: inline-flex; gap: 6px; margin-left: auto; align-items: center; }
|
|
.range-label { font-size: 12px; color: var(--muted); margin-right: 2px; }
|
|
.range-btn { cursor: pointer; border: 1px solid var(--border); background: #fff; color: var(--muted); border-radius: 8px; font-size: 12px; font-weight: 600; padding: 5px 12px; }
|
|
.range-btn.active { background: var(--green-mid); color: #fff; border-color: var(--green-mid); }
|
|
.members-all-time .balance-col.allowance-only,
|
|
.members-all-time .balance-col.remaining-only { display: none; }
|
|
.members-all-time .credits-col-head .mode-note::after,
|
|
.table-scroll { overflow-x: auto; border-radius: 12px; }
|
|
.table-scroll table { min-width: 980px; }
|
|
th.sortable { cursor: pointer; user-select: none; }
|
|
th.sortable:hover { color: var(--green-deep); }
|
|
th .arrow { font-size: 10px; margin-left: 3px; opacity: 0.7; }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="wrap">
|
|
<header>
|
|
<div class="brand">
|
|
<h1>Inference Cooperative</h1>
|
|
<div class="sub">Admin panel</div>
|
|
</div>
|
|
</header>
|
|
|
|
<div class="totals">
|
|
<div class="tot"><div class="num" id="tot-members">—</div><div class="lbl">members</div></div>
|
|
<div class="tot"><div class="num" id="tot-guests">—</div><div class="lbl">guests — guest access</div><div class="sub">excluded from member counts</div></div>
|
|
<div class="tot"><div class="num" id="tot-spend-cycle">—</div><div class="lbl">current balance used — members + co-op's own</div><div class="sub">co-op's own share: <span id="tot-spend-cycle-own">—</span></div></div>
|
|
<div class="tot"><div class="num" id="tot-spend-all">—</div><div class="lbl">all-time spend — members + co-op's own</div><div class="sub">co-op's own share: <span id="tot-spend-all-own">—</span></div></div>
|
|
</div>
|
|
|
|
<div class="flash" id="flash"></div>
|
|
|
|
<div class="tabs" style="margin-top:28px;">
|
|
<h2 id="view-title">Members</h2>
|
|
<button class="tab-btn active" id="tab-members" onclick="switchView('members')">Members</button>
|
|
<button class="tab-btn" id="tab-models" onclick="switchView('models')">Model usage</button>
|
|
<button class="tab-btn" id="tab-trends" onclick="switchView('trends')">Trends</button>
|
|
<span class="range-group" id="member-mode-group">
|
|
<button class="range-btn active" id="mmode-balance" onclick="setMemberMode('balance')">Balance</button>
|
|
<button class="range-btn" id="mmode-all" onclick="setMemberMode('all')">All time</button>
|
|
</span>
|
|
<span class="range-group" id="range-group" style="display:none;">
|
|
<span class="range-label">Period</span>
|
|
<button class="range-btn" id="range-30" onclick="setRange(30)">30 days</button>
|
|
<button class="range-btn active" id="range-all" onclick="setRange(0)">All time</button>
|
|
</span>
|
|
</div>
|
|
|
|
<div class="table-scroll">
|
|
<table id="table-members">
|
|
<thead>
|
|
<tr>
|
|
<th class="sortable" onclick="sortMembers('email')">Member<span class="arrow" id="arrow-members-email"></span></th>
|
|
<th class="sortable" onclick="sortMembers('active')">Status<span class="arrow" id="arrow-members-active"></span></th>
|
|
<th class="sortable" onclick="sortMembers('activated')">Activated<span class="arrow" id="arrow-members-activated"></span></th>
|
|
<th class="sortable" onclick="sortMembers('manual')">Source<span class="arrow" id="arrow-members-manual"></span></th>
|
|
<th class="sortable balance-col allowance-only" onclick="sortMembers('balance')">Allowance<span class="arrow" id="arrow-members-balance"></span></th>
|
|
<th class="sortable balance-col credits-col-head" onclick="sortMembers('credit_balance')">Credits<span class="mode-note"></span><span class="arrow" id="arrow-members-credit_balance"></span></th>
|
|
<th class="sortable" onclick="sortMembers('spend')"><span id="spend-mode-label">Spend</span><span class="arrow" id="arrow-members-spend"></span></th>
|
|
<th class="sortable balance-col" onclick="sortMembers('remaining')">Remaining<span class="arrow" id="arrow-members-remaining"></span></th>
|
|
<th class="sortable balance-col" onclick="sortMembers('reset_at')">Reset<span class="arrow" id="arrow-members-reset_at"></span></th>
|
|
<th>Adjust</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody id="rows"><tr><td colspan="8" style="color:var(--muted)">Loading…</td></tr></tbody>
|
|
</table>
|
|
</div>
|
|
|
|
<div id="guest-invite-section">
|
|
<div class="guest-invite-card">
|
|
<h3 class="guest-invite-title">Invite a guest</h3>
|
|
<p class="guest-invite-sub">Sends $2 of credits and 60 days of chat + dashboard access. The invitation comes from the co-op (admin) — no monthly cap.</p>
|
|
<form class="guest-invite-form" id="guest-invite-form" onsubmit="sendGuestAccess(event)">
|
|
<label class="guest-invite-label" for="guest-email">Their email</label>
|
|
<input id="guest-email" type="email" required placeholder="friend@example.com" autocomplete="off" inputmode="email" maxlength="254" />
|
|
<label class="guest-invite-label" for="guest-name">Their name (optional)</label>
|
|
<input id="guest-name" type="text" maxlength="80" autocomplete="off" placeholder="Only if you know it" />
|
|
<button type="submit" class="guest-invite-btn" id="guest-send">Send invite</button>
|
|
</form>
|
|
<div class="guest-invite-status" id="guest-invite-status" role="status" aria-live="polite"></div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="guests-section" style="display:none;">
|
|
<h3 style="margin:20px 0 8px;">Guests</h3>
|
|
<p style="color:var(--muted);font-size:12px;margin:0 0 8px;">Guest accounts — access an inviting member gave to someone outside the co-op. Not members — excluded from member counts; guest access lapses on its time box or when its credits are spent.</p>
|
|
<div class="table-scroll">
|
|
<table id="table-guests">
|
|
<thead>
|
|
<tr>
|
|
<th>Recipient</th>
|
|
<th>Invited by</th>
|
|
<th>Credits remaining</th>
|
|
<th>Expires</th>
|
|
<th>Status</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody id="guest-rows"></tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="trends-section" style="display:none;">
|
|
<div class="trend-controls">
|
|
<span class="range-group" id="trend-metrics">
|
|
<span class="range-label">Show</span>
|
|
<!-- The metric buttons are rendered from CoOpChart.CHART_METRICS, so this
|
|
panel and the member dashboard describe the same charts, in the same
|
|
order, with the same titles — Money included, as one metric among the
|
|
others. Editing the list here would defeat that: edit the canonical
|
|
module (ops-docs scripts/shared/coop_chart.js) instead. -->
|
|
</span>
|
|
<span class="range-group">
|
|
<span class="range-label">Period</span>
|
|
<button class="range-btn" id="tr-30" onclick="setTrendDays(30)">30 days</button>
|
|
<button class="range-btn active" id="tr-90" onclick="setTrendDays(90)">90 days</button>
|
|
<button class="range-btn" id="tr-all" onclick="setTrendDays(0)">All time</button>
|
|
</span>
|
|
</div>
|
|
<div class="trend-card">
|
|
<div class="trend-head">
|
|
<span class="trend-title" id="trend-title">Members</span>
|
|
<span id="trend-legend" class="money-legend"></span>
|
|
</div>
|
|
<div id="trend-body" class="trend-body"><p class="trend-empty">Loading</p></div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="agents-section" style="display:none;">
|
|
<h3 style="margin:20px 0 8px;">Agents</h3>
|
|
<p style="color:var(--muted);font-size:12px;margin:0 0 8px;">Bot and sandbox accounts. Not members — excluded from member counts; their usage is a collective expense.</p>
|
|
<div class="table-scroll">
|
|
<table id="table-agents">
|
|
<thead>
|
|
<tr>
|
|
<th>Account</th>
|
|
<th>Type</th>
|
|
<th>Spend</th>
|
|
<th>Budget</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody id="agent-rows"></tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="admins-section" style="display:none;">
|
|
<h3 style="margin:20px 0 8px;">Admin</h3>
|
|
<p style="color:var(--muted);font-size:12px;margin:0 0 8px;">Operator accounts (SSO owner and bot). Not members — excluded from member counts; their usage is a collective expense.</p>
|
|
<div class="table-scroll">
|
|
<table id="table-admins">
|
|
<thead>
|
|
<tr>
|
|
<th>Account</th>
|
|
<th>Type</th>
|
|
<th><span id="spend-mode-label-admin">Spend</span></th>
|
|
<th>Budget</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody id="admin-rows"></tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="table-scroll" style="margin-top:12px;">
|
|
<table id="table-models" style="display:none;">
|
|
<thead>
|
|
<tr>
|
|
<th class="sortable" onclick="sortModels('model')">Model<span class="arrow" id="arrow-models-model"></span></th>
|
|
<th class="sortable" onclick="sortModels('spend')">Spend<span class="arrow" id="arrow-models-spend"></span></th>
|
|
<th class="sortable" onclick="sortModels('tokens')">Tokens<span class="arrow" id="arrow-models-tokens"></span></th>
|
|
<th class="sortable" onclick="sortModels('requests')">Requests<span class="arrow" id="arrow-models-requests"></span></th>
|
|
</tr>
|
|
</thead>
|
|
<tbody id="model-rows"><tr><td colspan="4" style="color:var(--muted)">Loading…</td></tr></tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
|
|
<script>
|
|
/*@@CHART_MODULE@@*/
|
|
const $ = (id) => document.getElementById(id);
|
|
|
|
let flashTimer = null;
|
|
function flash(msg, ok) {
|
|
const f = $('flash');
|
|
f.textContent = msg;
|
|
f.className = 'flash show ' + (ok ? 'ok' : 'err');
|
|
// Clear the previous timer first, or a message shown soon after another is
|
|
// hidden by the FIRST message's timeout (hidden long before its own 6s).
|
|
if (flashTimer) clearTimeout(flashTimer);
|
|
flashTimer = setTimeout(() => { f.className = 'flash'; }, 6000);
|
|
}
|
|
|
|
// The invite card's OWN status line — the outcome where the operator is
|
|
// looking. Unlike the top flash it does NOT auto-hide: a submit's outcome
|
|
// should still be readable when the operator looks back at the form.
|
|
function inviteStatus(msg, ok) {
|
|
const s = $('guest-invite-status');
|
|
s.textContent = msg;
|
|
s.className = 'guest-invite-status ' + (ok ? 'ok' : 'err');
|
|
}
|
|
|
|
function fmt(n) { const v = Math.abs(Number(n)) < 0.005 ? 0 : (Number(n) || 0); return '$' + v.toFixed(2); }
|
|
|
|
async function loadModels() {
|
|
try {
|
|
const r = await fetch('/api/model-usage?days=' + rangeDays);
|
|
if (r.status === 403) return;
|
|
const d = await r.json();
|
|
if (d.error) { modelsData = []; $('model-rows').innerHTML = '<tr><td colspan="4" style="color:var(--muted)">' + esc(d.error) + '</td></tr>'; return; }
|
|
modelsData = d.models || [];
|
|
if (currentView === 'models') renderModels();
|
|
} catch (e) {
|
|
modelsData = [];
|
|
$('model-rows').innerHTML = '<tr><td colspan="4" style="color:var(--muted)">Could not load model usage.</td></tr>';
|
|
}
|
|
}
|
|
|
|
async function load() {
|
|
try {
|
|
const r = await fetch('/api/overview');
|
|
if (r.status === 403) { document.body.innerHTML = '<h1>Forbidden</h1>'; return; }
|
|
const d = await r.json();
|
|
$('tot-members').textContent = d.totals.members;
|
|
$('tot-spend-cycle').textContent = fmt(d.totals.total_spend);
|
|
// One number, the portal's own all-time spend (the shared helper behind the
|
|
// money payload and the member dashboard's card).
|
|
$('tot-spend-all').textContent = fmt(d.totals.spend_all_time ?? d.totals.total_all_time_spend ?? d.totals.total_spend);
|
|
// Break out the co-op's OWN (operator) portion of each total. These totals
|
|
// span members AND the co-op's own accounts, so the share is spelled out
|
|
// rather than left for the reader to guess.
|
|
$('tot-spend-cycle-own').textContent = fmt(d.totals.operator_spend ?? 0);
|
|
$('tot-spend-all-own').textContent = fmt(d.totals.operator_all_time_spend ?? 0);
|
|
// Guests: guest accounts live in their own list and never count as members.
|
|
// The portal splits them out (guests[]); an older payload that still tags
|
|
// rows account_type='guest' inside members[] is derived here, so the member
|
|
// count and the spend totals exclude guests in either payload shape.
|
|
const allRows = d.members || [];
|
|
const newShape = Array.isArray(d.guests);
|
|
guestsData = newShape ? d.guests : allRows.filter(m => (m.account_type || 'member') === 'guest');
|
|
membersData = newShape ? allRows : allRows.filter(m => (m.account_type || 'member') !== 'guest');
|
|
const gSpend = guestsData.reduce((s, m) => s + (Number(m.spend) || 0), 0);
|
|
const gAll = guestsData.reduce((s, m) => s + (Number(m.all_time_spend) || 0), 0);
|
|
const t = d.totals || {};
|
|
$('tot-members').textContent = newShape ? (t.members ?? membersData.length) : ((t.members ?? allRows.length) - guestsData.length);
|
|
$('tot-guests').textContent = guestsData.length;
|
|
$('tot-spend-cycle').textContent = fmt((t.total_spend ?? 0) - (newShape ? 0 : gSpend));
|
|
$('tot-spend-all').textContent = fmt(t.spend_all_time ?? ((t.total_all_time_spend ?? t.total_spend ?? 0) - (newShape ? 0 : gAll)));
|
|
adminsData = d.admins || [];
|
|
agentsData = d.agents || [];
|
|
if (currentView === 'members') renderMembers();
|
|
} catch (e) {
|
|
flash('Could not load: ' + e.message, false);
|
|
}
|
|
}
|
|
|
|
// ---- Trends (members + usage over time) ----
|
|
// Data comes from the portal, which owns it: metrics_daily is written by a
|
|
// 03:15 UTC scheduler task inside the portal app. Fetched once at the widest
|
|
// range; the metric and period toggles re-render client-side without refetching.
|
|
let trendsData = null;
|
|
let trendMetric = "members"; // members | spend | requests
|
|
let trendDays = 90; // 0 = all time
|
|
|
|
// ---- Trends: ONE chart area, described by the shared module ----
|
|
// Every metric this page can show — Money included — is defined once in
|
|
// CoOpChart.CHART_METRICS (canonical: ops-docs scripts/shared/coop_chart.js),
|
|
// which the member dashboard reads as well. This app owns the DATA (which
|
|
// endpoint feeds a metric, and which fetch it is allowed to make) and the DOM;
|
|
// the chart itself — titles, shape, axis rule, formatters — comes from the
|
|
// module, so the two UIs cannot drift apart again.
|
|
//
|
|
// A metric with no entry here is one this page can draw from ANOTHER source:
|
|
// METRIC_SOURCE maps metric -> fetch. Adding a metric to the shared list puts
|
|
// its button in both UIs at once; wiring it in one app only is what this map is.
|
|
const METRIC_SOURCE = {
|
|
members: "metrics", requests: "metrics", spend: "metrics",
|
|
energy: "metrics", co2e: "metrics",
|
|
money: "money"
|
|
};
|
|
|
|
function buildMetricButtons() {
|
|
const row = $("trend-metrics");
|
|
if (!row || row.getAttribute("data-built") === "1") return;
|
|
let html = "";
|
|
for (const def of CHART_METRICS) {
|
|
html += '<button class="range-btn" id="tm-' + def.id + '" data-metric="' + def.id + '">'
|
|
+ esc(def.title) + "</button>";
|
|
}
|
|
row.insertAdjacentHTML("beforeend", html);
|
|
row.setAttribute("data-built", "1");
|
|
// Delegated, not an inline handler: an inline onclick inside this
|
|
// Python triple-quoted string is exactly where a quote escape can
|
|
// silently break the whole page, and the escape that ships is not the
|
|
// one the raw source text shows.
|
|
if (!row.getAttribute("data-wired")) {
|
|
row.addEventListener("click", function (e) {
|
|
const b = e.target && e.target.closest ? e.target.closest("button[data-metric]") : null;
|
|
if (b) setTrendMetric(b.getAttribute("data-metric"));
|
|
});
|
|
row.setAttribute("data-wired", "1");
|
|
}
|
|
syncMetricButtons();
|
|
}
|
|
|
|
function syncMetricButtons() {
|
|
for (const def of CHART_METRICS) {
|
|
const b = $("tm-" + def.id);
|
|
if (b) b.className = "range-btn" + (def.id === trendMetric ? " active" : "");
|
|
}
|
|
}
|
|
|
|
async function loadMetrics() {
|
|
if (trendsData) { renderTrends(); return; }
|
|
const host = $("trend-body");
|
|
try {
|
|
const r = await fetch("/api/metrics?days=730");
|
|
if (r.status === 403) { host.innerHTML = "<p class=trend-empty>Forbidden</p>"; return; }
|
|
const d = await r.json();
|
|
if (d.error) { host.innerHTML = "<p class=trend-empty>" + d.error + "</p>"; return; }
|
|
trendsData = d.series || [];
|
|
renderTrends();
|
|
} catch (e) {
|
|
host.innerHTML = "<p class=trend-empty>Could not load trends</p>";
|
|
}
|
|
}
|
|
|
|
// The money metric's rows come from /api/money-series (the OC queries behind it
|
|
// are slow, so the portal caches them server-side). Fetched on first use.
|
|
async function loadMoneySeries() {
|
|
if (moneyData) { renderTrends(); return; }
|
|
const host = $("trend-body");
|
|
try {
|
|
const r = await fetch("/api/money-series");
|
|
if (r.status === 403) { host.innerHTML = "<p class=trend-empty>Forbidden</p>"; return; }
|
|
const d = await r.json();
|
|
if (d.error) { host.innerHTML = "<p class=trend-empty>" + esc(d.error) + "</p>"; return; }
|
|
moneyData = d;
|
|
renderTrends();
|
|
} catch (e) {
|
|
host.innerHTML = "<p class=trend-empty>Could not load the money series.</p>";
|
|
}
|
|
}
|
|
|
|
// Rows for a metric, or null when this page cannot get them. One place decides
|
|
// which fetch a metric needs, so setTrendMetric and the first paint agree.
|
|
function metricRows(id) {
|
|
const src = METRIC_SOURCE[id];
|
|
if (!src) return null;
|
|
if (src === "money") return moneyData ? (moneyData.series || []) : null;
|
|
return trendsData;
|
|
}
|
|
|
|
function loadForMetric() {
|
|
const src = METRIC_SOURCE[trendMetric];
|
|
if (src === "money") { if (moneyData) renderTrends(); else loadMoneySeries(); return; }
|
|
if (trendsData) renderTrends(); else loadMetrics();
|
|
}
|
|
|
|
function setTrendMetric(m) {
|
|
trendMetric = m;
|
|
syncMetricButtons();
|
|
loadForMetric();
|
|
}
|
|
|
|
function setTrendDays(d) {
|
|
trendDays = d;
|
|
$("tr-30").className = "range-btn" + (d === 30 ? " active" : "");
|
|
$("tr-90").className = "range-btn" + (d === 90 ? " active" : "");
|
|
$("tr-all").className = "range-btn" + (d === 0 ? " active" : "");
|
|
renderTrends();
|
|
}
|
|
|
|
// ---- Shared chart module ----
|
|
// Chart rendering + the exact-value hover tooltips come from the shared
|
|
// CoOpChart module (canonical: ops-docs scripts/shared/coop_chart.js,
|
|
// byte-identical copy shipped in this image and spliced in above). Destructure
|
|
// the pieces this page uses so call sites keep bare names. The full contract
|
|
// (stamp data-tip-host/i, then registerChartTips with the EXACT values) is
|
|
// documented in the module header.
|
|
const {
|
|
registerChartTips, hideChartTip, showChartTip, moveChartTip, chartTipTarget,
|
|
chartTipData, niceStep, measuredRuns, chartFrame, dateMarks, drawBars,
|
|
drawLineRuns, hoverTargets,
|
|
CHART_METRICS, metricDef, fmtMetric, fmtMoney, renderChart
|
|
} = CoOpChart;
|
|
|
|
function renderTrends() {
|
|
const host = $("trend-body");
|
|
if (!host) return;
|
|
hideChartTip();
|
|
const def = metricDef(trendMetric);
|
|
const legendEl = $("trend-legend");
|
|
$("trend-title").textContent = def.title;
|
|
const all = metricRows(trendMetric);
|
|
if (!all) {
|
|
// Two different situations, said differently: a metric this page HAS a
|
|
// source for but has not fetched yet, and one it has no source for at all.
|
|
host.innerHTML = METRIC_SOURCE[trendMetric]
|
|
? "<p class=trend-empty>Loading</p>"
|
|
: "<p class=trend-empty>Not available on this page.</p>";
|
|
if (legendEl) legendEl.innerHTML = "";
|
|
return;
|
|
}
|
|
const rows = trendDays === 0 ? all : all.slice(-trendDays);
|
|
// One renderer for every metric, shared with the member dashboard: it draws
|
|
// the chart, registers the exact tooltip values, and hands back the legend.
|
|
const out = renderChart({ host: "trend-body", def, rows, gridStroke: "var(--border)" });
|
|
if (out.empty) {
|
|
host.innerHTML = "<p class=trend-empty>Not enough history yet.</p>";
|
|
if (legendEl) legendEl.innerHTML = "";
|
|
return;
|
|
}
|
|
host.innerHTML = out.svg;
|
|
if (legendEl) {
|
|
legendEl.innerHTML = out.legend.map(it =>
|
|
'<span class="key"><span class="sw" style="background:' + it.color + '"></span>'
|
|
+ esc(it.name) + "</span>").join("");
|
|
}
|
|
}
|
|
|
|
// ---- Money is now a metric of Trends, like everything else ------------
|
|
// The chart (cumulative revenue, cumulative token spend, and the OC balance —
|
|
// which exists only from the day the snapshots began, so it draws as a gap
|
|
// before that, never a zero) is DEFINED in the shared module and drawn by
|
|
// renderTrends() when the money metric is selected: the same chart the member
|
|
// dashboard draws from the same definition. This page keeps only the rows it
|
|
// fetched; the period toggle above governs it like every other metric, so the
|
|
// separate period/spend-mode controls are gone.
|
|
let moneyData = null;
|
|
|
|
// ---- shared state ----
|
|
let membersData = [];
|
|
let guestsData = [];
|
|
let adminsData = [];
|
|
let agentsData = [];
|
|
let modelsData = [];
|
|
let currentView = 'members';
|
|
let memberSort = { key: 'spend', dir: -1 }; // leaderboard default: most spend first
|
|
let modelSort = { key: 'spend', dir: -1 };
|
|
let rangeDays = 0; // 0 = all time
|
|
let memberMode = 'balance'; // 'balance' | 'all' — Members view: current-balance figures vs all-time spend
|
|
|
|
function arrowFor(key, sortState) {
|
|
if (sortState.key !== key) return '';
|
|
return sortState.dir === 1 ? '▲' : '▼';
|
|
}
|
|
|
|
function clearArrows(table, sortState) {
|
|
document.querySelectorAll('#table-' + table + ' .arrow').forEach(el => { el.textContent = ''; });
|
|
document.querySelectorAll('#table-' + table + ' th').forEach(th => {
|
|
const span = th.querySelector('.arrow');
|
|
if (!span) return;
|
|
const key = th.getAttribute('onclick')?.match(/'([^']+)'/)?.[1];
|
|
if (key) span.textContent = arrowFor(key, sortState);
|
|
});
|
|
}
|
|
|
|
function switchView(view) {
|
|
currentView = view;
|
|
hideChartTip();
|
|
$('table-members').style.display = view === 'members' ? '' : 'none';
|
|
$('table-models').style.display = view === 'models' ? '' : 'none';
|
|
// The Admin section is a members-view category; hide it in the Models view
|
|
// (model usage already integrates admin spend into the totals).
|
|
$('guests-section').style.display = view === 'members' ? '' : 'none';
|
|
$('admins-section').style.display = view === 'members' ? '' : 'none';
|
|
$('agents-section').style.display = view === 'members' ? '' : 'none';
|
|
$('trends-section').style.display = view === 'trends' ? '' : 'none';
|
|
$('tab-members').className = 'tab-btn' + (view === 'members' ? ' active' : '');
|
|
$('tab-models').className = 'tab-btn' + (view === 'models' ? ' active' : '');
|
|
$('tab-trends').className = 'tab-btn' + (view === 'trends' ? ' active' : '');
|
|
$('view-title').textContent = view === 'members' ? 'Members' : (view === 'models' ? 'Model usage' : 'Trends');
|
|
// Mode groups: Balance/All-time for members; Period for models; the guest
|
|
// invite form belongs to the members view too.
|
|
$('range-group').style.display = view === 'models' ? '' : 'none';
|
|
$('member-mode-group').style.display = view === 'members' ? '' : 'none';
|
|
$('guest-invite-section').style.display = view === 'members' ? '' : 'none';
|
|
// Trends renders on first visit only, so the panel's initial load stays fast.
|
|
// loadForMetric fetches whatever the SELECTED metric needs (the money rows
|
|
// come from a different endpoint than the rest).
|
|
if (view === 'trends') loadForMetric();
|
|
render();
|
|
}
|
|
|
|
function setRange(days) {
|
|
rangeDays = days;
|
|
$('range-30').className = 'range-btn' + (days === 30 ? ' active' : '');
|
|
$('range-all').className = 'range-btn' + (days === 0 ? ' active' : '');
|
|
loadModels();
|
|
}
|
|
|
|
function setMemberMode(mode) {
|
|
memberMode = mode;
|
|
$('mmode-balance').className = 'range-btn' + (mode === 'balance' ? ' active' : '');
|
|
$('mmode-all').className = 'range-btn' + (mode === 'all' ? ' active' : '');
|
|
// Header label reflects the mode
|
|
$('spend-mode-label').textContent = mode === 'all' ? 'All-time spend' : 'Spend';
|
|
const adminLabel = document.getElementById('spend-mode-label-admin');
|
|
// Agents always show all-time: their cycle counter resets on the 1st, so a cycle
|
|
// figure would read as zeroed for the co-op's own bot accounts every month.
|
|
// The Admin columns show all-time figures in both modes (their cycle counter
|
|
// resets on the 1st, so a cycle figure would read as zeroed), but the header
|
|
// must not claim a mode the reader is not in — it said "All-time spend" while
|
|
// the table was in balance mode (ntnsndr, 2026-11-13). Just "Spend".
|
|
if (adminLabel) adminLabel.textContent = 'Spend';
|
|
// Balance-only columns (Allowance/Credits/Remaining/Reset) hide in all-time mode
|
|
$('table-members').parentElement.classList.toggle('members-all-time', mode === 'all');
|
|
const adminTable = document.getElementById('table-admins');
|
|
if (adminTable) adminTable.parentElement.classList.toggle('admins-all-time', mode === 'all');
|
|
renderMembers();
|
|
}
|
|
|
|
function sortMembers(key) {
|
|
memberSort = { key, dir: memberSort.key === key ? -memberSort.dir : 1 };
|
|
clearArrows('members', memberSort);
|
|
render();
|
|
}
|
|
|
|
function memberSpend(m) {
|
|
return memberMode === 'all' ? (m.all_time_spend ?? m.spend ?? 0) : (m.spend ?? 0);
|
|
}
|
|
|
|
function sortModels(key) {
|
|
modelSort = { key, dir: modelSort.key === key ? -modelSort.dir : -1 };
|
|
clearArrows('models', modelSort);
|
|
render();
|
|
}
|
|
|
|
function render() {
|
|
if (currentView === 'members') renderMembers();
|
|
else renderModels();
|
|
}
|
|
|
|
function renderMembers() {
|
|
const rows = [...membersData].sort((a, b) => {
|
|
let va = a[memberSort.key], vb = b[memberSort.key];
|
|
if (memberSort.key === 'spend') { va = memberSpend(a); vb = memberSpend(b); }
|
|
if (memberSort.key === 'active' || memberSort.key === 'activated') { va = va ? 1 : 0; vb = vb ? 1 : 0; }
|
|
if (typeof va === 'string' || typeof vb === 'string') {
|
|
return String(va ?? '').localeCompare(String(vb ?? '')) * memberSort.dir;
|
|
}
|
|
return ((va ?? 0) - (vb ?? 0)) * memberSort.dir;
|
|
});
|
|
$('rows').innerHTML = rows.map(m => {
|
|
const reset = m.reset_at ? m.reset_at.slice(0,10) : '—';
|
|
// Membership state is computed by the PORTAL (the source of truth) and
|
|
// carried on the overview row — the panel only renders it. Non-active
|
|
// states (in grace / awaiting contribution) still keep the member's access.
|
|
// ONE short pill, matching the panel's pill vocabulary; no caption line.
|
|
const state = m.state || (m.active ? 'active' : 'inactive');
|
|
const stateLabel = { active: 'active', in_grace: 'grace',
|
|
awaiting_contribution: 'awaiting', inactive: 'inactive' }[state] || state;
|
|
const stateClass = state === 'active' ? 'active' : (state === 'inactive' ? 'inactive' : 'grace');
|
|
const stateTitle = { active: '', in_grace: 'Payment due — access continues during grace',
|
|
awaiting_contribution: 'Awaiting contribution',
|
|
inactive: 'Membership deactivated' }[state] || '';
|
|
const statusCell = '<span class="pill ' + stateClass + '"' +
|
|
(stateTitle ? ' title="' + esc(stateTitle) + '"' : '') + '>' +
|
|
esc(stateLabel) + '</span>';
|
|
const act = m.activated
|
|
? '<span class="pill active">yes</span>'
|
|
: '<span class="pill inactive">pending</span>';
|
|
const credits = m.credit_balance ?? 0;
|
|
const creditsLeft = m.credits_remaining ?? credits;
|
|
// Balance view: credits LEFT. All-time view: total purchased.
|
|
const creditsShown = memberMode === 'all' ? credits : creditsLeft;
|
|
const creditsCell = creditsShown > 0
|
|
? fmt(creditsShown)
|
|
: '<span style="color:var(--muted)">—</span>';
|
|
const src = m.account_type === 'guest'
|
|
? '<span class="pill guest" title="' + esc('Guest account — from ' + (m.guest_inviter || '?') +
|
|
' · expires ' + (m.guest_expires_at ? String(m.guest_expires_at).slice(0, 10) : '?') +
|
|
' · $2 credit, no OC membership, never swept for dues') + '">guest</span>'
|
|
: (m.source === 'oc-incognito'
|
|
? '<span class="pill org" title="' + esc('OC subscription — their Open Collective profile hides its email, so their orders are matched by their OC slug') + '">OC incognito</span>'
|
|
: (m.manual
|
|
? '<span class="pill manual" title="Manual member (no OC subscription; exempt from sweep)">manual</span>'
|
|
: '<span class="pill active" title="Open Collective Membership subscription">OC</span>'));
|
|
// Effective Matrix handle: dashboard-set external MXID, else the local
|
|
// @username:inference.coop identity (pending users have no username yet).
|
|
// Account cell: username on top (prominent); email + Matrix handle beneath
|
|
// in the muted secondary style. Users who never finished setup have no
|
|
// username — fall back to the email in the top position.
|
|
const top = m.username || m.email;
|
|
const mxid = m.matrix_mxid || (m.username ? '@' + m.username + ':inference.coop' : '');
|
|
const mxidLine = mxid ? '<div style="color:var(--muted);font-size:11px">' + esc(mxid) + '</div>' : '';
|
|
const emailLine = m.username ? '<div style="color:var(--muted);font-size:11px">' + esc(m.email) + '</div>' : '';
|
|
const org = m.org
|
|
? ' <span class="pill org" title="Organizational membership: dues paid by OC organization">org: ' + esc(m.org) + '</span>'
|
|
: '';
|
|
return '<tr>' +
|
|
'<td><strong>' + esc(top) + '</strong>' + emailLine + mxidLine +
|
|
(org ? '<div style="margin-top:3px">' + org + '</div>' : '') + '</td>' +
|
|
'<td>' + statusCell + '</td>' +
|
|
'<td>' + act + '</td>' +
|
|
'<td>' + src + '</td>' +
|
|
'<td class="num balance-col allowance-only">' + fmt(m.balance) + '</td>' +
|
|
'<td class="num balance-col">' + creditsCell + '</td>' +
|
|
'<td class="num">' + fmt(memberSpend(m)) + '</td>' +
|
|
'<td class="num balance-col remaining-col remaining-only">' + fmt(m.remaining) + '</td>' +
|
|
'<td class="balance-col">' + esc(reset) + '</td>' +
|
|
'<td><div class="adjust">' +
|
|
'<input id="add-' + i(m.email) + '" placeholder="+$" />' +
|
|
'<button data-email="' + esc(m.email) + '" onclick="addBalance(this.dataset.email)" title="Add monthly allowance">Allow</button>' +
|
|
'<button data-email="' + esc(m.email) + '" class="credits-btn" onclick="addCredits(this.dataset.email)" title="Add non-expiring credits">Credit</button>' +
|
|
'</div></td>' +
|
|
'</tr>';
|
|
}).join('');
|
|
clearArrows('members', memberSort);
|
|
|
|
// Guests — guest accounts in their own list, never in the members table or
|
|
// the member count. Inviter and expiry come from the portal guest ledger.
|
|
const guestSection = document.getElementById('guests-section');
|
|
if (guestsData.length) {
|
|
guestSection.style.display = '';
|
|
$('guest-rows').innerHTML = guestsData.map(g => {
|
|
const top = g.username || g.email;
|
|
const emailLine = g.username ? '<div style="color:var(--muted);font-size:11px">' + esc(g.email) + '</div>' : '';
|
|
const credits = Number(g.credits_remaining ?? g.credit_balance ?? 0);
|
|
const exp = g.guest_expires_at ? String(g.guest_expires_at).slice(0, 10) : '—';
|
|
// The portal derives the display state — the SINGLE derivation, tested
|
|
// once in the portal (tests/test_guest_invited_state.py): 'invited'
|
|
// while the guest has not accepted their setup invite, else the
|
|
// guests-ledger status. This row is a pure consumer: first served field
|
|
// wins, nothing is derived here from flags. (guest_status first keeps
|
|
// the previous payload shape rendering identically during a portal
|
|
// rollback; a payload with neither field renders an empty pill — that
|
|
// shape no longer exists and must not be re-derived.)
|
|
const st = g.state === 'invited' ? 'invited'
|
|
: String(g.guest_status || g.state || '');
|
|
const stClass = { invited: 'invited', active: 'active', converted: 'org' }[st] || 'inactive';
|
|
const stTitle = {
|
|
invited: 'Invited — awaiting setup (the guest has not accepted their invite yet)',
|
|
active: 'Guest access live', converted: 'Guest became a member',
|
|
expired: 'Time box elapsed', depleted: 'Credits spent' }[st] || '';
|
|
return '<tr>' +
|
|
'<td><strong>' + esc(top) + '</strong>' + emailLine + '</td>' +
|
|
'<td>' + esc(g.guest_inviter || '—') + '</td>' +
|
|
'<td class="num remaining-col">' + fmt(credits) + '</td>' +
|
|
'<td>' + esc(exp) + '</td>' +
|
|
'<td><span class="pill ' + stClass + '"' + (stTitle ? ' title="' + esc(stTitle) + '"' : '') + '>' + esc(st) + '</span></td>' +
|
|
'</tr>';
|
|
}).join('');
|
|
} else { guestSection.style.display = 'none'; $('guest-rows').innerHTML = ''; }
|
|
|
|
// Agents/bots — real spend, not members. Rendered before the admin block, which
|
|
// returns early when there are no operator accounts.
|
|
const agentSection = document.getElementById('agents-section');
|
|
if (agentsData.length) {
|
|
agentSection.style.display = '';
|
|
$('agent-rows').innerHTML = agentsData.map(a => {
|
|
const kind = String(a.alias).split(':')[0];
|
|
const budget = (a.budget === null || a.budget === undefined) ? '—' : fmt(a.budget);
|
|
return '<tr>' +
|
|
'<td><strong>' + esc(a.name || a.alias) + '</strong></td>' +
|
|
'<td><span class="pill manual" title="Agent account, not a member">' + esc(kind) + '</span></td>' +
|
|
'<td class="num" title="All-time spend: agent accounts are billed monthly and their cycle counter resets on the 1st">' + fmt(a.all_time_spend ?? a.spend) + '</td>' +
|
|
'<td>' + budget + '</td>' +
|
|
'</tr>';
|
|
}).join('');
|
|
} else { agentSection.style.display = 'none'; }
|
|
|
|
// Admin category — operator accounts (SSO owner + bot), separate from members.
|
|
const adminSection = document.getElementById('admins-section');
|
|
if (!adminsData.length) { adminSection.style.display = 'none'; return; }
|
|
adminSection.style.display = '';
|
|
$('admin-rows').innerHTML = adminsData.map(m => {
|
|
const reset = m.reset_at ? m.reset_at.slice(0,10) : '—';
|
|
const adminTop = m.username || m.email;
|
|
return '<tr>' +
|
|
'<td><strong>' + esc(adminTop) + '</strong>' + (m.username ? '<div style="color:var(--muted);font-size:11px">' + esc(m.email) + '</div>' : '') + '</td>' +
|
|
'<td><span class="pill manual" title="Operator account, not a member">admin</span></td>' +
|
|
'<td class="num">' + fmt(memberSpend(m)) + '</td>' +
|
|
'<td>—</td>' +
|
|
'</tr>';
|
|
}).join('');
|
|
}
|
|
|
|
async function addCredits(email) {
|
|
const el = $('add-' + i(email));
|
|
const val = parseFloat(el.value);
|
|
if (!val || isNaN(val)) { flash('Enter a number', false); return; }
|
|
try {
|
|
const r = await fetch('/api/set-credits', {
|
|
method: 'POST', headers: {'Content-Type': 'application/json'},
|
|
body: JSON.stringify({ email, add: val, reason: 'admin adjustment (panel)' })
|
|
});
|
|
const d = await r.json();
|
|
if (d.error) { flash(d.error, false); }
|
|
else { flash('Added ' + fmt(val) + ' credits to ' + email, true); el.value = ''; load(); }
|
|
} catch (e) { flash(e.message, false); }
|
|
}
|
|
|
|
function renderModels() {
|
|
const rows = [...modelsData].sort((a, b) => {
|
|
const va = a[modelSort.key], vb = b[modelSort.key];
|
|
if (typeof va === 'string' || typeof vb === 'string') {
|
|
return String(va ?? '').localeCompare(String(vb ?? '')) * modelSort.dir;
|
|
}
|
|
return ((va ?? 0) - (vb ?? 0)) * modelSort.dir;
|
|
});
|
|
if (!rows.length) {
|
|
$('model-rows').innerHTML = '<tr><td colspan="4" style="color:var(--muted)">No usage recorded.</td></tr>';
|
|
return;
|
|
}
|
|
$('model-rows').innerHTML = rows.map(m =>
|
|
'<tr>' +
|
|
'<td>' + esc(m.model) + '</td>' +
|
|
'<td class="num">' + fmt(m.spend) + '</td>' +
|
|
'<td class="num">' + (m.tokens || 0).toLocaleString() + '</td>' +
|
|
'<td class="num">' + (m.requests || 0).toLocaleString() + '</td>' +
|
|
'</tr>'
|
|
).join('');
|
|
clearArrows('models', modelSort);
|
|
}
|
|
|
|
function i(email) { return email.replace(/[^a-z0-9]/g, '_'); }
|
|
|
|
function esc(s) {
|
|
return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
|
}
|
|
|
|
async function addBalance(email) {
|
|
const el = $('add-' + i(email));
|
|
const val = parseFloat(el.value);
|
|
if (!val || isNaN(val)) { flash('Enter a number', false); return; }
|
|
try {
|
|
const r = await fetch('/api/set-balance', {
|
|
method: 'POST', headers: {'Content-Type': 'application/json'},
|
|
body: JSON.stringify({ email, add: val })
|
|
});
|
|
const d = await r.json();
|
|
if (d.error) { flash(d.error, false); }
|
|
else { flash('Added ' + fmt(val) + ' to ' + email, true); el.value = ''; load(); }
|
|
} catch (e) { flash(e.message, false); }
|
|
}
|
|
|
|
// Guest action: provision a $2 guest account — the standard guest-invite form
|
|
// (the guest's email, required, plus an OPTIONAL display name; if left empty
|
|
// the guest sets their own at Cloudron setup and the invitation greets
|
|
// neutrally). The inviter is always the co-op's ADMIN account, recorded by
|
|
// the portal; admins have no monthly cap. The portal enforces the
|
|
// recipient-side guards (one guest per recipient ever, no existing portal
|
|
// row) and reports a clear refusal.
|
|
//
|
|
// Submit UX (the operator must always be able to tell what happened):
|
|
// * the button is disabled with "Sending…" for the whole request — a double
|
|
// click cannot fire a second invite while the first is in flight;
|
|
// * SUCCESS: the fields are cleared and the outcome is stated in the card
|
|
// itself — 'Invite sent to <email> — expires <date>.' (the guests list
|
|
// refreshes underneath, so the new account is visible too);
|
|
// * FAILURE: the error is shown plainly in the card (and the top flash),
|
|
// and the fields are KEPT so the operator can correct and retry.
|
|
async function sendGuestAccess(ev) {
|
|
if (ev) ev.preventDefault();
|
|
const email = ($('guest-email').value || '').trim();
|
|
const name = ($('guest-name').value || '').trim();
|
|
const btn = $('guest-send');
|
|
if (!email || email.indexOf('@') < 1) { inviteStatus("Enter the guest's email", false); flash("Enter the guest's email", false); return; }
|
|
btn.disabled = true; btn.textContent = "Sending…";
|
|
try {
|
|
const r = await fetch('/api/provision-guest', {
|
|
method: 'POST', headers: {'Content-Type': 'application/json'},
|
|
body: JSON.stringify({ email, name })
|
|
});
|
|
const d = await r.json().catch(() => ({}));
|
|
if (!r.ok || d.error) {
|
|
const msg = d.error || ('Could not send guest access (' + r.status + ')');
|
|
inviteStatus(msg, false); flash(msg, false);
|
|
return;
|
|
}
|
|
const days = d.expires_in_days || 60;
|
|
const exp = new Date(Date.now() + days * 86400000)
|
|
.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
|
|
const msg = 'Invite sent to ' + email + ' — expires ' + exp + '.';
|
|
inviteStatus(msg, true); flash(msg, true);
|
|
$('guest-email').value = ''; $('guest-name').value = '';
|
|
load();
|
|
} catch (e) { const msg = 'Guest access failed: ' + e.message; inviteStatus(msg, false); flash(msg, false); }
|
|
finally { btn.disabled = false; btn.textContent = 'Send invite'; }
|
|
}
|
|
|
|
// ---- Guest requests: REMOVED (2026-11-08) ----------------------------------
|
|
// The member self-serve approval gate is gone — member invitations provision
|
|
// immediately in the portal, so there is nothing to approve or reject here.
|
|
// The Guests list (members view) shows every member-invited guest with its
|
|
// inviter, credits, expiry and status, exactly like admin-created ones.
|
|
// The portal's /admin/guest-ledger still feeds the duplicate-send guard.
|
|
|
|
buildMetricButtons();
|
|
load();
|
|
loadModels();
|
|
</script>
|
|
</body>
|
|
</html>"""
|
|
|
|
# Splice the shared chart module into the page's single <script> block. The
|
|
# placeholder is a JS comment, so the extracted-and-checked block stays valid
|
|
# even before the splice (check-page-js.sh performs the same splice when it
|
|
# runs the harnesses).
|
|
PAGE_HTML = PAGE_HTML.replace("/*@@CHART_MODULE@@*/", CHART_MODULE_JS)
|
|
|
|
|
|
@app.exception_handler(HTTPException)
|
|
async def http_exception_handler(request: Request, exc: HTTPException):
|
|
return JSONResponse({"error": exc.detail}, status_code=exc.status_code)
|