Merge remote-tracking branch 'origin/feat/home-trends' into naprawa-53

# Conflicts:
#	frontend/app.js
This commit is contained in:
2026-11-25 19:03:38 +01:00
8 changed files with 324 additions and 4 deletions
@@ -0,0 +1,30 @@
"""Panorama folds into Atrium's home (Atrium#53, stage 3): it leaves the menu and the catalogue.
Its trends now live on the home page (`services/trends`, `GET /home/trends`), and the module tiles
were already the home page's. So Panorama's row becomes a service module (`in_menu` false, as Galena
in `0016` and Arbiter in `0017`): nobody is offered it any more, and nothing anybody had is taken
away while it still runs. Removing it from the platform (its container, the front door, its event
reader grant) is a deploy step of its own, after this.
Downgrade puts it back in the menu.
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "0018"
down_revision = "0017"
branch_labels = None
depends_on = None
_module = sa.table("module", sa.column("slug", sa.String), sa.column("in_menu", sa.Boolean))
def upgrade() -> None:
op.get_bind().execute(_module.update().where(_module.c.slug == "panorama").values(in_menu=False))
def downgrade() -> None:
op.get_bind().execute(_module.update().where(_module.c.slug == "panorama").values(in_menu=True))
+12 -2
View File
@@ -9,11 +9,11 @@ from fastapi import APIRouter, Depends, Query, Request
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, get_current_user
from ..deps import client_ip, get_current_user, require_administrator
from ..models import AppUser
from ..schemas import NoteIn
from ..services import marketplace as service
from ..services import stats
from ..services import stats, trends
router = APIRouter(tags=["marketplace"])
@@ -30,6 +30,16 @@ def home_stats(db: Session = Depends(get_db),
return stats.home(db, user)
@router.get("/home/trends")
def home_trends(days: int = Query(30, ge=1, le=366), db: Session = Depends(get_db),
user: AppUser = Depends(require_administrator)) -> dict:
"""Trends from the event log (moved from Panorama): events per day and kind, and how long
documents took from their first version to approval and to signature. Platform-wide sums, so
platform administrators only."""
return {"activity": trends.activity(db, days=days),
"durations": trends.durations(db, trends.SEGMENTS)}
@router.get("/marketplace")
def browse(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user),
q: str = Query("", max_length=100),
+2
View File
@@ -155,6 +155,8 @@ FAMILY: list[dict] = [
# The platform's dashboard (the split plan's M4). Pink is Panorama's own brand colour (Open
# Color pink, its CLAUDE.md). In English the tagline reads "The platform dashboard".
"slug": "panorama", "name": "Panorama", "hue": "pink", "glyph": "chart", "sort_order": 90,
# Folded into Atrium's home (Atrium#53, stage 3): its trends are the home page's now.
"in_menu": False,
"category": "Pulpit",
"tagline": "Pulpit platformy.",
"description": (
+188
View File
@@ -0,0 +1,188 @@
"""History and trends on the home page: aggregates over the platform's event log (`module_event`).
Moved here from Panorama (Atrium#53, stage 3: Panorama folds into Atrium's home and is retired).
Current numbers still come from each module's own stats, which the console asks directly; history
and trends come from the event log, which carries identifiers and numbers only - never a title, a
name or a sentence (`dredd_core.events.check_payload`). Nothing here returns an id or a list of
documents: events per day and kind, and how long documents took between two kinds of event.
**Where the log is.** Atrium is the hub: on the platform the log is its own (`dredd.module_event`,
revision 0011), reached through the `search_path`. Standalone nobody writes events into this schema,
so the charts say there is no log; nothing fails. A lightweight `table()` construct reads it, so this
file adds nothing to the metadata.
Events are not filtered per person (the log has no notion of who may read the subject), so the route
keeps these charts to platform administrators (`routers/marketplace.home_trends`).
"""
from __future__ import annotations
import datetime as dt
import statistics
from collections import defaultdict
from typing import Any
from sqlalchemy import DateTime, Text, column, func, literal_column, select, table, text
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Session as DbSession
#: The platform's working day (Compass's `clock.ZONE`): a day on a chart is a day in Poland.
ZONE = "Europe/Warsaw"
#: The longest history a chart asks for.
MAX_DAYS = 366
#: How far back the durations look for the events that start a measurement.
DURATION_YEARS = 2
_EVENT = table(
"module_event",
column("kind", Text),
column("source_module", Text),
column("payload", JSONB),
column("created_at", DateTime(timezone=True)),
)
#: The kinds the platform emits today (`dredd_core.events.FIRST_EVENTS`) in the console's words.
#: A kind not listed is still counted, under its own code.
KIND_LABELS: dict[str, str] = {
"document.version_added": "Nowe wersje dokumentów",
"workflow.approved": "Zatwierdzone obiegi",
"document.signed": "Podpisane dokumenty",
"negotiation.round_received": "Rundy negocjacji",
"analysis.accepted": "Zaakceptowane analizy",
}
#: The milestones a document passes, each the FIRST event of its kind naming that document
#: (`payload.document_id`), in order. Compass measured four stages from its own tables; three of its
#: five milestones exist as events today, so two stages remain. A new event kind adds a milestone
#: here, not a table.
MILESTONES: tuple[tuple[str, str], ...] = (
("created", "document.version_added"),
("approved", "workflow.approved"),
("signed", "document.signed"),
)
#: A stage runs from one milestone to the next.
SEGMENTS = ("przygotowanie", "podpisanie")
#: The distribution's bands in days, both ends included; `None` = no upper end (Compass W7).
BANDS = ((0, 7), (8, 30), (31, 90), (91, None))
def log_status(db: DbSession) -> str:
"""`ok` when the event log is reachable and readable by this role, `absent` when this database
has none (standalone), `no_grant` when it exists but this role may not read it. Catalog reads
only, so a missing grant is a status rather than a failed statement."""
row = db.execute(text(
"SELECT to_regclass('module_event') IS NOT NULL AS present, "
"CASE WHEN to_regclass('module_event') IS NULL THEN false "
"ELSE has_table_privilege(to_regclass('module_event'), 'SELECT') END AS readable"
)).one()
if not row.present:
return "absent"
return "ok" if row.readable else "no_grant"
def _day(column_):
# The zone as a literal, not a bind parameter: each bind is its own placeholder, so the GROUP BY
# expression would not be the select-list one and PostgreSQL refuses the query.
return func.date(func.timezone(literal_column(f"'{ZONE}'"), column_))
def activity(db: DbSession, *, days: int = 30, today: dt.date | None = None) -> dict[str, Any]:
"""Events per day and kind over the last `days` days (today included, the oldest first), every
day present with zeros, and the kinds ordered by their total."""
days = max(1, min(int(days), MAX_DAYS))
status = log_status(db)
if status != "ok":
return {"status": status, "days": [], "kinds": [], "total": 0}
today = today or dt.datetime.now(dt.timezone.utc).date()
first = today - dt.timedelta(days=days - 1)
day = _day(_EVENT.c.created_at)
rows = db.execute(
select(day.label("day"), _EVENT.c.kind, func.count().label("n"))
.where(day >= first, day <= today)
.group_by(day, _EVENT.c.kind)).all()
per_day: dict[dt.date, dict[str, int]] = defaultdict(dict)
totals: dict[str, int] = defaultdict(int)
for when, kind, n in rows:
per_day[when][kind] = n
totals[kind] += n
kinds = sorted(totals, key=lambda k: (-totals[k], k))
return {
"status": "ok",
"days": [{"date": (first + dt.timedelta(days=i)).isoformat(),
"counts": per_day.get(first + dt.timedelta(days=i), {})} for i in range(days)],
"kinds": [{"kind": k, "label": KIND_LABELS.get(k, k), "total": totals[k]} for k in kinds],
"total": sum(totals.values()),
}
# ── durations (Compass `dashboard.durations`, W5-W7, rebuilt on events) ───────
def _runs(chosen: list[int]) -> list[tuple[int, int]]:
"""The chosen stages as unbroken runs, each (first, last): [0, 1, 3] → [(0, 1), (3, 3)]."""
runs: list[tuple[int, int]] = []
for i in sorted(set(chosen)):
if runs and runs[-1][1] == i - 1:
runs[-1] = (runs[-1][0], i)
else:
runs.append((i, i))
return runs
def measure(m: dict[str, dt.date | None], segments) -> int | str:
"""One document's days over the chosen stages, or why it has none: `missing` when an end of a
run is unknown, `order` when a run ends before it starts. Pure, as Compass's."""
names = [name for name, _ in MILESTONES]
total = 0
for first, last in _runs([SEGMENTS.index(s) for s in segments]):
start, end = m.get(names[first]), m.get(names[last + 1])
if start is None or end is None:
return "missing"
if end < start:
return "order"
total += (end - start).days
return total
def milestones(db: DbSession, *, today: dt.date | None = None) -> list[dict[str, dt.date | None]]:
"""Each document's milestone days, from the first event of each milestone kind that names it.
Only documents whose first milestone falls in the last DURATION_YEARS years are measured."""
today = today or dt.datetime.now(dt.timezone.utc).date()
since = today - dt.timedelta(days=365 * DURATION_YEARS)
# `->>` with a literal key, for the GROUP BY reason `_day` gives.
doc = _EVENT.c.payload.op("->>")(literal_column("'document_id'"))
kinds = [kind for _, kind in MILESTONES]
rows = db.execute(
select(doc.label("doc"), _EVENT.c.kind, func.min(_day(_EVENT.c.created_at)).label("day"))
.where(_EVENT.c.kind.in_(kinds), doc.isnot(None))
.group_by(doc, _EVENT.c.kind)).all()
by_doc: dict[str, dict[str, dt.date]] = defaultdict(dict)
name_of = {kind: name for name, kind in MILESTONES}
for document, kind, day in rows:
by_doc[document][name_of[kind]] = day
first = MILESTONES[0][0]
return [m for m in by_doc.values() if m.get(first) and m[first] >= since]
def durations(db: DbSession, segments, *, today: dt.date | None = None) -> dict[str, Any]:
"""How long documents took over the chosen stages: how many were measured, the median, the
bands, and how many were left out and why. Aggregates only — no document is named."""
chosen = [s for s in SEGMENTS if s in segments]
status = log_status(db)
empty = {"segments": chosen, "measured": 0, "median_days": None,
"bands": [{"from": lo, "to": hi, "count": 0} for lo, hi in BANDS],
"skipped": {"missing": 0, "order": 0}}
if status != "ok" or not chosen:
return {"status": status, **empty}
measured, skipped = [], {"missing": 0, "order": 0}
for m in milestones(db, today=today):
days = measure(m, chosen)
if isinstance(days, str):
skipped[days] += 1
else:
measured.append(days)
return {"status": "ok", "segments": chosen, "measured": len(measured),
"median_days": statistics.median(measured) if measured else None,
"bands": [{"from": lo, "to": hi,
"count": sum(lo <= d and (hi is None or d <= hi) for d in measured)}
for lo, hi in BANDS],
"skipped": skipped}
+31
View File
@@ -0,0 +1,31 @@
"""Panorama's trends on Atrium's home (Atrium#53, stage 3). DB-free: the pure parts, and the guard."""
from __future__ import annotations
import datetime as dt
import inspect
from app.routers import marketplace
from app.services import trends
D = dt.date(2026, 11, 1)
def test_a_document_is_measured_over_both_stages():
m = {"created": D, "approved": D + dt.timedelta(days=3), "signed": D + dt.timedelta(days=10)}
assert trends.measure(m, trends.SEGMENTS) == 10
assert trends.measure(m, ["przygotowanie"]) == 3
def test_a_document_without_a_milestone_or_out_of_order_is_left_out():
assert trends.measure({"created": D, "approved": None, "signed": D}, trends.SEGMENTS) == "missing"
late = {"created": D, "approved": D - dt.timedelta(days=1), "signed": D}
assert trends.measure(late, ["przygotowanie"]) == "order"
def test_the_new_kinds_have_labels():
assert {"analysis.accepted", "negotiation.round_received"} <= set(trends.KIND_LABELS)
def test_trends_are_for_platform_administrators_only():
source = inspect.getsource(marketplace.home_trends)
assert "require_administrator" in source
+2 -2
View File
@@ -230,8 +230,8 @@ class TestServiceModules:
def test_galena_is_seeded_as_a_service(self):
from app.seed import FAMILY
flags = {e["slug"]: e.get("in_menu", True) for e in FAMILY}
assert flags["galena"] is False and flags["arbiter"] is False
assert all(flags[s] for s in flags if s not in ("galena", "arbiter"))
assert flags["galena"] is False and flags["arbiter"] is False and flags["panorama"] is False
assert all(flags[s] for s in flags if s not in ("galena", "arbiter", "panorama"))
def test_the_catalogue_hides_it_from_people_not_administrators(self):
body = inspect.getsource(marketplace.browse)
@@ -71,3 +71,13 @@ def test_0017_makes_only_arbiter_a_service_and_back(arbiter_revision, monkeypatc
assert up.startswith("UPDATE module SET in_menu=false") and "module.slug = 'arbiter'" in up
down, = _run(arbiter_revision, monkeypatch, "downgrade")
assert down.startswith("UPDATE module SET in_menu=true") and "module.slug = 'arbiter'" in down
def test_0018_retires_only_panorama_from_the_menu(monkeypatch):
spec = importlib.util.spec_from_file_location(
"revision_0018", BACKEND / "alembic" / "versions" / "0018_panorama_retired.py")
rev = importlib.util.module_from_spec(spec)
spec.loader.exec_module(rev)
assert (rev.revision, rev.down_revision) == ("0018", "0017")
up, = _run(rev, monkeypatch, "upgrade")
assert up.startswith("UPDATE module SET in_menu=false") and "module.slug = 'panorama'" in up
+49
View File
@@ -331,6 +331,21 @@ const I18N = {
'Notatka (nie da się jej później zmienić ani usunąć; nie wpisuj numerów PESEL, dowodu ani paszportu)': 'Note (it cannot be changed or deleted later; do not enter PESEL, identity card or passport numbers)',
'Akceptacja jest jednorazowa i nie da się jej cofnąć ani poprawić.': 'An acceptance is given once and cannot be withdrawn or corrected.',
'Akceptuj analizę': 'Accept the analysis',
'Zdarzenia modułów': 'Module events',
'umowy, obiegi, podpisy i negocjacje, ostatnie 30 dni': 'contracts, approvals, signatures and negotiations, last 30 days',
'Zdarzenia według rodzaju': 'Events by kind',
'ostatnie 30 dni': 'last 30 days',
'Czas obsługi dokumentu': 'Document turnaround',
'dni': 'days',
'dni (mediana)': 'days (median)',
'Zmierzono dokumentów': 'Documents measured',
'od pierwszej wersji do zatwierdzenia': 'from the first version to approval',
'od zatwierdzenia do podpisu': 'from approval to signature',
'Nowe wersje dokumentów': 'New document versions',
'Zatwierdzone obiegi': 'Approved workflows',
'Podpisane dokumenty': 'Signed documents',
'Rundy negocjacji': 'Negotiation rounds',
'Zaakceptowane analizy': 'Accepted analyses',
'Zapisano.': 'Saved.',
'Tej operacji nie da się cofnąć.': 'This cannot be undone.',
'Moduły': 'Modules',
@@ -4880,11 +4895,45 @@ async function loadHomeStats() {
<a class="chart-more" href="#/admin/audit">Dziennik zdarzeń</a></div>`);
}
}
if (p) charts.push(...await homeTrendCards());
if (!$('homeStats')) return;
box.innerHTML = `<div class="home-label"><span>W skrócie</span></div><div class="stats">${tiles.join('')}</div>`
+ `<div class="charts">${charts.join('')}</div>`;
localize(box);
}
/* The platform's trends from the event log (moved from Panorama, Atrium#53 stage 3): events per day
across the modules, and how long documents take from their first version to approval and to
signature. Platform-wide sums, so administrators only; no log (standalone) shows nothing. */
const TREND_SEGMENT = { przygotowanie: 'od pierwszej wersji do zatwierdzenia', podpisanie: 'od zatwierdzenia do podpisu' };
async function homeTrendCards() {
let t;
try { t = await api('GET', '/home/trends?days=30'); } catch { return []; }
const out = [];
const a = t.activity;
if (a && a.status === 'ok' && a.days.length) {
const series = a.days.map((d) => ({ day: d.date, n: Object.values(d.counts).reduce((s, n) => s + n, 0) }));
out.push(chartCard('Zdarzenia modułów', 'umowy, obiegi, podpisy i negocjacje, ostatnie 30 dni', series));
if (a.kinds.length) {
const max = Math.max(...a.kinds.map((k) => k.total));
out.push(`<div class="card chart"><div class="chart-h"><b>Zdarzenia według rodzaju</b><span>ostatnie 30 dni</span></div>
<div class="hbars">${a.kinds.map((k) => `<div class="hbar"><span>${esc(k.label)}</span>
<span class="hbar-t"><i style="width:${Math.max(4, Math.round(k.total / max * 100))}%"></i></span><b>${esc(String(k.total))}</b></div>`).join('')}</div></div>`);
}
}
const d = t.durations;
if (d && d.status === 'ok' && d.measured) {
const max = Math.max(1, ...d.bands.map((b) => b.count));
const band = (b) => (b.to == null ? `${b.from}+` : `${b.from}–${b.to}`) + ' ' + _tr('dni');
out.push(`<div class="card chart"><div class="chart-h"><b>Czas obsługi dokumentu</b><span>${esc(d.segments.map((s) => _tr(TREND_SEGMENT[s] || s)).join(', '))}</span></div>
<div class="chart-v">${esc(String(d.median_days))} <span class="tiny faint">${esc(_tr('dni (mediana)'))}</span></div>
<div class="hbars">${d.bands.map((b) => `<div class="hbar"><span>${esc(band(b))}</span>
<span class="hbar-t"><i style="width:${Math.max(4, Math.round(b.count / max * 100))}%"></i></span><b>${esc(String(b.count))}</b></div>`).join('')}</div>
<div class="tiny faint">${esc(_tr('Zmierzono dokumentów'))}: ${esc(String(d.measured))}</div></div>`);
}
return out;
}
/* Numbers from the modules themselves, read from the dashboards they already serve: one origin
and one account, so the browser asks each module directly with the same session cookie and
Atrium's backend is not involved. Each figure is the module's own permission-filtered count —