Files
devplacepy/devplacepy/services/statistics/build.py
T
retoorandClaude Sonnet 5.5 1a9201cb91 Admin pages: one shared specification, builders, fragments, caps and live refresh
Adds admin_sections registry, shared admin partials, WorkspaceList, admin CLAUDE.md spec,
capped node/flag listings, and api/unit tests enforcing the spec.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 01:50:50 +01:00

160 lines
4.9 KiB
Python

# retoor <retoor@molodetz.nl>
from __future__ import annotations
import re
from devplacepy.services.statistics.common import (
VALID_TABS,
cache_get,
cache_set,
iso,
now_utc,
window_config,
)
from devplacepy.services.statistics.tabs_data import (
build_ai,
build_awards,
build_containers,
build_content,
build_devii,
build_engagement,
build_game,
build_members,
build_moderation,
build_overview,
build_services,
build_social,
build_storage,
build_tools,
build_visitors,
)
NUMERIC_HEADER_TOKENS = (
"count", "events", "views", "gists", "posts", "votes", "actions", "stars",
"turns", "requests", "cost", "coins", "level", "restarts", "followers",
"upvotes", "downvotes", "members", "guests", "tokens", "errors",
)
NAME_HEADERS = ("user", "name")
NAME_HEADER_TOKENS = ("username", "instance")
NUMERIC_SAMPLE_ROWS = 12
ARROWS = {"up": "\u2191", "down": "\u2193", "flat": "\u2192"}
MONEY_SMALL_LIMIT = 1
CELL_DIGITS = 2
DECIMAL_DIGITS = 1
TAB_BUILDERS = {
"overview": build_overview,
"visitors": build_visitors,
"members": build_members,
"content": build_content,
"engagement": build_engagement,
"social": build_social,
"ai": build_ai,
"devii": build_devii,
"services": build_services,
"containers": build_containers,
"game": build_game,
"awards": build_awards,
"moderation": build_moderation,
"tools": build_tools,
"storage": build_storage,
}
NUMERIC_TEXT = re.compile(r"^-?\d+(\.\d+)?$")
def is_numeric_text(value) -> bool:
if isinstance(value, bool):
return False
if isinstance(value, (int, float)):
return True
return bool(NUMERIC_TEXT.match(str(value if value is not None else "").strip().replace(",", "")))
def format_number_text(value, digits: int) -> str:
number = float(str(value).strip().replace(",", ""))
if number == int(number):
return f"{int(number):,}"
return f"{round(number, digits):,}"
def column_class(index: int, columns: list, rows: list) -> str:
header = str(columns[index] if index < len(columns) else "").lower()
if index == 0:
if any(token in header for token in NAME_HEADER_TOKENS) or header in NAME_HEADERS:
return "statistics-col-name"
return "statistics-col-key"
if any(token in header for token in NUMERIC_HEADER_TOKENS):
return "statistics-col-num"
sample = rows[:NUMERIC_SAMPLE_ROWS]
if not sample:
return "statistics-col-num"
if all(is_numeric_text(row[index] if index < len(row) else None) for row in sample):
return "statistics-col-num"
return "statistics-col-text"
def present_card(card: dict) -> dict:
kind = card.get("format") or "int"
value = float(card.get("value") or 0)
if kind == "money":
display = f"${value:.4f}" if value < MONEY_SMALL_LIMIT else f"${value:.2f}"
elif kind == "decimal":
display = format_number_text(value, DECIMAL_DIGITS)
else:
display = f"{int(value):,}"
out = {**card, "display": display}
delta = card.get("delta")
if delta is not None:
direction = card.get("direction") or "flat"
out["direction"] = direction
out["arrow"] = ARROWS.get(direction, ARROWS["flat"])
out["delta_display"] = f"{format_number_text(abs(float(delta)), DECIMAL_DIGITS)}%"
return out
def present_table(table: dict) -> dict:
columns = list(table.get("columns") or [])
rows = list(table.get("rows") or [])
classes = [column_class(index, columns, rows) for index in range(len(columns))]
display_rows = [
[
format_number_text(row[index], CELL_DIGITS) if classes[index] == "statistics-col-num" and is_numeric_text(row[index]) else str(row[index] if row[index] is not None else "")
for index in range(len(columns))
]
for row in rows
]
return {**table, "column_classes": classes, "display_rows": display_rows, "row_count": f"{len(rows):,}"}
def build_statistics_tab(
tab: str,
hours: int = 168,
*,
compare: bool = True,
top_n: int = 10,
) -> dict:
key = (tab or "overview").strip().lower()
if key not in VALID_TABS:
key = "overview"
bounded_top = max(1, min(int(top_n or 10), 50))
window = window_config(hours)
cache_key = f"stats:{key}:{window['hours']}:{int(compare)}:{bounded_top}"
cached = cache_get(cache_key)
if cached is not None:
return cached
builder = TAB_BUILDERS[key]
body = builder(window["hours"], compare, bounded_top)
payload = {
"tab": key,
"window_hours": window["hours"],
"granularity": window["granularity"],
"generated_at": iso(now_utc()),
"compare": bool(compare),
**body,
}
payload["cards"] = [present_card(card) for card in payload.get("cards") or []]
payload["tables"] = [present_table(table) for table in payload.get("tables") or []]
cache_set(cache_key, payload)
return payload