Port the dashboard from Compass onto the stats contract and the event log (M4)

Panorama's dashboard is one card per platform module, filled from each
module's GET /api/v1/stats (dredd-core 0.23.0 stats_contract) called with the
person's own session token, so every tile counts only what that person may see
and equals the list it links to. Which modules exist is configuration
(<SLUG>_BASE_URL, empty = absent); an absent, down, slow or closed module is a
status on its card, never an error page.

Trends and durations are aggregates over the shared module_event, read
through the event log's new reader tier (SELECT only) via a table() construct,
so no local module_event shadow is ever built. Compass's dashboard_layout
(own/firm/builtin, strict write, lenient read, audited firm default) moves to
Panorama's own dashboard_layout table; its durations arithmetic is rebuilt on
event milestones. Trends are moderators-only by default (TRENDS_AUDIENCE).

The example entity is gone; 0001 builds with checkfirst=False; provision.sql
and CI's --check-file are the platform rendering. dredd-core is pinned to the
feat/m4-stats commit until v0.23.0 is tagged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-12 21:52:43 +01:00
co-authored by Claude Opus 5.5
parent 607a8f3ab5
commit d196a5f087
29 changed files with 1401 additions and 476 deletions
+20
View File
@@ -72,6 +72,26 @@ DB_LOCAL_HOSTS=
# ── Storage ──────────────────────────────────────────────────────────────────
DATA_DIR=/data
# ── The modules this dashboard reads ─────────────────────────────────────────
# Each module's PUBLIC base URL (https://<site>/galena). Panorama calls GET <url>/api/v1/stats
# with the person's own session (dredd-core's stats contract), so each module counts only what
# that person may see. Empty = not deployed here: shown as absent, never called. Standalone the
# person's Panorama session means nothing to another app, so the cards say "brak dostępu" - the
# numbers need the platform's one account.
GALENA_BASE_URL=
SYGNA_BASE_URL=
COUNSEL_BASE_URL=
COMPASS_BASE_URL=
ARBITER_BASE_URL=
LEXICON_BASE_URL=
AGORA_BASE_URL=
INSIDER_BASE_URL=
# Seconds per module call; the calls run in parallel.
STATS_TIMEOUT_SECONDS=3
# Who sees the trends and durations (aggregates over the shared event log, never per person):
# moderators (this module's moderators and the administrator) or everyone.
TRENDS_AUDIENCE=moderators
# ── One platform, one account ────────────────────────────────────────────────
# The shared identity schema. Empty — this stack — is STANDALONE: Panorama owns its own
# accounts, has its own sign-in screen and its own Users administration, and the three settings
+4 -1
View File
@@ -134,10 +134,13 @@ jobs:
run: pip install -r requirements-dev.txt
- name: db/managed/provision.sql is what dredd-core renders
# The SQL-editor path must never drift from the provisioning routine: exit 1 = stale; re-render it
# with --output instead of --check-file (db/managed/README.md).
# with --output instead of --check-file (db/managed/README.md). Rendered for the PLATFORM
# (--identity-schema / --identity-owner): the rendering Atrium's push.sh compares (Arbiter's
# M1d lesson, as Lexicon and Agora).
run: |
python -m dredd_core.managed provision --sql-only \
--schema panorama --app-role panorama_app --migrator-role panorama_migrator \
--identity-schema dredd --identity-owner atrium_migrator \
--check-file db/managed/provision.sql
- name: Emulate a managed Postgres (TEST-ONLY)
# The service is on localhost, so no --allow-remote (emulate refuses a non-local host without it).
+21 -6
View File
@@ -14,7 +14,7 @@ permissive (no copyleft).
The core is pinned by tag in `backend/requirements.txt`:
```
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.22.0
dredd-core @ git+https://github.com/Alpaq92/dredd-core@f170334895152565d1aac4d63c5d0bada7e92c8b # feat/m4-stats; repin to @v0.23.0 once tagged
```
It is a **private** repository, so installing it needs a token — see `README.md` for the
@@ -79,12 +79,15 @@ backend/app/
observability.py logging_config.py (db/errors/security/enums are shims)
models/ __init__ (shim: re-exports core's AppUser/Session/ModulePermission/AppSetting/AuditLog
[+ Node/PermissionGrant/Favorite in nodes tenancy])
example (the demo entity — this app's own model)
dashboard (DashboardLayout: a person's layout, the firm's default)
services/ auth · audit · moderation (shims over dredd_core)
authz (nodes tenancy: shim over dredd_core.authz · simple: local moderator/owner rules)
changes · settings · nodes · audit_log · example (this app's logic)
changes · settings · nodes · audit_log (this app's logic)
modules (the stats contract: every module's tiles, the person's token)
trends (aggregates over module_event, read via a table() construct)
dashboard_layout (ported from Compass)
(nodes: nodes tenancy only · audit_log: the read-only audit query)
routers/ health auth users admin nodes example dashboard (nodes: nodes tenancy only)
routers/ health auth users admin nodes dashboard (nodes: nodes tenancy only)
backend/tests/ unit (DB-free, always run) + integration (opt-in)
backend/alembic/ env + 0001_initial (pgcrypto, create_enum_types, create_all)
+ 0002_runtime_grants (runtime_grants_sql for DB_APP_ROLE; evidence tables in models/__init__)
@@ -300,5 +303,17 @@ node --check frontend/app.js # ALWAYS after editing the console
## Status
Scaffolded skeleton on dredd-core v0.22.0. The `example` entity (`Record`) is a worked seam —
model → migration → service → router → console screen — to copy for the real domain, then delete.
Scaffolded on dredd-core v0.22.0 (skill `dredd`, simple tenancy, pink, pl-first), then M4: the
dashboard ported from Compass and rebuilt on dredd-core 0.23.0's stats contract and the event log's
reader tier (pinned to the `feat/m4-stats` commit until v0.23.0 is tagged). Invariants of this app:
- **Never read another module's tables.** Current numbers come only from `GET <module>/api/v1/stats`
with the person's own token (`services/modules.py`); a tile equals its list because the module
counted it. Never add, filter or cache tiles across people.
- **Never put `module_event` on this app's metadata** (no `import dredd_core.events`): `0001` would
build a local copy, the platform check's `event shadow`. `services/trends.py` reads it through a
`table()` construct, by `search_path`, and answers `absent` / `no_grant` from the catalog.
- **Trends are aggregates only** — no id, title or list of documents leaves `trends.py` — and they
are kept to `TRENDS_AUDIENCE` (moderators by default), because the log is not filtered per person.
- A grouped expression carries no bind parameter (`_day`, the `->>` key): each bind is a new
placeholder and PostgreSQL then refuses the GROUP BY.
+27 -1
View File
@@ -5,6 +5,32 @@ Pulpit platformy: bieżące liczby z modułów i trendy ze zdarzeń.
Self-hosted and single-tenant, built on **dredd-core** — the shared substrate this app family
installs as a dependency rather than copies.
## What Panorama is
The platform's dashboard (work package M4 of the Compass split, `docs/plans/2026-11-06-podzial-compassu.md`
in the Compass repo), split out of Compass: its dashboard, the per-person layout (`dashboard_layout`)
and the durations chart. It is rebuilt on two read contracts, never on another module's tables:
* **Current numbers** come from each module's `GET /api/v1/stats` (dredd-core's
`stats_contract`, 0.23.0), called with the person's **own session token** through
`dredd_core.module_client`, so each module applies its own authorisation. A tile counts only what
that person may see and equals the list its link opens (`<module>/#/<link>`). Panorama adds
nothing up and re-checks nothing.
* **History and trends** come from the platform's event log (`module_event`, dredd-core 0.20.0),
read through the log's **reader tier** (`SELECT` only, 0.23.0). Events carry ids and numbers only;
the charts show sums (events per day and kind, how long documents took between two kinds of
event), never a document. Because events are not filtered per person, `TRENDS_AUDIENCE` keeps the
charts to moderators by default.
Which modules exist is configuration: `GALENA_BASE_URL`, `SYGNA_BASE_URL`, `COUNSEL_BASE_URL`,
`COMPASS_BASE_URL`, `ARBITER_BASE_URL`, `LEXICON_BASE_URL`, `AGORA_BASE_URL`, `INSIDER_BASE_URL`
(each module's public base URL; empty = not deployed). A module that is absent, down, slow
(`STATS_TIMEOUT_SECONDS`, parallel calls) or closed to the person is a status on its card
(`absent` · `unavailable` · `no_access`), and the rest of the dashboard renders.
Standalone (no `IDENTITY_SCHEMA`) Panorama runs, but its session means nothing to another app and
there is no event log, so every card says so: its numbers need the platform's one account.
## Stack
**FastAPI + SQLAlchemy 2 + Alembic + PostgreSQL 16 / 17**, Argon2id password hashing, server-side
@@ -20,7 +46,7 @@ writer, the security primitives, the shared enums and error types, and the engin
factories all come from one installed package. `backend/requirements.txt` pins it by tag:
```
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.22.0
dredd-core @ git+https://github.com/Alpaq92/dredd-core@f170334895152565d1aac4d63c5d0bada7e92c8b # feat/m4-stats; repin to @v0.23.0 once tagged
```
The app-side files that used to hold that code (`services/auth.py`, `models/__init__.py`,
+10 -3
View File
@@ -26,8 +26,14 @@ lifespan's `assert_identity_schema` is what proves `0003` then took them away ag
Nothing here is schema-qualified. Tables, enum types and `alembic_version` land in the first schema on
the migrator's search_path (`public` locally; `panorama, extensions` on the shared project, set by
provisioning), and `create_all`'s checkfirst and `create_enum_types` only look there — so a sibling
app's `audit_log` or `node_role` in *its* schema never makes a table or type here get skipped.
provisioning; `panorama, dredd, extensions` on the platform). `create_enum_types` only looks there, but
`create_all`'s default checkfirst does NOT: SQLAlchemy asks whether a table is VISIBLE, which follows
the whole search_path. On the platform `dredd.app_user`, `dredd.session` and `dredd.module_event`
are visible, so a checkfirst build would skip the local copies and create the foreign keys straight
against the hub's tables, and `0003`'s repoint would then reach the hub's tables and die on "must be
owner" (Arbiter's M1d platform rehearsal). Hence `checkfirst=False`, as Galena's, Arbiter's, Lexicon's
and Agora's `0001`: on a fresh schema there is nothing to check, and the local copies are exactly what
`0003` is written to move and drop.
Bumping the dredd-core pin can change what `Base.metadata` holds. That is an ordinary schema change
for this app and belongs in a **new** revision — never in an edit to this one.
@@ -102,7 +108,8 @@ def upgrade() -> None:
op.execute('CREATE EXTENSION IF NOT EXISTS "pgcrypto"')
# Order matters — the enum columns are create_type=False (see the module docstring).
create_enum_types(bind)
Base.metadata.create_all(bind=bind)
# checkfirst=False: see the module docstring.
Base.metadata.create_all(bind=bind, checkfirst=False)
def downgrade() -> None:
+45
View File
@@ -97,6 +97,51 @@ class Settings(BaseSettings):
# Working directory for anything written to disk (exports, generated documents).
data_dir: str = "data"
# ── The modules Panorama reads (dredd_core.stats_contract) ─────────────────────
# Each module's PUBLIC base URL (`https://<site>/galena`), as for every module-to-module call in
# the family (dredd_core.module_client): the call hairpins out through the platform's front door
# with the acting person's own session token, so each module applies its own authorisation and a
# person sees only their own numbers. Empty = the module is not deployed here: the dashboard
# shows it as absent and never calls it. A module that is configured but down, slow or closed
# to this person is a status on its card, never an error page.
galena_base_url: str = ""
sygna_base_url: str = ""
counsel_base_url: str = ""
compass_base_url: str = ""
arbiter_base_url: str = ""
lexicon_base_url: str = ""
agora_base_url: str = ""
insider_base_url: str = ""
# One time budget per module call (seconds); the calls run in parallel.
stats_timeout_seconds: float = Field(default=3.0, gt=0, le=30)
# Who sees the trends and durations (aggregates over the platform's event log, dredd-core
# 0.20.0). Events are not filtered per person - they carry ids and numbers only, and a chart
# shows sums - so the default keeps them to this module's moderators and the administrator;
# `everyone` shows them to every person admitted to Panorama.
trends_audience: str = "moderators"
@field_validator("galena_base_url", "sygna_base_url", "counsel_base_url", "compass_base_url",
"arbiter_base_url", "lexicon_base_url", "agora_base_url", "insider_base_url")
@classmethod
def _module_url_is_a_safe_address(cls, v: str) -> str:
v = v.strip()
if v:
from dredd_core.errors import ValidationError
from dredd_core.module_client import check_base_url
try:
check_base_url(v)
except ValidationError as exc: # an AppError, which pydantic would not report
raise ValueError(f"{exc.detail} ({exc.extra.get('code')})") from None
return v
@field_validator("trends_audience")
@classmethod
def _known_trends_audience(cls, v: str) -> str:
v = v.strip().lower()
if v not in ("moderators", "everyone"):
raise ValueError("TRENDS_AUDIENCE must be 'moderators' or 'everyone'")
return v
# ── One platform, one account ────────────────────────────────────────────────
# The shared identity schema. Empty — the default, and what this repo's own compose stack runs —
# is the STANDALONE deployment: Panorama owns `app_user` / `session` / `module_permission` in
+3 -11
View File
@@ -13,8 +13,6 @@ builds core's types and this app's own from the model metadata (the columns use
"""
from __future__ import annotations
from enum import StrEnum
from dredd_core.enums import SessionKind, TokenScope
# NOTE: SessionKind and TokenScope back plain Text columns, NOT native PG enums — core's choice,
@@ -23,19 +21,13 @@ from dredd_core.enums import SessionKind, TokenScope
# ── Panorama's own ────────────────────────────────────────────────────────
# Demo enum for the `example` entity. Replace it with the real domain. A new enum needs no edit to
# the migration: declare it here, bind it with `pg_enum(MyEnum, "my_enum")` on the model, and make
# sure the model is imported in `app/models/__init__.py` — `create_enum_types` reads it from the
# metadata, and the table itself is picked up by `create_all`.
class RecordStatus(StrEnum):
open = "open"
done = "done"
# None yet. A new enum needs no edit to the migration: declare it here, bind it with
# `pg_enum(MyEnum, "my_enum")` on the model, and make sure the model is imported in
# `app/models/__init__.py` — `create_enum_types` reads it from the metadata.
__all__ = [
# from dredd-core, unchanged
"SessionKind",
"TokenScope",
# this app's own
"RecordStatus",
]
+2 -2
View File
@@ -21,7 +21,7 @@ from .edge import BodySizeLimit, ConsoleUnlessApi, SecurityHeaders, SpaStaticFil
from .errors import ProblemDetailErrorMiddleware, install_error_handlers
from .logging_config import configure_logging
from .observability import setup_observability
from .routers import admin, auth, dashboard, example, health, users
from .routers import admin, auth, dashboard, health, users
API_PREFIX = "/api/v1"
@@ -116,7 +116,7 @@ if settings.cors_origins_list:
for router in (
health.router, auth.router, users.router, admin.router,
example.router, dashboard.router,
dashboard.router,
):
app.include_router(router, prefix=API_PREFIX)
+5 -3
View File
@@ -22,7 +22,9 @@ are still created by the migration. They stay empty and unused; that is expected
Leave them alone rather than trying to drop them — a later move to tree tenancy just starts
using them.
Add your own models next to `.example` and import them below.
Panorama's own table is `dashboard_layout` (a person's layout and the firm's default). Its numbers
are not stored here at all: current counts come from each module's stats endpoint, trends from the
platform's event log.
"""
from dredd_core import (
AppSetting,
@@ -37,7 +39,7 @@ from dredd_core import (
pg_enum,
)
from .example import Record
from .dashboard import DashboardLayout
# ── evidence tables: what the runtime role may never rewrite ──────────────────────────────────────
# The runtime-grants migration (alembic/versions/0002_runtime_grants.py, and every later revision
@@ -59,6 +61,6 @@ __all__ = [
# but the table is on `Base.metadata`, so it has to be re-exported here or `own_tables(...,
# shared=SHARED_IDENTITY_TABLES)` would be excluding a name this app never imported.
"AppUser", "Session", "ModulePermission", "AppSetting", "AuditLog",
"Record",
"DashboardLayout",
"APPEND_ONLY_TABLES", "NO_DELETE_TABLES",
]
+33
View File
@@ -0,0 +1,33 @@
"""The dashboard's layout: which elements a person shows, in what order and how large.
Ported from Compass (`services/dashboard_layout.py`, spec 2026-10-13 pulpit-uklad U1-U6), where it
was a row of core's `table_view`. Panorama has no tables to view, so the layout is its own small
table with the same three levels: a person's own (`user_id` set), the firm's default set by a
moderator (`user_id` NULL, at most one such row), the one built into the code (no row at all).
"""
from __future__ import annotations
import uuid
from typing import Any
from sqlalchemy import ForeignKey, Index, UniqueConstraint, text
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column
from dredd_core import Base, TimestampMixin, UUIDPkMixin
class DashboardLayout(UUIDPkMixin, TimestampMixin, Base):
__tablename__ = "dashboard_layout"
# NULL = the firm's default. A person's row goes with the person.
user_id: Mapped[uuid.UUID | None] = mapped_column(
ForeignKey("app_user.id", ondelete="CASCADE"))
config: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False)
__table_args__ = (
UniqueConstraint("user_id", name="uq_dashboard_layout_user_id"),
# NULLs are distinct in a unique constraint, so the one firm default needs its own index.
Index("uq_dashboard_layout_firm", text("(user_id IS NULL)"), unique=True,
postgresql_where=text("user_id IS NULL")),
)
-27
View File
@@ -1,27 +0,0 @@
"""The demo domain entity — a worked seam to copy, then delete."""
from __future__ import annotations
import uuid
from sqlalchemy import ForeignKey, Index, Text
from sqlalchemy.orm import Mapped, mapped_column
from dredd_core import Base, TimestampMixin, UUIDPkMixin, pg_enum
from ..enums import RecordStatus
class Record(UUIDPkMixin, TimestampMixin, Base):
__tablename__ = "record"
name: Mapped[str] = mapped_column(Text, nullable=False)
note: Mapped[str | None] = mapped_column(Text)
status: Mapped[RecordStatus] = mapped_column(
pg_enum(RecordStatus, "record_status"), nullable=False
)
# Who may act on the row, in the absence of a permission tree. Services check this; the
# instance admin bypasses it.
owner_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
created_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
__table_args__ = (Index("ix_record_status", "status"),)
+82 -16
View File
@@ -1,30 +1,96 @@
"""What the console's landing screen needs, in one round trip.
"""The dashboard: current numbers from every module, trends from the event log, the layout.
One endpoint rather than five: the dashboard is the first thing every user loads, and five
parallel requests on a cold connection is the difference between "instant" and "sluggish". The
counts come from the same permission-filtered service the list screens use, so a tile can never
report a number that includes something the reader may not open.
`GET /dashboard` asks every configured module for its tiles with the person's OWN credential (the
token this request carries), so each module applies its own authorisation and the dashboard shows
only what this person may see there; a module that is absent, down or closed to them is a status on
its card. `GET /dashboard/activity` and `GET /dashboard/durations` are aggregates over the event
log, kept to `TRENDS_AUDIENCE`. The layout routes are Compass's, unchanged in shape.
Not audited: the tiles are counts of what the person can already open, and the trends are sums.
"""
from __future__ import annotations
from fastapi import APIRouter, Depends
from typing import Any, Literal
from fastapi import APIRouter, Body, Depends, Query, Request
from sqlalchemy.orm import Session
from ..config import get_settings
from ..db import get_db
from ..deps import get_current_user
from ..deps import client_ip, extract_token, get_current_user, require_moderator
from ..errors import AuthorizationError
from ..models import AppUser
from ..services import example as service
from ..services import dashboard_layout, moderation, modules, trends
router = APIRouter(tags=["dashboard"])
def _may_see_trends(db: Session, user: AppUser) -> bool:
return get_settings().trends_audience == "everyone" or moderation.is_moderator(db, user)
def _trends_reader(db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> AppUser:
if not _may_see_trends(db, user):
raise AuthorizationError("Trendy widzą moderatorzy tego modułu.",
{"code": "trends_moderators_only"})
return user
@router.get("/dashboard")
def dashboard(db: Session = Depends(get_db),
def dashboard(request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
rows = service.list_records(db, user)
counts = {
"total": len(rows),
"open": sum(1 for r in rows if r["status"] == "open"),
"done": sum(1 for r in rows if r["status"] == "done"),
}
return {"cards": counts, "recent": rows[:8]}
return {"modules": modules.current(token=extract_token(request)),
"trends": _may_see_trends(db, user)}
@router.get("/dashboard/activity")
def activity(days: int = Query(30, ge=1, le=trends.MAX_DAYS), db: Session = Depends(get_db),
_: AppUser = Depends(_trends_reader)) -> dict:
return trends.activity(db, days=days)
Segment = Literal["przygotowanie", "podpisanie"]
@router.get("/dashboard/durations")
def durations(segment: list[Segment] = Query(..., min_length=1), db: Session = Depends(get_db),
_: AppUser = Depends(_trends_reader)) -> dict:
return trends.durations(db, segment)
@router.get("/dashboard/layout")
def read_layout(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
return dashboard_layout.current(db, user)
@router.put("/dashboard/layout/me")
def save_own_layout(config: Any = Body(...), db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
dashboard_layout.save_own(db, user=user, config=config)
db.commit()
return dashboard_layout.current(db, user)
@router.delete("/dashboard/layout/me")
def delete_own_layout(db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
dashboard_layout.delete_own(db, user=user)
db.commit()
return dashboard_layout.current(db, user)
@router.put("/admin/dashboard/layout")
def save_firm_layout(request: Request, config: Any = Body(...), db: Session = Depends(get_db),
admin: AppUser = Depends(require_moderator)) -> dict:
dashboard_layout.save_firm_default(db, actor=admin, config=config, ip=client_ip(request))
db.commit()
return dashboard_layout.current(db, admin)
@router.delete("/admin/dashboard/layout")
def delete_firm_layout(request: Request, db: Session = Depends(get_db),
admin: AppUser = Depends(require_moderator)) -> dict:
dashboard_layout.delete_firm_default(db, actor=admin, ip=client_ip(request))
db.commit()
return dashboard_layout.current(db, admin)
-59
View File
@@ -1,59 +0,0 @@
"""The demo entity's HTTP surface — copy this shape, then delete the file.
Note what is NOT here: no `select(...)`, no `db.add`, no permission logic. The router validates,
delegates, commits, and shapes the response. That separation is what lets one reviewer check
every access rule by reading `services/authz.py` and the services, not twenty route handlers.
"""
from __future__ import annotations
import uuid
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 ..enums import RecordStatus
from ..models import AppUser
from ..schemas import RecordCreateIn, RecordUpdateIn
from ..services import example as service
router = APIRouter(prefix="/records", tags=["records"])
@router.get("")
def list_records(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user),
q: str = Query("", max_length=200), status: RecordStatus | None = Query(None)) -> list[dict]:
return service.list_records(db, user, q=q, status=status)
@router.get("/{record_id}")
def get_record(record_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
return service.get_record(db, user, record_id)
@router.post("", status_code=201)
def create_record(body: RecordCreateIn, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
out = service.create_record(db, user, name=body.name, note=body.note, ip=client_ip(request))
db.commit()
return out
@router.patch("/{record_id}")
def update_record(record_id: uuid.UUID, body: RecordUpdateIn, request: Request,
db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
out = service.update_record(db, user, record_id, name=body.name, note=body.note,
status=body.status, ip=client_ip(request))
db.commit()
return out
@router.delete("/{record_id}")
def delete_record(record_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
service.delete_record(db, user, record_id, ip=client_ip(request))
db.commit()
return {"status": "ok"}
-16
View File
@@ -13,7 +13,6 @@ from typing import Annotated, Any
from dredd_core.enums import NodeRole
from pydantic import AfterValidator, BaseModel, Field
from .enums import RecordStatus
_EMAIL = re.compile(r"^[^@\s]+@[^@\s.]+(\.[^@\s.]+)+$")
@@ -105,21 +104,6 @@ class GrantIn(BaseModel):
role: NodeRole
# ── the demo entity ───────────────────────────────────────────────────────────
class RecordCreateIn(BaseModel):
name: str = Field(min_length=1, max_length=200)
note: str | None = Field(default=None, max_length=4000)
# Required in node tenancy (which container it goes in); ignored in simple tenancy.
parent_id: uuid.UUID | None = None
class RecordUpdateIn(BaseModel):
"""Every field optional: `None` means "not supplied", never "blank it"."""
name: str | None = Field(default=None, min_length=1, max_length=200)
note: str | None = Field(default=None, max_length=4000)
status: RecordStatus | None = None
# ── administration ────────────────────────────────────────────────────────────
class SettingsIn(BaseModel):
"""A partial set of settings to change, validated against `services/settings.SPECS`."""
-8
View File
@@ -18,14 +18,11 @@ from __future__ import annotations
import logging
from dredd_core.db import make_engine, make_session_factory
from sqlalchemy import select
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import NullPool
from .config import get_settings
from .db import SessionLocal
from .enums import RecordStatus
from .models import Record
from .services import auth as auth_service
log = logging.getLogger("panorama.seed")
@@ -55,11 +52,6 @@ def run(session_factory: sessionmaker | None = None) -> None:
)
log.info("Created bootstrap admin %s", admin.email)
if settings.seed_demo and db.scalar(select(Record.id)) is None:
db.add(Record(name="Nowy rekord", note="Notatka",
status=RecordStatus.open, owner_id=admin.id, created_by=admin.id))
log.info("Seeded demo data")
db.commit()
finally:
db.close()
+160
View File
@@ -0,0 +1,160 @@
"""The dashboard's layout: which elements it shows, in what order and how large.
Ported from Compass (`services/dashboard_layout.py`, spec 2026-10-13 pulpit-uklad U1-U6) with its
rules intact: three levels (the person's own, the firm's default set by a moderator, the built-in
one), strict on write (an unknown element, a size it does not take or an element twice is a 422 in
Polish), lenient on read (whatever stopped holding is dropped, so the dashboard always loads), the
person's own not audited, the firm's default audited as `dashboard_layout.firm_default`.
What changed is what an element is. Compass's were its own tiles and charts; Panorama's are one card
per MODULE of the platform (`module.<slug>`, the tiles that module answers with) and the two charts
built on the event log. A layout changes what is shown, never what is counted.
"""
from __future__ import annotations
from typing import Any
from sqlalchemy import Integer, Text, delete, func, literal, select, text
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.orm import Session as DbSession
from ..errors import ValidationError
from ..models import AppUser, DashboardLayout
from . import audit
from .modules import SLUGS
KEY = "dashboard"
#: The advisory lock every write of the firm's layout takes (paired with hashtext(KEY)), so two
#: writes queue and the audit's "before" is the layout in force. Compass's class key.
_LOCK_CLASS = 0x44435456
#: s = one column of six, m = half the row, l = the whole row (U2); a phone shows two columns.
CARD = ("m", "l")
#: Every element there is, in the built-in order, with the sizes it takes; the first is its default.
WIDGETS: dict[str, tuple[str, ...]] = {
**{f"module.{slug}": CARD for slug in SLUGS},
"chart.activity": ("l", "m"),
"chart.durations": ("l", "m"),
}
#: The built-in layout.
BUILTIN = {"v": 1, "widgets": [{"key": k, "size": sizes[0]} for k, sizes in WIDGETS.items()]}
def _widget_ok(widget: Any) -> bool:
return (isinstance(widget, dict) and isinstance(widget.get("key"), str)
and widget.get("key") in WIDGETS
and widget.get("size") in WIDGETS[widget["key"]])
def checked(config: Any) -> dict[str, Any]:
"""`config` as stored, or a 422 saying what is wrong with it (U3)."""
if not isinstance(config, dict) or set(config) - {"v", "widgets"}:
raise ValidationError("Układ pulpitu ma postać {v, widgets}.")
if config.get("v") != 1:
raise ValidationError("Nieznana wersja układu pulpitu.")
widgets = config.get("widgets")
if not isinstance(widgets, list):
raise ValidationError("Układ pulpitu potrzebuje listy elementów.")
out: list[dict[str, str]] = []
for widget in widgets:
if not isinstance(widget, dict) or set(widget) - {"key", "size"}:
raise ValidationError("Element pulpitu ma postać {key, size}.")
if not isinstance(widget.get("key"), str) or widget["key"] not in WIDGETS:
raise ValidationError("Pulpit nie zna takiego elementu.")
if widget.get("size") not in WIDGETS[widget["key"]]:
raise ValidationError("Ten element nie ma takiego rozmiaru.")
if any(w["key"] == widget["key"] for w in out):
raise ValidationError("Ten sam element występuje na pulpicie dwa razy.")
out.append({"key": widget["key"], "size": widget["size"]})
return {"v": 1, "widgets": out}
def readable(config: Any) -> dict[str, Any] | None:
"""A stored layout without what stopped holding; `None` when nothing of it can be read."""
if not isinstance(config, dict) or not isinstance(config.get("widgets"), list):
return None
out: list[dict[str, str]] = []
for widget in config["widgets"]:
if _widget_ok(widget) and all(w["key"] != widget["key"] for w in out):
out.append({"key": widget["key"], "size": widget["size"]})
return {"v": 1, "widgets": out}
def current(db: DbSession, user: AppUser) -> dict[str, Any]:
"""`GET /dashboard/layout`: the layout in force for `user`, whose it is, the firm's default
and every element there is with its sizes."""
own_row, firm_row = _row(db, user.id), _row(db, None)
own = readable(own_row.config) if own_row else None
firm = readable(firm_row.config) if firm_row else None
layout, source = ((own, "user") if own is not None else (firm, "firm") if firm is not None
else (BUILTIN, "builtin"))
return {"layout": layout, "source": source, "firm_default": firm,
"widgets": [{"key": k, "sizes": list(sizes)} for k, sizes in WIDGETS.items()]}
def save_own(db: DbSession, *, user: AppUser, config: Any) -> None:
_put(db, user.id, checked(config))
def delete_own(db: DbSession, *, user: AppUser) -> None:
db.execute(delete(DashboardLayout).where(DashboardLayout.user_id == user.id))
def save_firm_default(db: DbSession, *, actor: AppUser, config: Any,
ip: str | None = None) -> None:
config = checked(config)
_serialize_firm_default(db)
before = _row(db, None)
old = dict(before.config) if before else {}
_put(db, None, config)
if old != config:
_audit(db, actor, _row(db, None), old, config, ip)
def delete_firm_default(db: DbSession, *, actor: AppUser, ip: str | None = None) -> None:
_serialize_firm_default(db)
row = _row(db, None)
if row is None:
return
_audit(db, actor, row, dict(row.config), {}, ip)
db.delete(row)
db.flush()
# ── the row ──────────────────────────────────────────────────────────────────
def _row(db: DbSession, user_id) -> DashboardLayout | None:
# populate_existing: `_put` is a Core upsert, which an object already in the session does not
# see; after the lock this is the layout as committed now.
owner = (DashboardLayout.user_id.is_(None) if user_id is None
else DashboardLayout.user_id == user_id)
return db.scalars(select(DashboardLayout).where(owner)
.execution_options(populate_existing=True)).first()
def _put(db: DbSession, user_id, config: dict) -> None:
stmt = insert(DashboardLayout).values(user_id=user_id, config=config)
if user_id is None:
stmt = stmt.on_conflict_do_update(
index_elements=[text("(user_id IS NULL)")],
index_where=DashboardLayout.user_id.is_(None),
set_={"config": config, "updated_at": func.now()})
else:
stmt = stmt.on_conflict_do_update(
constraint="uq_dashboard_layout_user_id",
set_={"config": config, "updated_at": func.now()})
db.execute(stmt)
def _serialize_firm_default(db: DbSession) -> None:
"""Every write of the firm's layout waits for the one before it to end. An advisory lock,
because the first save has no row to lock yet."""
db.execute(select(func.pg_advisory_xact_lock(
literal(_LOCK_CLASS, Integer), func.hashtext(literal(KEY, Text)))))
def _audit(db: DbSession, actor: AppUser, row: DashboardLayout, before: dict, after: dict,
ip: str | None) -> None:
audit.record(db, actor_id=actor.id, action="dashboard_layout.firm_default",
entity_type="dashboard_layout", entity_id=row.id, detail=KEY, ip=ip,
diff={"layout": [before, after]})
-105
View File
@@ -1,105 +0,0 @@
"""The demo domain service — the seam to copy for real work, then delete.
What it demonstrates, and what your real services should keep doing:
* every read and write goes through `authz`, including the list query;
* `None` means "not supplied", never "blank it";
* anything worth reconstructing later is written to the append-only audit log.
"""
from __future__ import annotations
import uuid
from sqlalchemy import select
from sqlalchemy.orm import Session as DbSession
from ..enums import RecordStatus
from ..errors import NotFoundError, ValidationError
from ..models import AppUser, Record
from . import audit, authz, changes
def _as_dict(r: Record) -> dict:
return {
"id": str(r.id), "name": r.name, "note": r.note, "status": r.status.value,
"owner_id": str(r.owner_id) if r.owner_id else None,
"created_at": r.created_at.isoformat() if r.created_at else None,
}
def list_records(db: DbSession, user: AppUser, *, q: str = "",
status: str | None = None) -> list[dict]:
stmt = select(Record)
if q:
stmt = stmt.where(Record.name.ilike(f"%{q}%"))
if status:
stmt = stmt.where(Record.status == RecordStatus(status))
rows = list(db.scalars(stmt.order_by(Record.created_at.desc())).all())
return [_as_dict(r) for r in rows if authz.can_read(db, user, r.owner_id)]
def get_record(db: DbSession, user: AppUser, record_id: uuid.UUID) -> dict:
row = db.get(Record, record_id)
if row is None:
raise NotFoundError("Not found.")
authz.assert_can_read(db, user, row.owner_id)
return _as_dict(row)
def create_record(db: DbSession, user: AppUser, *, name: str, note: str | None = None,
ip: str | None = None) -> dict:
name = (name or "").strip()
if not name:
raise ValidationError("Give it a name.")
row = Record(name=name, note=note, status=RecordStatus.open,
owner_id=user.id, created_by=user.id)
db.add(row)
db.flush()
audit.record(db, action="record.create", entity_type="record", entity_id=row.id,
actor_id=user.id, detail=name, ip=ip)
return _as_dict(row)
def update_record(db: DbSession, user: AppUser, record_id: uuid.UUID, *,
name: str | None = None, note: str | None = None,
status: str | None = None, ip: str | None = None) -> dict:
row = db.get(Record, record_id)
if row is None:
raise NotFoundError("Not found.")
authz.assert_can_write(db, user, row.owner_id)
before = {"name": row.name, "note": row.note, "status": row.status.value}
# `None` means "not supplied", never "blank it" — otherwise a partial update silently wipes
# the fields it didn't mention.
if name is not None:
row.name = name.strip() or row.name
if note is not None:
row.note = note
if status is not None:
row.status = RecordStatus(status)
after = {"name": row.name, "note": row.note, "status": row.status.value}
db.flush()
audit.record(db, action="record.update", entity_type="record", entity_id=row.id,
actor_id=user.id, ip=ip, diff=changes.diff_of(before, after))
return _as_dict(row)
def delete_record(db: DbSession, user: AppUser, record_id: uuid.UUID,
ip: str | None = None) -> None:
row = db.get(Record, record_id)
if row is None:
raise NotFoundError("Not found.")
authz.assert_can_write(db, user, row.owner_id)
audit.record(db, action="record.delete", entity_type="record", entity_id=row.id,
actor_id=user.id, detail=row.name, ip=ip)
db.delete(row)
db.flush()
def counts(db: DbSession, user: AppUser) -> dict:
rows = list_records(db, user)
return {
"total": len(rows),
"open": sum(1 for r in rows if r["status"] == RecordStatus.open.value),
"done": sum(1 for r in rows if r["status"] == RecordStatus.done.value),
}
+67
View File
@@ -0,0 +1,67 @@
"""The current numbers: every configured module's tiles, read with the person's own session.
Each module answers dredd-core's stats contract (`GET <module>/api/v1/stats`,
`dredd_core.stats_contract`): tiles that count only what the CALLER may see, each equal to the list
its link opens. Panorama never adds, filters or re-checks them; it lays them out. Which modules
exist is configuration (`<SLUG>_BASE_URL`, empty = not deployed here), and a module that is absent,
down, slow or closed to this person is a status on its card — the dashboard always renders.
No database: nothing here is stored. The numbers are as fresh as the call.
"""
from __future__ import annotations
from typing import Any
from dredd_core import stats_contract
from ..config import Settings, get_settings
#: Every module of the platform Panorama knows how to ask, in the order the dashboard shows them:
#: slug (the module's path and `module_permission.module_slug`) and its name in the console.
CATALOG: tuple[tuple[str, str], ...] = (
("galena", "Dokumenty"),
("compass", "Obieg"),
("arbiter", "Analizy"),
("lexicon", "Biblioteka klauzul"),
("agora", "Negocjacje"),
("sygna", "Sprawy"),
("counsel", "Ocena pracy"),
("insider", "Akty prawne"),
)
SLUGS = tuple(slug for slug, _ in CATALOG)
def configured(settings: Settings | None = None) -> dict[str, str]:
"""`slug → base URL` for every module of the catalog; an empty URL is a module not deployed."""
settings = settings or get_settings()
return {slug: getattr(settings, f"{slug}_base_url", "") or "" for slug in SLUGS}
def _href(base_url: str, link: str) -> str:
"""Where a tile leads in the browser: the module's console at its hash route. `link` passed the
contract's validator (relative, no scheme, no leading `/` or `#`), and the base URL passed
`module_client.check_base_url` at start-up."""
return f"{base_url.rstrip('/')}/#/{link}"
def current(*, token: str | None, settings: Settings | None = None,
gather=stats_contract.gather) -> list[dict[str, Any]]:
"""One card per catalog module: its name, status, tiles (each with the `href` its link opens)
and, when it answered, when its numbers were taken. `gather` is the test seam."""
settings = settings or get_settings()
urls = configured(settings)
names = dict(CATALOG)
lines = gather(urls, token=token, timeout=settings.stats_timeout_seconds)
out = []
for line in lines:
base = urls[line["module"]]
out.append({
"module": line["module"],
"name": names[line["module"]],
"status": line["status"],
"reason": line["reason"],
"as_of": line["as_of"],
"url": f"{base.rstrip('/')}/" if base else None,
"tiles": [dict(tile, href=_href(base, tile["link"])) for tile in line["tiles"]],
})
return out
+193
View File
@@ -0,0 +1,193 @@
"""History and trends: aggregates over the platform's event log (`module_event`, dredd-core 0.20.0).
The owner's decision for Panorama (Compass split plan, 2026-11-06): current numbers come from each
module's stats endpoint, history and trends from the event log. An event carries identifiers and
numbers only — never a title, a name or a sentence (`dredd_core.events.check_payload`) — and this
module shows nothing but sums of them: events per day and kind, and how long documents took between
two kinds of event (the part of Compass's `dashboard.durations` that events can answer). No id ever
leaves this file; no list of documents is returned.
**Where the log is.** On the platform it is `dredd.module_event`, created and granted by the hub;
Panorama's runtime role reads it through the event log's READER tier (`event_grants_sql(...,
reader_roles=[panorama_app])`, dredd-core 0.23.0: `SELECT` and nothing else). The table is reached
the family's way, through the `search_path`, never schema-qualified. Panorama does NOT import
`dredd_core.events`: that would put `module_event` on this app's metadata and `0001` would build a
local copy - the shadow the platform check calls `event shadow`. A lightweight `table()` construct
reads it instead. **Standalone** nobody writes events into Panorama's schema, so there is no log and
the charts say so; nothing fails.
Events are not filtered per person (the log has no notion of who may read the subject), which is why
`TRENDS_AUDIENCE` keeps these charts to moderators unless an operator opens them to everyone.
"""
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 the hub has not given Panorama the reader
tier. 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}
+5 -1
View File
@@ -25,7 +25,11 @@
# The repo is PRIVATE, so pip needs credentials to fetch it:
# local — a GitHub PAT in your git credential helper (or an SSH `insteadOf` rewrite)
# CI — the DREDD_CORE_TOKEN repo secret; see the auth step in .github/workflows/ci.yml
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.22.0
#
# Panorama needs 0.23.0: `dredd_core.stats_contract` (the tiles) and the event log's reader tier.
# TEMPORARY: pinned to the dredd-core branch `feat/m4-stats` (commit f170334) until v0.23.0 is
# tagged; REPIN to `@v0.23.0` then (and in README.md / CLAUDE.md).
dredd-core @ git+https://github.com/Alpaq92/dredd-core@f170334895152565d1aac4d63c5d0bada7e92c8b
# Web framework
fastapi==0.115.6
+208
View File
@@ -0,0 +1,208 @@
"""The dashboard, DB-free: the module cards over the stats contract, the layout's rules, the
durations' arithmetic, and who may see the trends."""
from __future__ import annotations
import datetime as dt
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from types import SimpleNamespace
import pytest
from dredd_core import stats_contract
from app.config import Settings
from app.errors import ValidationError
from app.services import dashboard_layout as layout
from app.services import modules, trends
def _settings(**urls):
return Settings(**urls)
# ── the module cards ─────────────────────────────────────────────────────────────
class _Galena(BaseHTTPRequestHandler):
"""A module that answers the contract — and counts what the TOKEN may see, as Galena does."""
seen: list = []
def log_message(self, *args):
pass
def do_GET(self): # noqa: N802
_Galena.seen.append((self.path, self.headers.get("Authorization")))
if self.headers.get("Authorization") != "Bearer alice":
body, status = {"title": "Unauthorized"}, 401
else:
body, status = stats_contract.make_response("galena", [
stats_contract.make_tile(key="contracts", label="Umowy w rejestrze", count=2,
link="cards")]), 200
raw = json.dumps(body).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
@pytest.fixture(scope="module")
def galena_url():
server = ThreadingHTTPServer(("127.0.0.1", 0), _Galena)
threading.Thread(target=server.serve_forever, daemon=True).start()
yield f"http://127.0.0.1:{server.server_address[1]}/galena"
server.shutdown()
server.server_close()
def test_every_catalog_module_gets_a_card_and_the_tiles_link_into_the_module(galena_url):
cards = modules.current(token="alice", settings=_settings(galena_base_url=galena_url))
assert [c["module"] for c in cards] == list(modules.SLUGS)
galena = cards[0]
assert galena["status"] == "ok" and galena["url"] == galena_url + "/"
assert galena["tiles"] == [{"key": "contracts", "label": "Umowy w rejestrze", "count": 2,
"link": "cards", "href": galena_url + "/#/cards"}]
# Not configured = absent, never called.
assert {c["status"] for c in cards[1:]} == {"absent"}
assert _Galena.seen[-1] == ("/galena/api/v1/stats", "Bearer alice")
def test_a_person_the_module_does_not_know_sees_no_access_not_an_error(galena_url):
cards = modules.current(token="mallory", settings=_settings(galena_base_url=galena_url))
assert (cards[0]["status"], cards[0]["reason"], cards[0]["tiles"]) == (
"no_access", "status_401", [])
def test_a_module_that_is_down_is_unavailable_and_the_rest_still_render(galena_url):
# A port nothing listens on: the call fails fast; the dashboard still answers for the others.
cards = modules.current(token="alice", settings=_settings(
galena_base_url=galena_url, sygna_base_url="http://127.0.0.1:9/sygna"))
by = {c["module"]: c for c in cards}
assert by["galena"]["status"] == "ok"
assert by["sygna"]["status"] == "unavailable" and by["sygna"]["tiles"] == []
def test_a_bad_module_address_refuses_start_up():
with pytest.raises(ValueError):
Settings(galena_base_url="ftp://x")
with pytest.raises(ValueError):
Settings(galena_base_url="https://user:pw@x/galena")
with pytest.raises(ValueError):
Settings(trends_audience="anyone")
# ── the layout ──────────────────────────────────────────────────────────────────
def test_the_builtin_layout_holds_every_module_and_both_charts():
keys = [w["key"] for w in layout.BUILTIN["widgets"]]
assert keys == [f"module.{s}" for s in modules.SLUGS] + ["chart.activity", "chart.durations"]
assert layout.checked(layout.BUILTIN) == layout.BUILTIN
@pytest.mark.parametrize("config", [
[], {"v": 2, "widgets": []}, {"v": 1}, {"v": 1, "widgets": {}}, {"v": 1, "widgets": [], "x": 1},
{"v": 1, "widgets": [{"key": "module.nope", "size": "m"}]},
{"v": 1, "widgets": [{"key": "module.galena", "size": "s"}]},
{"v": 1, "widgets": [{"key": "module.galena", "size": "m"}] * 2},
{"v": 1, "widgets": [{"key": "chart.activity", "size": "l", "extra": 1}]},
])
def test_a_bad_layout_is_a_polish_422(config):
with pytest.raises(ValidationError):
layout.checked(config)
def test_reading_a_stale_layout_drops_what_stopped_holding():
stored = {"v": 1, "widgets": [{"key": "module.gone", "size": "m"},
{"key": "chart.activity", "size": "m"},
{"key": "chart.activity", "size": "l"}, "junk"]}
assert layout.readable(stored) == {"v": 1, "widgets": [{"key": "chart.activity", "size": "m"}]}
assert layout.readable("junk") is None
# ── durations (Compass's arithmetic over event milestones) ─────────────────────
def test_runs_join_adjacent_stages():
assert trends._runs([0, 1]) == [(0, 1)]
assert trends._runs([1]) == [(1, 1)]
@pytest.mark.parametrize(("m", "segments", "want"), [
({"created": dt.date(2026, 1, 1), "approved": dt.date(2026, 1, 11)}, ["przygotowanie"], 10),
({"created": dt.date(2026, 1, 1), "approved": dt.date(2026, 1, 11),
"signed": dt.date(2026, 1, 14)}, ["przygotowanie", "podpisanie"], 13),
({"created": dt.date(2026, 1, 1)}, ["przygotowanie"], "missing"),
({"created": dt.date(2026, 1, 5), "approved": dt.date(2026, 1, 1)}, ["przygotowanie"], "order"),
({"approved": dt.date(2026, 1, 1), "signed": dt.date(2026, 1, 2)}, ["podpisanie"], 1),
])
def test_measure(m, segments, want):
assert trends.measure(m, segments) == want
class _FakeDb:
"""Answers the catalog probe only: enough to prove the statuses without a database."""
def __init__(self, present, readable):
self.row = SimpleNamespace(present=present, readable=readable)
def execute(self, *_):
return SimpleNamespace(one=lambda: self.row)
def test_no_event_log_is_a_status_not_an_error():
assert trends.activity(_FakeDb(False, False), days=7) == {
"status": "absent", "days": [], "kinds": [], "total": 0}
d = trends.durations(_FakeDb(True, False), ["przygotowanie"])
assert d["status"] == "no_grant" and d["measured"] == 0 and len(d["bands"]) == 4
def test_the_trends_never_name_a_document():
"""Aggregates only: nothing the durations or activity answer carries an id or a list of rows."""
d = trends.durations(_FakeDb(False, False), ["przygotowanie"])
assert set(d) == {"status", "segments", "measured", "median_days", "bands", "skipped"}
# ── who may see the trends ─────────────────────────────────────────────────────
def test_trends_are_moderators_only_by_default(monkeypatch):
from fastapi.testclient import TestClient
from app import deps
from app.db import get_db
from app.main import app
from app.routers import dashboard
person = SimpleNamespace(id="u", is_admin=False)
app.dependency_overrides[deps.get_current_user] = lambda: person
app.dependency_overrides[get_db] = lambda: _FakeDb(False, False)
seen = {}
def fake_current(*, token):
seen["token"] = token
return []
monkeypatch.setattr(dashboard.modules, "current", fake_current)
try:
client = TestClient(app)
monkeypatch.setattr(dashboard.moderation, "is_moderator", lambda db, user: False)
r = client.get("/api/v1/dashboard/activity")
assert r.status_code == 403 and r.json()["code"] == "trends_moderators_only"
r = client.get("/api/v1/dashboard", headers={"Authorization": "Bearer the-persons-token"})
assert r.json() == {"modules": [], "trends": False}
assert seen["token"] == "the-persons-token" # the person's own credential, nothing else
monkeypatch.setattr(dashboard.moderation, "is_moderator", lambda db, user: True)
assert client.get("/api/v1/dashboard/activity").json()["status"] == "absent"
finally:
app.dependency_overrides.clear()
def test_grouped_expressions_carry_no_bind_parameters():
"""A bound zone or JSON key is a new placeholder at every use, so the GROUP BY expression stops
being the select-list one and PostgreSQL refuses the query (found in the M4 platform run)."""
from sqlalchemy.dialects import postgresql
compiled = str(trends._day(trends._EVENT.c.created_at).compile(dialect=postgresql.dialect()))
assert "'Europe/Warsaw'" in compiled and "%(" not in compiled
+1 -1
View File
@@ -353,7 +353,7 @@ def test_every_column_that_names_a_person_is_found():
found = {(table, column) for table, column, _ in rev._person_columns()}
assert ("audit_log", "actor_id") in found
assert ("app_setting", "updated_by") in found
assert ("record", "created_by") in found # the app's own demo table
assert ("dashboard_layout", "user_id") in found # the app's own table
# The shared tables' own person-columns are the hub's, in the hub's schema, and were never local.
assert not any(table in {"app_user", "session", "module_permission"} for table, _ in found)
+43 -34
View File
@@ -5,9 +5,8 @@ setting a test changes is put back, so the suite can be re-run against the same
cannot be deleted, only deactivated, and nothing here depends on a clean slate.
This is the floor every app in the family inherits: authentication, the admin boundary, the closed
settings set, access control on the demo entity, bad input as 422 (never 500), the cross-site write
refusal, and the append-only audit log held by the database itself. Replace the demo-entity tests
with the real domain's; keep the rest.
settings set, the dashboard's layout and statuses, bad input as 422 (never 500), the cross-site write
refusal, and the append-only audit log held by the database itself.
"""
from __future__ import annotations
@@ -34,15 +33,6 @@ def root_id(admin_client):
return next(u["id"] for u in units if u["parent_id"] is None)
def _create_record(client, headers, name: str, parent_id: str | None) -> dict:
body = {"name": name, "note": "n"}
if parent_id:
body["parent_id"] = parent_id
r = client.post("/api/v1/records", json=body, headers=headers)
assert r.status_code == 201, r.text
return r.json()
# ── authentication ────────────────────────────────────────────────────────────
def test_health_is_public(client):
assert client.get("/api/v1/health").json()["status"] == "ok"
@@ -66,7 +56,7 @@ def test_anonymous_requests_are_refused():
anon = TestClient(app)
assert anon.get("/api/v1/auth/me").status_code == 401
assert anon.get("/api/v1/records").status_code == 401
assert anon.get("/api/v1/dashboard").status_code == 401
def test_the_admin_boundary(admin_client, make_user):
@@ -101,32 +91,51 @@ def test_settings_are_a_closed_typed_set(admin_client):
assert admin_client.get("/api/v1/config").json()["settings"]["instance_name"] != name
# ── the demo entity: access control and partial updates ───────────────────────
def test_records_are_private_to_those_allowed(admin_client, make_user, root_id):
owner, stranger = make_user("owner"), make_user("stranger")
if NODES:
# In the tree, a grant on the container is what lets someone write into it.
r = admin_client.put(f"/api/v1/nodes/{root_id}/grants",
json={"user_id": owner["id"], "role": "editor"})
assert r.status_code == 200, r.text
rec = _create_record(admin_client, bearer(owner["token"]), f"Private {RUN}", root_id)
# ── the dashboard: modules, trends, layout ──────────────────────────────────────
def test_the_dashboard_renders_with_every_module_absent(admin_client):
"""No <SLUG>_BASE_URL in the integration environment: every card is absent, nothing fails."""
d = admin_client.get("/api/v1/dashboard").json()
assert {m["status"] for m in d["modules"]} == {"absent"}
assert all(m["tiles"] == [] for m in d["modules"])
h_other = bearer(stranger["token"])
assert admin_client.get(f"/api/v1/records/{rec['id']}", headers=h_other).status_code == 404
assert rec["id"] not in {x["id"] for x in admin_client.get("/api/v1/records", headers=h_other).json()}
assert admin_client.patch(f"/api/v1/records/{rec['id']}", json={"note": "x"},
headers=h_other).status_code == 404
# `None` means "not supplied": a status-only update keeps the note.
r = admin_client.patch(f"/api/v1/records/{rec['id']}", json={"status": "done"},
headers=bearer(owner["token"]))
assert r.status_code == 200 and r.json()["note"] == "n" and r.json()["status"] == "done"
def test_trends_say_where_the_log_is(admin_client, make_user):
# Standalone there is no event log in this schema: a status, not an error.
r = admin_client.get("/api/v1/dashboard/activity?days=7")
assert r.status_code == 200 and r.json()["status"] in {"absent", "ok"}
r = admin_client.get("/api/v1/dashboard/durations?segment=przygotowanie")
assert r.status_code == 200 and r.json()["measured"] >= 0
bob = make_user("trendless")
assert admin_client.get("/api/v1/dashboard/activity",
headers=bearer(bob["token"])).status_code == 403
def test_a_layout_is_personal_and_the_firms_default_is_a_moderators(admin_client, make_user):
eve = make_user("layout")
h = bearer(eve["token"])
mine = {"v": 1, "widgets": [{"key": "chart.activity", "size": "m"}]}
r = admin_client.put("/api/v1/dashboard/layout/me", json=mine, headers=h)
assert r.status_code == 200 and r.json()["source"] == "user", r.text
assert r.json()["layout"] == mine
assert admin_client.put("/api/v1/dashboard/layout/me", headers=h, json={
"v": 1, "widgets": [{"key": "chart.nope", "size": "m"}]}).status_code == 422
assert admin_client.put("/api/v1/admin/dashboard/layout", json=mine,
headers=h).status_code == 403
firm = {"v": 1, "widgets": [{"key": "module.galena", "size": "l"}]}
try:
assert admin_client.put("/api/v1/admin/dashboard/layout", json=firm).status_code == 200
assert admin_client.put("/api/v1/admin/dashboard/layout", json=firm).status_code == 200
r = admin_client.delete("/api/v1/dashboard/layout/me", headers=h)
assert r.json()["source"] == "firm" and r.json()["layout"] == firm
finally:
admin_client.delete("/api/v1/admin/dashboard/layout")
assert admin_client.get("/api/v1/dashboard/layout", headers=h).json()["source"] == "builtin"
@pytest.mark.parametrize(("method", "path", "body"), [
("GET", "/api/v1/records/not-a-uuid", None),
("PATCH", f"/api/v1/records/{uuid.uuid4()}", {"status": "archived-forever"}),
("GET", "/api/v1/records?status=bogus", None),
("GET", "/api/v1/dashboard/durations?segment=bogus", None),
("GET", "/api/v1/dashboard/activity?days=0", None),
("PUT", "/api/v1/dashboard/layout/me", {"v": 2}),
])
def test_bad_input_is_422_never_500(admin_client, method, path, body):
r = admin_client.request(method, path, json=body)
+5 -3
View File
@@ -30,7 +30,7 @@ def test_core_tables_are_registered():
def test_the_apps_own_tables_are_registered():
"""A model missing from `app/models/__init__.py` silently gets no table."""
assert "record" in _metadata().tables
assert "dashboard_layout" in _metadata().tables
def test_every_model_enum_is_derived_for_the_migration():
@@ -46,8 +46,10 @@ def test_every_model_enum_is_derived_for_the_migration():
)
def test_the_apps_own_enum_is_derived():
assert "record_status" in enum_types(_metadata())
def test_the_event_log_is_never_on_this_metadata():
"""Panorama reads `module_event` (the hub's, on the platform) through a `table()` construct.
On the metadata, `0001` would build a local copy: the `event shadow` the platform check names."""
assert "module_event" not in _metadata().tables
def test_every_evidence_table_is_a_real_table():
+1 -2
View File
@@ -5,7 +5,7 @@ import pytest
from pydantic import ValidationError as PydanticValidationError
from app.config import Settings
from app.enums import RecordStatus, SessionKind, TokenScope
from app.enums import SessionKind, TokenScope
from app.schemas import LoginIn
from app.security import (
APP_TOKEN_PREFIX,
@@ -87,7 +87,6 @@ class TestSlugify:
class TestEnums:
def test_values_are_the_db_labels(self):
assert RecordStatus.open.value == "open"
assert SessionKind.app_token.value == "app_token"
assert TokenScope.read.value == "read"
+12 -10
View File
@@ -90,19 +90,21 @@ avoids.
```bash
python -m dredd_core.managed provision --sql-only --schema panorama --app-role panorama_app \
--migrator-role panorama_migrator --output db/managed/provision.sql
--migrator-role panorama_migrator --identity-schema dredd --identity-owner atrium_migrator \
--output db/managed/provision.sql
```
The committed file is the **standalone** rendering, which is what a generated app needs on day one.
Joining a platform adds two flags to that command, and therefore changes the file — which is exactly
why CI compares it. See section 6.
The committed file is the **platform** rendering: Panorama is split out of Compass to run as a
module of Atrium (its numbers need the platform's one account), so it ships with the identity flags,
exactly as Galena, Sygna, Counsel, Lexicon and Agora do, and CI's `--check-file` step passes the same
two flags. A standalone deployment renders without `--identity-schema` / `--identity-owner` (and
must then not use the committed file). See section 6.
**Joining Atrium (the platform) means re-rendering with the identity flags**, exactly as Galena,
Sygna and Counsel ship theirs, and adding the same two flags to CI's `--check-file` step:
```bash
python -m dredd_core.managed provision --sql-only --schema panorama --app-role panorama_app --migrator-role panorama_migrator --identity-schema dredd --identity-owner atrium_migrator --output db/managed/provision.sql
```
**The event log's reader tier.** Panorama's trends read the shared `module_event`. That grant is the
hub's, not provisioning's: Atrium's event-grant revision names `panorama_app` in `reader_roles`
(`dredd_core.events.event_grants_sql`, dredd-core 0.23.0: `SELECT` and nothing else), and
`python -m dredd_core.managed check ... --identity-schema dredd --events-reader` proves it from this
side. Without it the trend charts say the log is not readable; nothing else changes.
(plus every `--extension` this app's `0001` needs). The platform's `deploy/push.sh` checks it: before
it provisions anything, it re-renders each module's `provision.sql` from that module's checkout with
+46 -15
View File
@@ -1,16 +1,16 @@
-- =================================================================================================
-- Managed Postgres provisioning for one app of the family, in the shared database:
-- schema panorama, migrator panorama_migrator, app panorama_app, extensions: none, migrator statement_timeout 30min
-- search_path panorama, extensions; no shared identity schema (this app owns its own accounts)
-- search_path panorama, dredd, extensions; shared identity schema dredd, owned by atrium_migrator (created by its owner, USAGE only here)
--
-- Rendered by dredd-core. Do not edit: re-render, and let CI check it is current (exit 1 = stale):
-- python -m dredd_core.managed provision --sql-only \
-- --schema panorama --app-role panorama_app --migrator-role panorama_migrator \
-- --schema panorama --app-role panorama_app --migrator-role panorama_migrator --identity-schema dredd --identity-owner atrium_migrator \
-- --output db/managed/provision.sql (CI: --check-file db/managed/provision.sql)
--
-- Preferred path, from a shell (passwords come from environment variables and are never printed):
-- python -m dredd_core.managed provision --admin-url ADMIN_DATABASE_URL \
-- --schema panorama --app-role panorama_app --migrator-role panorama_migrator \
-- --schema panorama --app-role panorama_app --migrator-role panorama_migrator --identity-schema dredd --identity-owner atrium_migrator \
-- --migrator-password-env PANORAMA_MIGRATOR_PASSWORD --app-password-env PANORAMA_APP_PASSWORD
--
-- SQL editor path (no shell): paste this whole file into the provider's SQL editor, replace both
@@ -30,8 +30,8 @@ DECLARE
app_role text := 'panorama_app';
admin_roles text[] := ARRAY['postgres', 'postgres_managed']::text[];
extension_names text[] := '{}'::text[];
identity_schema text := '';
identity_owner text := '';
identity_schema text := 'dredd';
identity_owner text := 'atrium_migrator';
owns_identity boolean := false;
seen text;
r text;
@@ -200,19 +200,50 @@ BEGIN
END
$dredd_provision_extensions_usage$;
-- 9. search_path of panorama_migrator
ALTER ROLE panorama_migrator SET search_path = panorama, extensions;
-- 9. temporary membership in the identity owner atrium_migrator: needed to grant on dredd
GRANT atrium_migrator TO CURRENT_USER;
-- 10. search_path of panorama_app
ALTER ROLE panorama_app SET search_path = panorama, extensions;
-- 10. schema dredd: USAGE for panorama_migrator and panorama_app
GRANT USAGE ON SCHEMA dredd TO panorama_migrator, panorama_app;
-- 11. statement_timeout of panorama_migrator
-- 11. schema dredd: check that the USAGE grant took
DO $dredd_provision_identity_usage$
DECLARE
identity_schema text := 'dredd';
migrator_role text := 'panorama_migrator';
app_role text := 'panorama_app';
identity_owner text := 'atrium_migrator';
BEGIN
IF NOT (has_schema_privilege(migrator_role, identity_schema, 'USAGE')
AND has_schema_privilege(app_role, identity_schema, 'USAGE')) THEN
RAISE EXCEPTION USING
MESSAGE = 'provision: could not grant USAGE on the shared identity schema '
|| quote_ident(identity_schema) || ' to ' || quote_ident(migrator_role) || ' and '
|| quote_ident(app_role),
HINT = 'The connected role holds no grant option there (PostgreSQL then only warns "no '
|| 'privileges were granted"), because the schema belongs to ' || quote_ident(identity_owner)
|| '. The temporary membership in that role is what carries the grant option: check '
|| '--identity-owner names the role that really owns the schema.';
END IF;
END
$dredd_provision_identity_usage$;
-- 12. search_path of panorama_migrator
ALTER ROLE panorama_migrator SET search_path = panorama, dredd, extensions;
-- 13. search_path of panorama_app
ALTER ROLE panorama_app SET search_path = panorama, dredd, extensions;
-- 14. statement_timeout of panorama_migrator
ALTER ROLE panorama_migrator SET statement_timeout = '30min';
-- 12. end the temporary membership: no standing SET ROLE panorama_migrator for the admin
-- 15. end the temporary membership: no standing SET ROLE panorama_migrator for the admin
REVOKE panorama_migrator FROM CURRENT_USER;
-- 13. verify the end state
-- 16. end the temporary membership in atrium_migrator
REVOKE atrium_migrator FROM CURRENT_USER;
-- 17. verify the end state
DO $dredd_provision_verify$
DECLARE
target_schema text := 'panorama';
@@ -220,9 +251,9 @@ DECLARE
app_role text := 'panorama_app';
extension_names text[] := '{}'::text[];
timeout_setting text := 'statement_timeout=30min';
path_setting text := 'search_path=panorama, extensions';
identity_schema text := '';
identity_owner text := '';
path_setting text := 'search_path=panorama, dredd, extensions';
identity_schema text := 'dredd';
identity_owner text := 'atrium_migrator';
admin_roles text[] := ARRAY['postgres', 'postgres_managed']::text[];
admin_is_super boolean := (SELECT rolsuper FROM pg_roles WHERE rolname = current_user);
problems text[] := '{}'::text[];
+70
View File
@@ -36,6 +36,10 @@
--warn-bg: #fdf3e0;
--err: #b02525;
--err-bg: #fdeceb;
/* Data-viz only (the family's one exception to monochrome chrome): Open Color violet/teal/orange. */
--chart-1: #7048e8;
--chart-2: #0ca678;
--chart-3: #f08c00;
--radius: 8px;
--radius-sm: 6px;
@@ -70,6 +74,9 @@
--warn-bg: #2a2115;
--err: #f08a80;
--err-bg: #2c1a18;
--chart-1: #9775fa;
--chart-2: #38d9a9;
--chart-3: #ffa94d;
--shadow: 0 1px 2px rgba(0, 0, 0, .4), 0 4px 14px rgba(0, 0, 0, .3);
}
}
@@ -97,6 +104,9 @@
--warn-bg: #2a2115;
--err: #f08a80;
--err-bg: #2c1a18;
--chart-1: #9775fa;
--chart-2: #38d9a9;
--chart-3: #ffa94d;
--shadow: 0 1px 2px rgba(0, 0, 0, .4), 0 4px 14px rgba(0, 0, 0, .3);
}
@@ -510,3 +520,63 @@ td.mono { font-family: var(--mono); font-size: 12.5px; }
table.rt td.acts-cell { justify-content: flex-end; padding-top: 8px; }
table.rt td:not(:first-child) .row { justify-content: flex-end; }
}
/* ── dashboard (ported from Compass: the grid, the edit bar, the bars) ───────── */
.dash { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 12px; }
.dash .w { position: relative; min-width: 0; display: flex; flex-direction: column; }
.dash .size-s { grid-column: span 1; }
.dash .size-m { grid-column: span 3; }
.dash .size-l { grid-column: span 6; }
.dash .wbody { flex: 1; display: flex; flex-direction: column; min-width: 0; }
.dash .wbody > .tile, .dash .wbody > .card { flex: 1; margin: 0; }
@media (max-width: 1100px) {
.dash { grid-template-columns: repeat(4, minmax(0, 1fr)); }
.dash .size-m { grid-column: span 2; }
.dash .size-l { grid-column: span 4; }
}
@media (max-width: 700px) {
.dash { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.dash .size-m, .dash .size-l { grid-column: span 2; }
}
.dash .w.editing { outline: 1px dashed var(--border-input); outline-offset: 3px; border-radius: var(--radius-sm); cursor: grab; padding-top: 34px; }
.dash .w.editing .wbody { pointer-events: none; }
.wbar { position: absolute; top: 0; right: 0; z-index: 2; display: flex; gap: 2px; padding: 2px;
background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-sm); }
.wbar button { width: 24px; height: 24px; display: inline-flex; align-items: center; justify-content: center;
border: 0; background: none; color: var(--text-muted); border-radius: 4px; cursor: pointer; font: inherit; }
.wbar button:hover { background: var(--surface-hover); color: var(--text); }
.wbar button:disabled { opacity: .35; cursor: default; }
.wbar button.x:hover { background: var(--err-bg); color: var(--err); }
.dashtools { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; margin: 0 0 14px; }
/* A module's card: its tiles link into the module, at the list each one counts. */
.modcard h3 a { color: inherit; text-decoration: none; }
.modcard h3 a:hover { text-decoration: underline; }
.modcard.off { opacity: .8; }
.modcard .tiles { margin-top: 8px; }
a.tile { color: inherit; text-decoration: none; display: block; }
a.tile:hover { border-color: var(--text-muted); }
.legend, .bars { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; font-size: 13.5px; }
.bars.static li { display: flex; align-items: center; gap: 8px; }
.bars .name { flex: 0 0 40%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.bars .bar { flex: 1; height: 8px; background: var(--surface-hover); border-radius: 4px; overflow: hidden; }
.bars .bar > span { display: block; height: 100%; background: var(--text-muted); }
.stages { display: flex; gap: 14px; flex-wrap: wrap; margin-bottom: 6px; font-size: 13.5px; }
.durations { margin-top: 12px; }
.durations .tiles { margin-bottom: 12px; }
/* „Aktywność”: a stacked column per day, the three most frequent kinds in the chart colours. */
.stack .plot, .stack .labels { display: grid; grid-template-columns: repeat(var(--n), 1fr); gap: 2px; }
.stack .plot { height: 150px; border-bottom: 1px solid var(--border); align-items: end; }
.stack .col { display: flex; flex-direction: column-reverse; height: 100%; justify-content: flex-start; }
.stack .seg { display: block; width: 100%; min-height: 1px; }
.stack .labels { margin: 4px 0 8px; font-size: 11px; color: var(--text-faint); }
.stack .labels span { overflow: visible; white-space: nowrap; }
.s0 { background: var(--chart-1); }
.s1 { background: var(--chart-2); }
.s2 { background: var(--chart-3); }
.s3 { background: var(--text-faint); }
.chartkey { display: flex; flex-wrap: wrap; gap: 6px 16px; margin: 4px 0 8px; }
.chartkey li { display: flex; align-items: center; gap: 6px; }
.chartkey .sw { width: 10px; height: 10px; border-radius: 2px; display: inline-block; }
+338 -152
View File
@@ -20,7 +20,7 @@
depend on the trailing slash — bare `/panorama` would resolve to `/api/v1` — which is why a
platform proxy must redirect `/panorama` to `/panorama/`. */
const API = new URL('api/v1', document.baseURI).pathname;
/* 'nodes' = records live in a permission tree; 'simple' = flat, owner-based. */
/* 'nodes' = a permission tree; 'simple' = flat, owner-based (Panorama). */
const TENANCY = 'simple';
const $ = (id) => document.getElementById(id);
@@ -198,11 +198,9 @@ const I18N = {
'Język: polski': 'Language: Polish',
'Język: angielski': 'Language: English',
'Pulpit': 'Dashboard',
'Rekordy': 'Records',
'Administracja': 'Administration',
'Użytkownicy': 'Users',
'Przestrzenie': 'Workspaces',
'Nowy rekord': 'New record',
'Nazwa': 'Name',
'Notatka': 'Note',
'Utworzono': 'Created',
@@ -212,11 +210,63 @@ const I18N = {
'Edytuj': 'Edit',
'Wczytywanie…': 'Loading…',
'Brak wyników': 'Nothing found',
'Brak rekordów.': 'No records yet.',
'Nie znaleziono strony.': 'Page not found.',
'otwarty': 'open',
'zamknięty': 'done',
'Wszystkich': 'Total',
'Dokumenty': 'Documents',
'Obieg': 'Workflow',
'Analizy': 'Analyses',
'Biblioteka klauzul': 'Clause library',
'Negocjacje': 'Negotiations',
'Sprawy': 'Matters',
'Ocena pracy': 'Work review',
'Akty prawne': 'Legal acts',
'Nie działa w tej instalacji': 'Not deployed here',
'Brak dostępu do tego modułu': 'You have no access to this module',
'Moduł chwilowo nie odpowiada': 'The module is not answering right now',
'Ten moduł nie podaje jeszcze liczb.': 'This module does not report numbers yet.',
'Trendy widzą moderatorzy tego modułu.': "This module's moderators see the trends.",
'Aktywność na platformie': 'Platform activity',
'Czas trwania': 'Duration',
'Dostosuj pulpit': 'Customise dashboard',
'Gotowe': 'Done',
'Dodaj element': 'Add an element',
'Dodaj element…': 'Add an element…',
'Przywróć domyślny': 'Restore the default',
'Ustaw jako domyślny dla firmy': "Make it the firm's default",
'Przeciągnij element albo użyj strzałek, żeby zmienić kolejność.': 'Drag an element or use the arrows to change the order.',
'Pulpit jest pusty. Kliknij „Dostosuj pulpit”, żeby dodać elementy.': 'The dashboard is empty. Click “Customise dashboard” to add elements.',
'Twój układ': 'Your layout',
'Układ domyślny firmy': "The firm's default layout",
'Układ wbudowany': 'The built-in layout',
'Wcześniej': 'Earlier',
'Później': 'Later',
'Zmień rozmiar': 'Change size',
'Usuń z pulpitu': 'Remove from the dashboard',
'Mały': 'Small',
'Połowa wiersza': 'Half a row',
'Cały wiersz': 'Whole row',
'Ta instalacja nie ma dziennika zdarzeń (Panorama działa samodzielnie).': 'This installation has no event log (Panorama runs standalone).',
'Platforma nie dała jeszcze Panoramie wglądu w dziennik zdarzeń.': 'The platform has not given Panorama read access to the event log yet.',
'Brak zdarzeń w ostatnich 30 dniach.': 'No events in the last 30 days.',
'Inne': 'Other',
'Suma zdarzeń całej platformy; bez nazw i treści dokumentów.': 'Totals across the platform; no document names or content.',
'Nowe wersje dokumentów': 'New document versions',
'Zatwierdzone obiegi': 'Approved workflows',
'Podpisane dokumenty': 'Signed documents',
'Rundy negocjacji': 'Negotiation rounds',
'Zaakceptowane analizy': 'Accepted analyses',
'Od pierwszej wersji do zatwierdzenia': 'From the first version to approval',
'Od zatwierdzenia do podpisu': 'From approval to signature',
'Zaznacz co najmniej jeden etap.': 'Tick at least one stage.',
'ponad': 'over',
'najwyżej': 'at most',
'dni': 'days',
'Poza pomiarem:': 'Not measured:',
'bez zdarzeń wybranych etapów,': 'without events for the chosen stages,',
'ze zdarzeniami w złej kolejności.': 'with events out of order.',
'Żaden dokument nie ma jeszcze zdarzeń wybranych etapów.': 'No document has events for the chosen stages yet.',
'Mediana, dni': 'Median, days',
'Zmierzone dokumenty': 'Documents measured',
'Kafelki': 'Tiles',
'Zapisano.': 'Saved.',
'Tej operacji nie da się cofnąć.': 'This cannot be undone.',
};
@@ -372,7 +422,6 @@ const isModerator = () => !!(state.user && state.user.is_moderator);
/* ── navigation ─────────────────────────────────────────────────────────── */
const NAV = [
{ hash: '#/', icon: 'dashboard', label: 'Pulpit' },
{ hash: '#/records', icon: 'file', label: 'Rekordy' },
];
function renderNav(counts) {
@@ -426,8 +475,6 @@ async function router() {
C.innerHTML = '<div class="faint">Wczytywanie…</div>';
try {
if (!seg.length) await viewDashboard(C);
else if (seg[0] === 'records' && seg[1]) await viewRecord(C, seg[1]);
else if (seg[0] === 'records') await viewRecords(C, q);
else if (seg[0] === 'admin') await viewAdmin(C);
else C.innerHTML = '<div class="empty">Nie znaleziono strony.</div>';
} catch (ex) {
@@ -440,159 +487,296 @@ async function router() {
}
/* ── dashboard ──────────────────────────────────────────────────────────── */
/* One card per module of the platform, each holding the tiles that module answered with (dredd-core's
stats contract): a tile counts only what THIS person may see there and equals the list its link
opens, because the module counted it with the person's own session. Panorama adds nothing up and
re-checks nothing. A module that is not deployed, down, slow or closed to this person is a status
on its card; the rest of the dashboard renders. The two charts are aggregates over the platform's
event log. Ported from Compass's dashboard (spec 2026-10-13 D1-D5, wykresy W5-W7, pulpit-uklad
U1-U6): every element can be moved, resized, removed and added back. */
const dash = { C: null, data: null, layout: null, activity: null, durations: null, edit: false,
drag: null, timer: null, saving: null };
const DASH_SAVE_MS = 400;
const MODULE_STATUS = {
absent: 'Nie działa w tej instalacji',
no_access: 'Brak dostępu do tego modułu',
unavailable: 'Moduł chwilowo nie odpowiada',
};
const CHART_LABEL = { 'chart.activity': 'Aktywność na platformie', 'chart.durations': 'Czas trwania' };
const SIZE_LABEL = { s: 'Mały', m: 'Połowa wiersza', l: 'Cały wiersz' };
const LAYOUT_SOURCE = { user: 'Twój układ', firm: 'Układ domyślny firmy', builtin: 'Układ wbudowany' };
function moduleOf(key) {
return ((dash.data && dash.data.modules) || []).find((m) => 'module.' + m.module === key);
}
/* An element's name in the „Dodaj element” list. A module's name is translated as a phrase. */
function widgetLabel(key) {
const m = moduleOf(key);
return m ? m.name : (CHART_LABEL[key] || key);
}
async function viewDashboard(C) {
const d = await api('GET', '/dashboard');
const c = d.cards || {};
state.counts = { records: c.total };
// The tiles and the layout first; each chart loads into its own card and fails there alone.
const [d, layout] = await Promise.all([api('GET', '/dashboard'), api('GET', '/dashboard/layout')]);
setCrumb([{ label: 'Pulpit' }]);
const tiles = [
{ k: 'Wszystkich', v: c.total ?? 0, cls: '' },
{ k: 'otwarty', v: c.open ?? 0, cls: '' },
{ k: 'zamknięty', v: c.done ?? 0, cls: '' },
];
C.innerHTML = pageHead('Pulpit', state.user.full_name || state.user.email,
`<button class="btn primary" onclick="openRecordNew()">${svg(ICN.plus)}Nowy rekord</button>`)
+ `<div class="tiles">${tiles.map((t) => `<div class="tile ${t.cls}"><div class="k">${esc(t.k)}</div><div class="v">${esc(String(t.v))}</div></div>`).join('')}</div>`
+ `<div class="card" style="margin-top:14px"><h3>Rekordy<span class="n">${(d.recent || []).length}</span></h3>${recordTable(d.recent || [])}</div>`;
Object.assign(dash, { C, data: d, layout, edit: false, drag: null, activity: null, durations: null });
state.counts = {};
drawDashboard();
if (d.trends) loadCharts();
}
function statusChip(s) {
const cls = s === 'done' ? 'ok' : '';
const label = s === 'done' ? 'zamknięty' : 'otwarty';
return `<span class="chip ${cls}">${esc(label)}</span>`;
async function loadCharts() {
const [activity, durations] = await Promise.all([
api('GET', '/dashboard/activity?days=30').catch((ex) => ({ error: ex.message })),
api('GET', durationsPath(STAGES.map(([key]) => key))).catch((ex) => ({ error: ex.message }))]);
Object.assign(dash, { activity, durations });
if (!dash.edit) drawDashboard();
}
function recordTable(rows) {
if (!rows.length) return '<div class="empty">Brak rekordów.</div>';
return `<div class="tablewrap"><table class="rt"><thead><tr>
<th>Nazwa</th><th>Status</th><th>Utworzono</th>
</tr></thead><tbody>${rows.map((r) => `<tr class="click" onclick="location.hash='#/records/${encodeURIComponent(r.id)}'">
<td><div>${esc(r.name)}${r.note ? `<div class="faint tiny">${esc(r.note)}</div>` : ''}</div></td>
<td${lbl('Status')}>${statusChip(r.status)}</td>
<td class="faint tiny"${lbl('Utworzono')}>${fmtDate(r.created_at)}</td>
</tr>`).join('')}</tbody></table></div>`;
function moduleCard(m) {
const head = m.url
? `<a href="${esc(m.url)}" data-no-i18n>${esc(_tr(m.name))}</a>`
: `<span data-no-i18n>${esc(_tr(m.name))}</span>`;
if (m.status !== 'ok') {
return `<div class="card modcard off"><h3>${head}</h3><div class="faint tiny">${esc(MODULE_STATUS[m.status] || m.status)}</div></div>`;
}
const tiles = m.tiles.length
? `<div class="tiles">${m.tiles.map((t) => `<a class="tile" href="${esc(t.href)}"><div class="k" data-no-i18n>${esc(t.label)}</div><div class="v" data-no-i18n>${esc(Number(t.count).toLocaleString(LOCALE))}</div></a>`).join('')}</div>`
: '<div class="empty">Ten moduł nie podaje jeszcze liczb.</div>';
return `<div class="card modcard"><h3>${head}</h3>${tiles}</div>`;
}
/* ── records ────────────────────────────────────────────────────────────── */
async function viewRecords(C, q) {
const params = new URLSearchParams();
if (q.q) params.set('q', q.q);
if (q.status) params.set('status', q.status);
const rows = await api('GET', '/records' + (params.toString() ? '?' + params : ''));
setCrumb([{ label: 'Rekordy' }]);
function widgetBody(key) {
if (key.startsWith('module.')) {
const m = moduleOf(key);
return m ? moduleCard(m) : '';
}
if (!dash.data.trends) {
return `<div class="card"><h3>${esc(CHART_LABEL[key] || key)}</h3><div class="faint tiny">Trendy widzą moderatorzy tego modułu.</div></div>`;
}
if (key === 'chart.activity') return `<div class="card"><h3>Aktywność na platformie</h3>${activityBody(dash.activity)}</div>`;
if (key === 'chart.durations') return durationsCard(dash.durations);
return '';
}
C.innerHTML = pageHead('Rekordy', rows.length + '',
`<button class="btn primary" onclick="openRecordNew()">${svg(ICN.plus)}Nowy rekord</button>`)
+ `<div class="toolbar">
<input type="search" id="rq" placeholder="Szukaj…" value="${esc(q.q || '')}" />
<select id="rstatus">
${['', 'open', 'done'].map((s) => `<option value="${s}" ${q.status === s ? 'selected' : ''}>${s ? (s === 'done' ? 'zamknięty' : 'otwarty') : '—'}</option>`).join('')}
</select>
</div>`
+ (rows.length ? `<div class="card">${recordTable(rows)}</div>` : '<div class="empty">Brak rekordów.</div>');
/* One element in the grid; in edit mode with its bar: move, resize, remove (U5). */
function widget(w, i, all) {
const k = `data-key="${esc(w.key)}"`;
const sizes = (dash.layout.widgets.find((x) => x.key === w.key) || {}).sizes || [w.size];
const size = `${_tr('Zmień rozmiar')}: ${_tr(SIZE_LABEL[w.size])}`;
const bar = dash.edit ? `<div class="wbar">
<button type="button" ${k} title="Wcześniej" aria-label="${esc(_tr('Wcześniej'))}"${i === 0 ? ' disabled' : ''} onclick="moveWidget(this.dataset.key, -1)">←</button>
<button type="button" ${k} title="Później" aria-label="${esc(_tr('Później'))}"${i === all.length - 1 ? ' disabled' : ''} onclick="moveWidget(this.dataset.key, 1)">→</button>
${sizes.length > 1 ? `<button type="button" ${k} title="Zmień rozmiar" aria-label="${esc(size)}" onclick="resizeWidget(this.dataset.key)"><span data-no-i18n>${esc(w.size.toUpperCase())}</span></button>` : ''}
<button type="button" class="x" ${k} title="Usuń z pulpitu" aria-label="${esc(_tr('Usuń z pulpitu'))}" onclick="removeWidget(this.dataset.key)">×</button>
</div>` : '';
// Firefox starts no drag without data set.
const drag = dash.edit ? ` draggable="true" ondragstart="event.dataTransfer.setData('text/plain', this.dataset.key); dash.drag = this.dataset.key" ondragover="event.preventDefault()" ondrop="event.preventDefault(); dropWidget(this.dataset.key)"` : '';
return `<div class="w size-${esc(w.size)}${dash.edit ? ' editing' : ''}" ${k}${drag}>${bar}<div class="wbody">${widgetBody(w.key)}</div></div>`;
}
const go = () => {
const p = new URLSearchParams();
if ($('rq').value.trim()) p.set('q', $('rq').value.trim());
if ($('rstatus').value) p.set('status', $('rstatus').value);
location.hash = '#/records' + (p.toString() ? '?' + p : '');
function drawDashboard() {
const C = dash.C;
if (!C) return;
// An absent module's card is shown only while editing: a dashboard full of „not deployed” says
// nothing. Unavailable and no-access cards stay, because something there is expected and missing.
const shown = dash.layout.layout.widgets.filter((w) => {
const m = moduleOf(w.key);
return dash.edit || !m || m.status !== 'absent';
});
const on = new Set(dash.layout.layout.widgets.map((w) => w.key));
const hidden = dash.layout.widgets.filter((w) => !on.has(w.key));
const actions = dash.edit
? '<button type="button" class="btn primary" onclick="editDashboard(false)">Gotowe</button>'
: '<button type="button" class="btn" onclick="editDashboard(true)">Dostosuj pulpit</button>';
const add = hidden.length ? `<select aria-label="${esc(_tr('Dodaj element'))}" onchange="addWidget(this.value)">
<option value="" data-no-i18n>${esc(_tr('Dodaj element…'))}</option>
${hidden.map((w) => `<option value="${esc(w.key)}" data-no-i18n>${esc(_tr(widgetLabel(w.key)))}</option>`).join('')}
</select>` : '';
const tools = dash.edit ? `<div class="card dashtools">
<span class="faint tiny">${esc(LAYOUT_SOURCE[dash.layout.source] || '')}</span>
${add}
${dash.layout.source === 'user' ? '<button type="button" class="btn" onclick="restoreLayout()">Przywróć domyślny</button>' : ''}
${isModerator() ? '<button type="button" class="btn" onclick="setFirmLayout()">Ustaw jako domyślny dla firmy</button>' : ''}
<span class="tiny faint">Przeciągnij element albo użyj strzałek, żeby zmienić kolejność.</span>
</div>` : '';
const grid = shown.length ? `<div class="dash">${shown.map(widget).join('')}</div>`
: '<div class="empty">Pulpit jest pusty. Kliknij „Dostosuj pulpit”, żeby dodać elementy.</div>';
C.innerHTML = pageHead('Pulpit', state.user.full_name || state.user.email, actions) + tools + grid;
localize(C);
}
function editDashboard(on) {
dash.edit = on;
drawDashboard();
}
/* Every change is drawn at once and saved a moment later: a run of clicks is one request. A 422
means the layout went stale (an element gone): the server's is read back. */
function layoutChanged() {
clearTimeout(dash.timer);
dash.timer = setTimeout(() => { dash.saving = (dash.saving || Promise.resolve()).then(() => guard(async () => {
let reply;
try {
reply = await api('PUT', '/dashboard/layout/me', dash.layout.layout);
} catch (ex) {
if (ex && ex.status === 422) {
dash.layout = await api('GET', '/dashboard/layout');
if (dash.edit) drawDashboard();
}
throw ex;
}
Object.assign(dash.layout, { source: reply.source, firm_default: reply.firm_default });
if (dash.edit) drawDashboard();
})); }, DASH_SAVE_MS);
drawDashboard();
}
function moveWidget(key, by) {
const ws = dash.layout.layout.widgets;
const i = ws.findIndex((w) => w.key === key);
const j = i + by;
if (i < 0 || j < 0 || j >= ws.length) return;
[ws[i], ws[j]] = [ws[j], ws[i]];
layoutChanged();
}
/* An element dropped onto another takes its place. */
function dropWidget(target) {
const ws = dash.layout.layout.widgets;
const from = ws.findIndex((w) => w.key === dash.drag);
const to = ws.findIndex((w) => w.key === target);
dash.drag = null;
if (from < 0 || to < 0 || from === to) return;
ws.splice(to, 0, ws.splice(from, 1)[0]);
layoutChanged();
}
/* The next size the element takes, round again after the last. */
function resizeWidget(key) {
const w = dash.layout.layout.widgets.find((x) => x.key === key);
const sizes = (dash.layout.widgets.find((x) => x.key === key) || {}).sizes || [];
if (!w || sizes.length < 2) return;
w.size = sizes[(sizes.indexOf(w.size) + 1) % sizes.length];
layoutChanged();
}
function removeWidget(key) {
dash.layout.layout.widgets = dash.layout.layout.widgets.filter((w) => w.key !== key);
layoutChanged();
}
/* A hidden element comes back at the end, in its default size. */
function addWidget(key) {
const kind = dash.layout.widgets.find((w) => w.key === key);
if (!kind || dash.layout.layout.widgets.some((w) => w.key === key)) return;
dash.layout.layout.widgets.push({ key, size: kind.sizes[0] });
layoutChanged();
}
/* Deletes the person's own layout: the firm's default, else the built-in one, takes over. */
function restoreLayout() {
clearTimeout(dash.timer);
guard(async () => {
await dash.saving;
dash.layout = await api('DELETE', '/dashboard/layout/me');
drawDashboard();
});
}
function setFirmLayout() {
guard(async () => {
const reply = await api('PUT', '/admin/dashboard/layout', dash.layout.layout);
dash.layout.firm_default = reply.firm_default;
toast('Zapisano.');
});
}
/* ── charts (aggregates over the event log) ─────────────────────────────── */
const LOG_STATUS = {
absent: 'Ta instalacja nie ma dziennika zdarzeń (Panorama działa samodzielnie).',
no_grant: 'Platforma nie dała jeszcze Panoramie wglądu w dziennik zdarzeń.',
};
/* „Aktywność na platformie”: events per day, the three most frequent kinds as the three chart
colours (the family's data-viz exception to the monochrome UI), the rest grey. */
function activityBody(a) {
if (!a) return '<div class="faint tiny">Wczytywanie…</div>';
if (a.error) return `<div class="banner err">${esc(a.error)}</div>`;
if (a.status !== 'ok') return `<div class="empty">${esc(LOG_STATUS[a.status] || a.status)}</div>`;
if (!a.total) return '<div class="empty">Brak zdarzeń w ostatnich 30 dniach.</div>';
const top = a.kinds.slice(0, 3).map((k) => k.kind);
const series = (day) => {
const c = day.counts || {};
const parts = top.map((k) => c[k] || 0);
const rest = Object.entries(c).filter(([k]) => !top.includes(k)).reduce((s, [, n]) => s + n, 0);
return [...parts, rest];
};
$('rq').addEventListener('change', go);
$('rstatus').addEventListener('change', go);
const totals = a.days.map((d) => series(d).reduce((x, y) => x + y, 0));
const max = Math.max(1, ...totals);
const cols = a.days.map((d, i) => {
const s = series(d);
const segs = s.map((n, j) => (n ? `<span class="seg s${j}" style="height:${(n / max) * 100}%"></span>` : '')).join('');
return `<span class="col" title="${esc(`${d.date}: ${totals[i]}`)}" aria-label="${esc(`${d.date}: ${totals[i]}`)}">${segs}</span>`;
}).join('');
const labels = a.days.map((d, i) => `<span data-no-i18n>${i % 5 === 0 ? esc(d.date.slice(8, 10) + '.' + d.date.slice(5, 7)) : ''}</span>`).join('');
const legend = a.kinds.slice(0, 3).map((k, j) => `<li><span class="sw s${j}"></span><span>${esc(_tr(k.label))}</span> <span class="faint" data-no-i18n>${esc(String(k.total))}</span></li>`).join('')
+ (a.kinds.length > 3 ? `<li><span class="sw s3"></span><span>Inne</span> <span class="faint" data-no-i18n>${esc(String(a.kinds.slice(3).reduce((x, k) => x + k.total, 0)))}</span></li>` : '');
return `<div class="stack"><div class="plot" style="--n:${a.days.length}">${cols}</div><div class="labels" style="--n:${a.days.length}">${labels}</div></div><ul class="legend chartkey">${legend}</ul>
<div class="tiny faint">Suma zdarzeń całej platformy; bez nazw i treści dokumentów.</div>`;
}
async function viewRecord(C, id) {
const r = await api('GET', '/records/' + encodeURIComponent(id));
setCrumb([{ label: 'Rekordy', href: '#/records' }, { label: r.name }]);
/* „Czas trwania” (Compass W3-W7, on events): the person ticks stages, the server joins them. */
const STAGES = [['przygotowanie', 'Od pierwszej wersji do zatwierdzenia'], ['podpisanie', 'Od zatwierdzenia do podpisu']];
const canDelete = TENANCY !== 'nodes' || r.role === 'manager';
C.innerHTML = pageHead(r.name, r.path || '',
`<button class="btn" onclick="openRecordEdit('${esc(r.id)}')">${svg(ICN.check)}Edytuj</button>`
+ (canDelete ? `<button class="btn danger" onclick="deleteRecord('${esc(r.id)}')">${svg(ICN.trash)}Usuń</button>` : ''))
+ `<div class="card"><div class="grid3">
${field('Status', r.status === 'done' ? 'zamknięty' : 'otwarty')}
${field('Utworzono', fmtDateTime(r.created_at))}
</div>
${r.note ? `<div style="margin-top:14px"><div class="tiny faint">Notatka</div><div>${esc(r.note)}</div></div>` : ''}
</div>`;
function durationsPath(chosen) {
return '/dashboard/durations?' + chosen.map((s) => 'segment=' + encodeURIComponent(s)).join('&');
}
function containerOptions(selected) {
return state.containers.map((n) =>
`<option value="${esc(n.id)}" ${n.id === selected ? 'selected' : ''}>${esc(n.path)}</option>`).join('');
function durationsCard(d) {
const boxes = STAGES.map(([key, label]) => `<label><input type="checkbox" data-stage="${key}" checked onchange="loadDurations()" /> ${label}</label>`).join('');
return `<div class="card" id="durations"><h3>Czas trwania</h3>
<div class="row stages">${boxes}</div>
<div class="out">${durationsBody(d)}</div></div>`;
}
function openRecordNew() {
const where = TENANCY === 'nodes'
? `<label class="field" style="margin-top:12px">Przestrzenie
<select id="rcParent">${containerOptions()}</select></label>`
: '';
modal('Nowy rekord', '',
`<label class="field">Nazwa<input id="rcName" /></label>
<label class="field" style="margin-top:12px">Notatka<textarea id="rcNote"></textarea></label>
${where}`,
`<button class="btn" onclick="closeModal()">Anuluj</button>
<button class="btn primary" onclick="saveRecordNew()">Zapisz</button>`);
/* Only the last tick's answer is drawn: an earlier, slower one must not land after it. */
let durationsTick = 0;
async function loadDurations() {
const el = document.getElementById('durations');
if (!el) return;
const tick = ++durationsTick;
const chosen = [...el.querySelectorAll('input[data-stage]:checked')].map((i) => i.dataset.stage);
const html = chosen.length
? durationsBody(await api('GET', durationsPath(chosen)).catch((ex) => ({ error: ex.message })))
: '<div class="empty">Zaznacz co najmniej jeden etap.</div>';
if (tick !== durationsTick) return;
const out = el.querySelector('.out');
out.innerHTML = html;
localize(out);
}
function saveRecordNew() {
guard(async () => {
const body = { name: $('rcName').value, note: $('rcNote').value || null };
if (TENANCY === 'nodes') body.parent_id = $('rcParent') ? $('rcParent').value : null;
const r = await api('POST', '/records', body);
closeModal();
toast('Zapisano.');
location.hash = '#/records/' + encodeURIComponent(r.id);
await router();
});
function bandLabel(b) {
const n = (v) => `<span data-no-i18n>${esc(String(v))}</span>`;
if (b.to == null) return `<span>ponad</span> ${n(b.from - 1)} <span>dni</span>`;
if (!b.from) return `<span>najwyżej</span> ${n(b.to)} <span>dni</span>`;
return `${n(`${b.from}-${b.to}`)} <span>dni</span>`;
}
function openRecordEdit(id) {
guard(async () => {
const r = await api('GET', '/records/' + encodeURIComponent(id));
modal('Edytuj', r.name,
`<label class="field">Nazwa<input id="reName" value="${esc(r.name)}" /></label>
<label class="field" style="margin-top:12px">Notatka<textarea id="reNote">${esc(r.note || '')}</textarea></label>
<label class="field" style="margin-top:12px">Status
<select id="reStatus">
<option value="open" ${r.status === 'open' ? 'selected' : ''}>otwarty</option>
<option value="done" ${r.status === 'done' ? 'selected' : ''}>zamknięty</option>
</select></label>`,
`<button class="btn" onclick="closeModal()">Anuluj</button>
<button class="btn primary" onclick="saveRecordEdit('${esc(id)}')">Zapisz</button>`);
});
}
function saveRecordEdit(id) {
guard(async () => {
await api('PATCH', '/records/' + encodeURIComponent(id), {
name: $('reName').value,
note: $('reNote').value,
status: $('reStatus').value,
});
closeModal();
toast('Zapisano.');
await router();
});
}
function deleteRecord(id) {
modal('Usuń', '',
'<div class="banner warn">Tej operacji nie da się cofnąć.</div>',
`<button class="btn" onclick="closeModal()">Anuluj</button>
<button class="btn danger" onclick="confirmDeleteRecord('${esc(id)}')">Usuń</button>`);
}
function confirmDeleteRecord(id) {
guard(async () => {
await api('DELETE', '/records/' + encodeURIComponent(id));
closeModal();
toast('Zapisano.');
location.hash = '#/records';
await router();
});
function durationsBody(d) {
if (!d) return '<div class="faint tiny">Wczytywanie…</div>';
if (d.error) return `<div class="banner err">${esc(d.error)}</div>`;
if (d.status && d.status !== 'ok') return `<div class="empty">${esc(LOG_STATUS[d.status] || d.status)}</div>`;
const skipped = d.skipped || {};
const note = `<div class="tiny faint" style="margin-top:10px"><span>Poza pomiarem:</span> <span data-no-i18n>${esc(String(skipped.missing || 0))}</span> <span>bez zdarzeń wybranych etapów,</span> <span data-no-i18n>${esc(String(skipped.order || 0))}</span> <span>ze zdarzeniami w złej kolejności.</span></div>`;
if (!d.measured) return '<div class="empty">Żaden dokument nie ma jeszcze zdarzeń wybranych etapów.</div>' + note;
const median = Number(d.median_days).toLocaleString(LOCALE, { maximumFractionDigits: 1 });
const top = Math.max(...d.bands.map((b) => b.count));
const bands = d.bands.map((b) => `<li><span class="name">${bandLabel(b)}</span><span class="bar"><span style="width:${top ? (b.count / top) * 100 : 0}%"></span></span><span class="faint" data-no-i18n>${esc(String(b.count))}</span></li>`).join('');
return `<div class="durations"><div class="tiles stats"><div class="tile"><div class="k">Mediana, dni</div><div class="v" data-no-i18n>${esc(median)}</div></div>
<div class="tile"><div class="k">Zmierzone dokumenty</div><div class="v" data-no-i18n>${esc(String(d.measured))}</div></div></div>
<ul class="bars static">${bands}</ul></div>${note}`;
}
/* ── administration ─────────────────────────────────────────────────────── */
@@ -722,17 +906,19 @@ function openSearch() {
const run = async () => {
const q = input.value.trim();
if (!q) { $('sres').innerHTML = ''; return; }
try {
const rows = await api('GET', '/records?q=' + encodeURIComponent(q));
$('sres').innerHTML = rows.length
? `<div class="sgroup">Rekordy</div>` + rows.slice(0, 12).map((r) =>
`<button class="sitem" onclick="closeModal();location.hash='#/records/${encodeURIComponent(r.id)}'">
<span class="ic">${svg(ICN.file)}</span>
<span class="sb"><span class="st">${esc(r.name)}</span>
<span class="ss">${esc(r.note || '')}</span></span></button>`).join('')
: '<div class="search-empty">Brak wyników</div>';
localize($('sres'));
} catch { $('sres').innerHTML = ''; }
/* Panorama keeps no records of its own: the palette finds a tile on the dashboard already
loaded and opens the list it counts, in its module. */
const needle = q.toLocaleLowerCase(LOCALE);
const hits = ((dash.data && dash.data.modules) || []).flatMap((m) => m.tiles.map((t) => ({ m, t })))
.filter(({ m, t }) => `${m.name} ${t.label}`.toLocaleLowerCase(LOCALE).includes(needle));
$('sres').innerHTML = hits.length
? `<div class="sgroup">Kafelki</div>` + hits.slice(0, 12).map(({ m, t }) =>
`<a class="sitem" href="${esc(t.href)}">
<span class="ic">${svg(ICN.dashboard)}</span>
<span class="sb"><span class="st" data-no-i18n>${esc(t.label)}</span>
<span class="ss" data-no-i18n>${esc(m.name)} · ${esc(String(t.count))}</span></span></a>`).join('')
: '<div class="search-empty">Brak wyników</div>';
localize($('sres'));
};
input.addEventListener('input', () => { clearTimeout(timer); timer = setTimeout(run, 180); });
}