askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
dashboard.py · 10.6 KB · 264 lines
| 1 | """User home dashboard: a client-rendered fold over data this codebase |
| 2 | already has, not a new data model. |
| 3 | |
| 4 | No new schema, no new collection, no new write path. Every number on this |
| 5 | page is a sum or a count over an *existing* collection's records, fetched |
| 6 | from the browser with the caller's own session cookie -- so permissions |
| 7 | and row-filters (see each source collection's own permissions/rules.json) |
| 8 | govern what shows up, and this object holds no data access of its own. |
| 9 | Same identity-aware, browser-polls-its-own-APIs pattern as |
| 10 | packages/app-activity/objects/site/activity.py and |
| 11 | packages/app-worker/objects/site/profile.py, and the same shared chrome |
| 12 | (/style, /nav) as every other /style page in this codebase. |
| 13 | |
| 14 | This is deliberately NOT packages/system-dashboard/objects/system/ |
| 15 | dashboard.py -- that object is the *operator* view (server health, |
| 16 | inventory, admin-only metrics, no shared chrome, its own inline dark |
| 17 | palette). This is the signed-in *user's own* dashboard: AI spend, task |
| 18 | counts, recent activity, and a couple of one-line collection counts, all |
| 19 | scoped to what that one user can see. It is served at /dashboard by the |
| 20 | single-segment site-object convention (/dashboard -> site_dashboard), |
| 21 | the same convention app-activity's site_activity (-> /activity) and |
| 22 | app-tasks's site_tasks (-> /tasks) already rely on -- no site_routes |
| 23 | record is seeded or required. |
| 24 | |
| 25 | Ported from a private predecessor-system audit, not part of this repo: |
| 26 | that system's dashboard folded three things into one summary -- a wallet/ |
| 27 | billing balance, AI/API usage, and task stats. Billing is infra-deferred |
| 28 | in this codebase (no Stripe integration is built), so this v1 ports only |
| 29 | the AI-usage and task-stats halves, plus the recent-activity feed |
| 30 | (already its own endpoint here, /api/activity) and one-line counts for a |
| 31 | few other collections that already have pages. No wallet balance, no |
| 32 | charts, no new metrics beyond simple sums and counts -- faithful and |
| 33 | minimal. |
| 34 | """ |
| 35 | |
| 36 | _STYLE = """ |
| 37 | .stats { display: grid; gap: var(--gap); grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); } |
| 38 | .stats .card { text-decoration: none; color: var(--text); } |
| 39 | .stats .card:hover { border-color: var(--accent); } |
| 40 | .stats .card .value { font-size: 1.4rem; font-weight: 700; } |
| 41 | .stats .card .label { color: var(--muted); font-size: 0.75rem; text-transform: uppercase; |
| 42 | letter-spacing: 0.03em; margin-top: 0.2rem; } |
| 43 | .dashsection { margin-top: 1.75rem; } |
| 44 | .dashsection h2 { font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.04em; |
| 45 | color: var(--muted); margin: 0 0 0.6rem; } |
| 46 | .feed .listrow .rowtitle .verb { color: var(--accent-strong); } |
| 47 | .feed .listrow .rowtitle .coll { color: var(--muted); font-weight: 400; } |
| 48 | """ |
| 49 | |
| 50 | _SCRIPT = r""" |
| 51 | const esc = (s) => String(s == null ? "" : s).replace(/[&<>"']/g, |
| 52 | (c) => ({"&": "&", "<": "<", ">": ">", '"': """, "'": "'"}[c])); |
| 53 | const el = (id) => document.getElementById(id); |
| 54 | const money = (cents) => "$" + (Number(cents || 0) / 100).toFixed(2); |
| 55 | |
| 56 | async function fetchJson(url) { |
| 57 | try { |
| 58 | const res = await fetch(url, {credentials: "same-origin", headers: {accept: "application/json"}}); |
| 59 | if (!res.ok) return null; |
| 60 | return await res.json(); |
| 61 | } catch (e) { |
| 62 | return null; |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | // Same relative-time shape as app-theme/objects/site/list.py's relDate, |
| 67 | // copied verbatim -- see app-activity/objects/site/activity.py's docstring |
| 68 | // for why (list.py doesn't export it). |
| 69 | function relDate(iso) { |
| 70 | if (!iso) return ""; |
| 71 | const d = new Date(iso); if (isNaN(d)) return ""; |
| 72 | const ms = Date.now() - d.getTime(); |
| 73 | if (ms < 3600000) { const m = Math.floor(ms / 60000); return m < 1 ? "just now" : m + "m ago"; } |
| 74 | if (ms < 86400000) return Math.floor(ms / 3600000) + "h ago"; |
| 75 | if (ms < 7 * 86400000) return Math.floor(ms / 86400000) + "d ago"; |
| 76 | return d.toLocaleDateString(undefined, {month: "short", day: "numeric"}); |
| 77 | } |
| 78 | |
| 79 | function statTile(href, value, label) { |
| 80 | return '<a class="card" href="' + esc(href) + '"><div class="value">' + esc(value) + |
| 81 | '</div><div class="label">' + esc(label) + '</div></a>'; |
| 82 | } |
| 83 | |
| 84 | // --- AI spend: fold ai_usage.cost_cents, grouped by model -------------- |
| 85 | async function loadAiUsage() { |
| 86 | const body = await fetchJson("/collections/ai_usage/records?limit=500"); |
| 87 | const records = (body && body.records) || []; |
| 88 | if (!records.length) { |
| 89 | el("ai-usage").innerHTML = '<div class="state">No AI usage yet.</div>'; |
| 90 | return; |
| 91 | } |
| 92 | let totalCents = 0; |
| 93 | let unpriced = 0; |
| 94 | const byModel = {}; |
| 95 | for (const r of records) { |
| 96 | if (r.cost_cents === null || r.cost_cents === undefined || r.cost_cents === "") { |
| 97 | unpriced += 1; |
| 98 | } else { |
| 99 | totalCents += Number(r.cost_cents) || 0; |
| 100 | } |
| 101 | const key = r.model || "unknown"; |
| 102 | const stat = byModel[key] || (byModel[key] = {calls: 0, cents: 0}); |
| 103 | stat.calls += 1; |
| 104 | stat.cents += Number(r.cost_cents) || 0; |
| 105 | } |
| 106 | const rows = Object.entries(byModel) |
| 107 | .sort((a, b) => b[1].cents - a[1].cents) |
| 108 | .map(([model, stat]) => |
| 109 | "<tr><td>" + esc(model) + "</td><td class=num>" + stat.calls + |
| 110 | "</td><td class=num>" + money(stat.cents) + "</td></tr>") |
| 111 | .join(""); |
| 112 | const note = unpriced |
| 113 | ? '<div class="meta" style="margin-top:0.4rem">' + unpriced + |
| 114 | " call" + (unpriced === 1 ? "" : "s") + " with no matched price, counted as $0</div>" |
| 115 | : ""; |
| 116 | el("ai-usage").innerHTML = |
| 117 | '<div class="stats"><div class="card"><div class="value">' + money(totalCents) + |
| 118 | '</div><div class="label">Total AI Spend · ' + records.length + " call" + |
| 119 | (records.length === 1 ? "" : "s") + "</div></div></div>" + note + |
| 120 | '<table style="margin-top:0.75rem"><thead><tr><th>Model</th><th class=num>Calls</th>' + |
| 121 | "<th class=num>Cost</th></tr></thead><tbody>" + rows + "</tbody></table>"; |
| 122 | } |
| 123 | |
| 124 | // --- Task stats: fold tasks.status into counts per status -------------- |
| 125 | const TASK_STATUS_ORDER = ["draft", "open", "assigned", "waiting_on_client", |
| 126 | "approved", "disputed", "cancelled"]; |
| 127 | |
| 128 | async function loadTasks() { |
| 129 | const body = await fetchJson("/collections/tasks/records?limit=500"); |
| 130 | const records = (body && body.records) || []; |
| 131 | if (!records.length) { |
| 132 | el("task-stats").innerHTML = '<div class="state">No tasks yet.</div>'; |
| 133 | return; |
| 134 | } |
| 135 | const counts = {}; |
| 136 | for (const r of records) { |
| 137 | const status = r.status || "unknown"; |
| 138 | counts[status] = (counts[status] || 0) + 1; |
| 139 | } |
| 140 | const statuses = TASK_STATUS_ORDER.filter((s) => counts[s]) |
| 141 | .concat(Object.keys(counts).filter((s) => !TASK_STATUS_ORDER.includes(s))); |
| 142 | el("task-stats").innerHTML = '<div class="stats">' + |
| 143 | statuses.map((s) => statTile("/tasks", counts[s], s.replace(/_/g, " "))).join("") + |
| 144 | "</div>"; |
| 145 | } |
| 146 | |
| 147 | // --- Recent activity: fold /api/activity, same row shape as app-activity |
| 148 | function activityRow(entry) { |
| 149 | const actor = entry.actor || "unattributed"; |
| 150 | const verb = String(entry.action || "").toUpperCase(); |
| 151 | const av = actor.trim().charAt(0).toUpperCase() || "?"; |
| 152 | return '<div class="listrow"><div class="av">' + esc(av) + '</div><div class="body">' |
| 153 | + '<div class="rowtitle">' + esc(actor) + ' <span class="verb">' + esc(verb) + '</span> ' |
| 154 | + '<span class="coll">' + esc(entry.collection) + '</span> ' + esc(entry.title) + '</div>' |
| 155 | + '<div class="rowmeta"><span class="when">' + esc(relDate(entry.timestamp)) + '</span></div>' |
| 156 | + '</div></div>'; |
| 157 | } |
| 158 | |
| 159 | async function loadActivity() { |
| 160 | const body = await fetchJson("/api/activity?limit=8"); |
| 161 | const entries = (body && body.activity) || []; |
| 162 | el("activity").innerHTML = entries.length |
| 163 | ? entries.map(activityRow).join("") |
| 164 | : '<div class="state">Nothing yet.</div>'; |
| 165 | } |
| 166 | |
| 167 | // --- One-line counts for a few other collections, opportunistic -------- |
| 168 | // Not a dependency: dbbasic-package.json declares none of these, and a |
| 169 | // missing/empty collection just leaves its tile out, same posture as |
| 170 | // app-worker/objects/site/profile.py's article fetch. |
| 171 | const OTHER_COLLECTIONS = [ |
| 172 | {collection: "notes", label: "Notes", href: "/notes"}, |
| 173 | {collection: "contacts", label: "Contacts", href: "/contacts"}, |
| 174 | {collection: "invoices", label: "Invoices", href: "/invoices"}, |
| 175 | ]; |
| 176 | |
| 177 | async function loadOtherCounts() { |
| 178 | const bodies = await Promise.all( |
| 179 | OTHER_COLLECTIONS.map((spec) => fetchJson("/collections/" + spec.collection + "/records?limit=1"))); |
| 180 | const tiles = []; |
| 181 | bodies.forEach((body, i) => { |
| 182 | if (body && typeof body.total === "number") { |
| 183 | tiles.push(statTile(OTHER_COLLECTIONS[i].href, body.total, OTHER_COLLECTIONS[i].label)); |
| 184 | } |
| 185 | }); |
| 186 | const section = el("other-counts-section"); |
| 187 | if (!tiles.length) { section.style.display = "none"; return; } |
| 188 | section.style.display = "block"; |
| 189 | el("other-counts").innerHTML = '<div class="stats">' + tiles.join("") + "</div>"; |
| 190 | } |
| 191 | |
| 192 | loadAiUsage(); |
| 193 | loadTasks(); |
| 194 | loadActivity(); |
| 195 | loadOtherCounts(); |
| 196 | """ |
| 197 | |
| 198 | |
| 199 | def GET(request): |
| 200 | identity = request.get("_identity", {}) |
| 201 | user_id = identity.get("user_id") |
| 202 | _logger.info("site_dashboard served", user_id=user_id or "anonymous") |
| 203 | |
| 204 | if not user_id: |
| 205 | body = ( |
| 206 | '<div class="breadcrumb">Home / Dashboard</div>' |
| 207 | '<div class="pagehead"><h1>Dashboard</h1></div>' |
| 208 | '<div class="hint">Your dashboard shows AI spend, task counts, and recent ' |
| 209 | "activity once you sign in — each fetched with your own session, so " |
| 210 | 'you only ever see your own data. <a href="/login?next=/dashboard">Sign in' |
| 211 | "</a> to see yours.</div>" |
| 212 | ) |
| 213 | script = "" |
| 214 | else: |
| 215 | body = """ |
| 216 | <div class="breadcrumb"><a href="/">Home</a> / Dashboard</div> |
| 217 | <div class="pagehead"><h1>Dashboard</h1></div> |
| 218 | |
| 219 | <div class="dashsection"> |
| 220 | <h2>AI Spend</h2> |
| 221 | <div id="ai-usage"><div class="state">loading…</div></div> |
| 222 | </div> |
| 223 | |
| 224 | <div class="dashsection"> |
| 225 | <h2>Tasks</h2> |
| 226 | <div id="task-stats"><div class="state">loading…</div></div> |
| 227 | </div> |
| 228 | |
| 229 | <div class="dashsection"> |
| 230 | <h2>Recent Activity</h2> |
| 231 | <div class="feed" id="activity"><div class="state">loading…</div></div> |
| 232 | </div> |
| 233 | |
| 234 | <div class="dashsection" id="other-counts-section" style="display:none"> |
| 235 | <h2>Also Yours</h2> |
| 236 | <div id="other-counts"></div> |
| 237 | </div> |
| 238 | """ |
| 239 | script = f"<script>{_SCRIPT}</script>" |
| 240 | |
| 241 | who = ( |
| 242 | f"signed in as <strong>{user_id}</strong>" |
| 243 | if user_id |
| 244 | else '<a href="/login?next=/dashboard">sign in</a>' |
| 245 | ) |
| 246 | html = f"""<!doctype html> |
| 247 | <html lang="en"> |
| 248 | <head> |
| 249 | <meta charset="utf-8"> |
| 250 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 251 | <title>Dashboard</title> |
| 252 | <link rel="stylesheet" href="/style"> |
| 253 | <style>{_STYLE}</style> |
| 254 | </head> |
| 255 | <body> |
| 256 | <div class="wrap"> |
| 257 | <header class="app"><h1><a href="/">DBBASIC</a></h1><div class="who">{who}</div></header> |
| 258 | {body} |
| 259 | </div> |
| 260 | {script} |
| 261 | <script src="/nav"></script> |
| 262 | </body> |
| 263 | </html>""" |
| 264 | return {"content_type": "text/html; charset=utf-8", "body": html} |