Port the negotiation room from Compass (M3)

negotiation_room is Agora's subject (dredd_core.document_ref: a Galena
DocumentRef or a plain_files FileRef); contract_version and contract_comment
become negotiation_round and negotiation_comment. With Galena a round is a new
commit on the room's document, written through Galena's upload (dest = the
document's path) with the person's token and pinned at the commit Galena
answers; without Galena it is a new plain file. Access is the room's
participants plus the module's moderators (plan P5). The .docx comparison
(compare.py, stdlib only) is kept server-side. A round from the other side
emits negotiation.round_received (dredd-core 0.20 events) in the round's
transaction. Revision 0005 is idempotent; 0001 builds with checkfirst=False;
provision.sql is rendered for the platform.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-12 20:47:15 +01:00
co-authored by Claude Opus 5.5
parent 160bf0d39f
commit cd3d0f130b
31 changed files with 2326 additions and 398 deletions
+6
View File
@@ -72,6 +72,12 @@ DB_LOCAL_HOSTS=
# ── Storage ──────────────────────────────────────────────────────────────────
DATA_DIR=/data
# ── Galena (optional) ────────────────────────────────────────────────────────
# Galena's PUBLIC base URL (https://<site>/galena). Empty = no Galena: rooms are plain files only,
# and a room on a Galena document answers 409 galena_disabled (D9). Set, every round of a room on a
# Galena document is written there as a new commit of that document, with the person's own token.
GALENA_BASE_URL=
# ── One platform, one account ────────────────────────────────────────────────
# The shared identity schema. Empty — this stack — is STANDALONE: Agora 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).
run: |
python -m dredd_core.managed provision --sql-only \
--schema agora --app-role agora_app --migrator-role agora_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).
+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; `agora, 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; `agora, 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 and
Lexicon's `0001`: on a fresh schema there is nothing to check, and the local copies are exactly what
`0003` and `0005` are 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:
@@ -0,0 +1,112 @@
"""The negotiation room (M3, ported from Compass's `0017_negocjacje`): rooms, participants, rounds,
comments — and the module-event log Agora writes `negotiation.round_received` into (dredd-core
0.20.0 `events`).
`0001` builds from the live metadata, so a database created after this revision already has every
table below and this one has nothing to do but the platform step, the event policies and the
grants. It is idempotent and decided by the catalog, as every revision after `0001` must be:
1. **Tables**: each of this revision's tables that is not yet in `current_schema()` is created from
the metadata. The check is the catalog of THIS schema (`to_regclass(own.name)`), never
`checkfirst`, which follows the whole search_path. The receiver's `module_event_cursor` and
`module_event_receipt` are Agora's own in both shapes (importing `dredd_core.events` registers
them; Agora sends and receives nothing yet). Standalone the log `module_event` is too.
2. **The event log**. Standalone: `event_policies_sql()` on `current_schema()` (row-level security:
a role inserts only rows whose `source_role` is itself). On the platform (`IDENTITY_SCHEMA` set)
the log is the hub's (`dredd.module_event`, created and granted by the hub's revision); a fresh
platform install still gets a local copy from `0001`, which would shadow the shared one through
the search_path, so it is dropped here — while empty. A row in it would be an event nobody else
ever read, and dropping it silently is the one thing this revision refuses to do.
3. **Runtime grants**, as every table-creating revision ends: rooms, rounds and comments on
`NO_DELETE`, the log and the receipts on `APPEND_ONLY` (`app/models/__init__.py`).
No SQL text below carries a percent sign or a colon-name sequence: `op.execute` wraps it in `text()`.
Downgrade drops this revision's own tables when the database is standalone (the log too: events are
a feed, the evidence is the rounds and the audit); on the platform it refuses, as `0003` does.
"""
from __future__ import annotations
from dredd_core.events import event_policies_sql
from dredd_core.schema import create_enum_types, runtime_grants_sql
from sqlalchemy import text
from alembic import op
from app.config import get_settings
from app.models import APPEND_ONLY_TABLES, NO_DELETE_TABLES, Base
revision = "0005"
down_revision = "0004"
branch_labels = None
depends_on = None
#: This revision's own tables, parents before children.
OWN_TABLES = ("negotiation_room", "negotiation_participant", "negotiation_round",
"negotiation_comment", "module_event_cursor", "module_event_receipt")
EVENT_LOG = "module_event"
def _q(name: str) -> str:
return '"' + name.replace('"', '""') + '"'
def _own(bind) -> str:
return bind.execute(text("SELECT current_schema()")).scalar()
def _exists(bind, schema: str, table: str) -> bool:
return bind.execute(text("SELECT to_regclass(:n) IS NOT NULL"),
{"n": f"{_q(schema)}.{_q(table)}"}).scalar()
def _drop_local_log(bind, own: str) -> None:
if not _exists(bind, own, EVENT_LOG):
return
rows = bind.execute(text(f"SELECT count(*) FROM {_q(own)}.{_q(EVENT_LOG)}")).scalar()
if rows:
raise RuntimeError(
f"negotiation: {own}.{EVENT_LOG} holds {rows} event(s), written while this schema had a "
"log of its own; on the platform the log is the hub's. Export them if they matter, "
"empty the table, then migrate again. Nothing was dropped.")
op.execute(f"DROP TABLE {_q(own)}.{_q(EVENT_LOG)}")
def _grants() -> str:
return runtime_grants_sql(get_settings().db_app_role, append_only=APPEND_ONLY_TABLES,
no_delete=NO_DELETE_TABLES)
def upgrade() -> None:
bind = op.get_bind()
settings = get_settings()
if op.get_context().as_sql:
# Offline (`--sql`) there is no catalog to ask: `0001` already rendered every table from
# the metadata, so the rendering of this revision is its grants.
op.execute(_grants())
return
own = _own(bind)
create_enum_types(bind, Base.metadata)
if settings.shares_identity:
_drop_local_log(bind, own)
wanted = OWN_TABLES
else:
wanted = (EVENT_LOG, *OWN_TABLES)
missing = [Base.metadata.tables[name] for name in wanted if not _exists(bind, own, name)]
if missing:
# Unqualified, so it lands in current_schema().
Base.metadata.create_all(bind=bind, tables=missing, checkfirst=False)
if not settings.shares_identity:
op.execute(event_policies_sql())
op.execute(_grants())
def downgrade() -> None:
if get_settings().shares_identity:
raise RuntimeError("negotiation: no downgrade on the platform.")
bind = op.get_bind()
own = _own(bind)
for table in reversed((EVENT_LOG, *OWN_TABLES)):
if _exists(bind, own, table):
op.execute(f"DROP TABLE {_q(own)}.{_q(table)} CASCADE")
+18 -1
View File
@@ -94,9 +94,26 @@ class Settings(BaseSettings):
_require_verified_tls(name, getattr(self, name.lower()), self.db_local_hosts)
return self
# Working directory for anything written to disk (exports, generated documents).
# Working directory for anything written to disk. A room or round without Galena lives under
# DATA_DIR/files (dredd_core.plain_files), one file = one id, never overwritten.
data_dir: str = "data"
# ── Galena (D9) ───────────────────────────────────────────────────────────────
# Galena's PUBLIC base URL (`https://<site>/galena`). A room on a Galena document reads it, and
# writes each new round as a commit on it, through Galena's API with the acting person's token
# (dredd_core.module_client). Empty = Galena is off for this module: rooms are plain files only,
# and one already on a document answers 409 `galena_disabled`. As Arbiter and Lexicon.
galena_base_url: str = ""
@field_validator("galena_base_url")
@classmethod
def _galena_is_a_safe_address(cls, v: str) -> str:
v = v.strip()
if v:
from dredd_core.module_client import check_base_url
check_base_url(v)
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: Agora owns `app_user` / `session` / `module_permission` in
+1 -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,11 @@ from dredd_core.enums import SessionKind, TokenScope
# ── Agora'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: Agora keeps its states as text with a CHECK (`models/negotiation.py`).
__all__ = [
# from dredd-core, unchanged
"SessionKind",
"TokenScope",
# this app's own
"RecordStatus",
]
+6 -4
View File
@@ -20,8 +20,9 @@ from .deps import refuse_cross_site_write
from .edge import BodySizeLimit, ConsoleUnlessApi, SecurityHeaders, SpaStaticFiles
from .errors import ProblemDetailErrorMiddleware, install_error_handlers
from .logging_config import configure_logging
from .models import SHARED_TABLES
from .observability import setup_observability
from .routers import admin, auth, dashboard, example, health, users
from .routers import admin, auth, dashboard, health, rooms, users
API_PREFIX = "/api/v1"
@@ -58,7 +59,8 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
own = conn.scalar(text("SELECT current_schema()")) or ""
try:
assert_identity_schema(conn, own_schema=own,
identity_schema=settings.identity_schema)
identity_schema=settings.identity_schema,
tables=SHARED_TABLES)
except IdentitySchemaError as exc:
# Core names the problem; this names the way out, because there is one specific way
# to arrive here that looks like a bug and is not. Revision 0003 is a **no-op when
@@ -81,7 +83,7 @@ async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
app = FastAPI(
title="Agora API",
version=__version__,
description="A self-hosted management console.",
description="Negocjacje: pokoje, rundy wymiany, porównanie i wątek komentarzy.",
docs_url=f"{API_PREFIX}/docs",
redoc_url=None,
openapi_url=f"{API_PREFIX}/openapi.json",
@@ -116,7 +118,7 @@ if settings.cors_origins_list:
for router in (
health.router, auth.router, users.router, admin.router,
example.router, dashboard.router,
rooms.router, dashboard.router,
):
app.include_router(router, prefix=API_PREFIX)
+24 -5
View File
@@ -22,7 +22,10 @@ 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.
Agora's own models are in `.negotiation`. Module events come from dredd-core (`dredd_core.events`,
v0.20.0): Agora SENDS `negotiation.round_received`. Standalone the log `module_event` is this app's
own; on the platform it is the hub's, which is why `SHARED_TABLES` holds it beside the identity
tables.
"""
from dredd_core import (
AppSetting,
@@ -36,8 +39,21 @@ from dredd_core import (
UUIDPkMixin,
pg_enum,
)
from dredd_core.events import EventCursor, EventReceipt, ModuleEvent
from dredd_core.identity import EVENT_TABLES, SHARED_IDENTITY_TABLES
from .example import Record
from .negotiation import (
NegotiationComment,
NegotiationParticipant,
NegotiationRoom,
NegotiationRound,
)
#: The tables that belong to the platform, not to this app, when it is a module of it: the shared
#: identity tables and the event log. They may not exist in this app's schema there
#: (`assert_identity_schema` in the lifespan is given this set), and a backup sweep would leave them
#: out (`own_tables(..., shared=SHARED_TABLES)`).
SHARED_TABLES: frozenset[str] = SHARED_IDENTITY_TABLES | EVENT_TABLES
# ── evidence tables: what the runtime role may never rewrite ──────────────────────────────────────
# The runtime-grants migration (alembic/versions/0002_runtime_grants.py, and every later revision
@@ -48,9 +64,11 @@ from .example import Record
# (--append-only / --no-delete). Changing them on a deployed database needs a new revision that
# re-applies the grants.
#: The runtime role may INSERT and SELECT, never UPDATE, DELETE or TRUNCATE.
APPEND_ONLY_TABLES: tuple[str, ...] = ("audit_log",)
APPEND_ONLY_TABLES: tuple[str, ...] = ("audit_log", "module_event", "module_event_receipt")
#: The runtime role may never DELETE or TRUNCATE (a decision that must survive; supersede it instead).
NO_DELETE_TABLES: tuple[str, ...] = ()
#: A room, its rounds and its comments are evidence of the exchange (a comment is "deleted" by
#: `deleted_at`, a room is closed, never removed).
NO_DELETE_TABLES: tuple[str, ...] = ("negotiation_room", "negotiation_round", "negotiation_comment")
__all__ = [
"Base", "TimestampMixin", "UUIDPkMixin", "SafeInet", "pg_enum",
@@ -59,6 +77,7 @@ __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",
"NegotiationRoom", "NegotiationParticipant", "NegotiationRound", "NegotiationComment",
"ModuleEvent", "EventCursor", "EventReceipt", "SHARED_TABLES",
"APPEND_ONLY_TABLES", "NO_DELETE_TABLES",
]
-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"),)
+135
View File
@@ -0,0 +1,135 @@
"""The negotiation room (ported from Compass, spec 2026-10-13 negocjacje G1-G9; the Compass split plan
of 2026-11-06, work package M3).
**`negotiation_room` is Agora's subject** (the plan's "przedmiot pracy"): one row pinned to exactly
one Galena document or one plain file, in the two `dredd_core.document_ref` shapes, with no foreign
key across modules. It takes the place of Compass's `contract`. The room's own reference is **round
1**, the document the negotiation started from; it never changes, so nothing that read it is ever
rewritten.
**`negotiation_round`** (Compass's `contract_version`) is one round of the exchange: number, side,
note, who and when, and a reference of its own in the room's shape. The plan's ruling ("Agora a
nikt poza Galeną nie wersjonuje"): a round is an EVENT carrying a file, not a document history.
With Galena (the room's reference is a DocumentRef) the round's bytes are a new commit on that same
document, written through Galena's own upload with the acting person's token, and the round pins
that commit; without Galena they are one new `plain_files` file. No merging, authorship or
redaction here. A round is evidence of what a side sent, so `NO_DELETE` (`models/__init__.py`).
**`negotiation_comment`** (Compass's `contract_comment`): plain text, never edited, its author may
delete it (`deleted_at`, the row stays, `NO_DELETE`). Internal only (G5): the counterparty has no
account here; a guest is a later work package.
**`negotiation_participant`** answers who may enter a room (plan P5: without Galena there is no
tree, so access = the room's participants + this module's moderators, no copy of `node`). The owner
is always one. With Galena, reading a round's bytes is still Galena's decision, asked with the
person's token.
"""
from __future__ import annotations
import datetime as dt
import uuid
from dredd_core import Base, TimestampMixin, UUIDPkMixin
from dredd_core.document_ref import SubjectRefMixin
from sqlalchemy import (
Boolean,
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
Text,
UniqueConstraint,
text,
)
from sqlalchemy.orm import Mapped, mapped_column
#: Whose version a round is (G1): ours, or the other side's. The first one from the other side is
#: what `negotiation.round_received` reports (G8 moved to an event: the register is Galena's).
SIDES = ("nasza", "druga_strona")
#: A room open for rounds and comments, or closed (kept, read-only).
ROOM_STATUSES = ("open", "closed")
def _one_of(column: str, values: tuple[str, ...]) -> str:
return f"{column} IN ({', '.join(repr(v) for v in values)})"
class NegotiationRoom(UUIDPkMixin, TimestampMixin, SubjectRefMixin, Base):
__tablename__ = "negotiation_room"
title: Mapped[str] = mapped_column(Text, nullable=False)
note: Mapped[str | None] = mapped_column(Text)
status: Mapped[str] = mapped_column(Text, nullable=False, server_default=text("'open'"))
#: Seeded demo data.
demo: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("false"))
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__ = (
*SubjectRefMixin.subject_ref_constraints(),
CheckConstraint(_one_of("status", ROOM_STATUSES), name="status"),
Index("ix_negotiation_room_status", "status"),
Index("ix_negotiation_room_document", "ref_document_id"),
)
class NegotiationParticipant(UUIDPkMixin, Base):
__tablename__ = "negotiation_participant"
room_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("negotiation_room.id", ondelete="CASCADE"), nullable=False
)
user_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("app_user.id"), nullable=False)
added_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
__table_args__ = (
UniqueConstraint("room_id", "user_id", name="uq_negotiation_participant"),
Index("ix_negotiation_participant_user", "user_id"),
)
class NegotiationRound(UUIDPkMixin, SubjectRefMixin, Base):
__tablename__ = "negotiation_round"
room_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("negotiation_room.id", ondelete="RESTRICT"), nullable=False
)
#: 2, 3, ... (round 1 is the room's own reference and has no row, as in Compass).
number: Mapped[int] = mapped_column(Integer, nullable=False)
side: Mapped[str] = mapped_column(Text, nullable=False)
note: Mapped[str | None] = mapped_column(Text)
#: The name the file had on the person's disk (a Galena round keeps the document's path).
original_filename: Mapped[str] = mapped_column(Text, nullable=False)
created_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
__table_args__ = (
*SubjectRefMixin.subject_ref_constraints(),
CheckConstraint(_one_of("side", SIDES), name="side"),
CheckConstraint("number >= 2", name="number"),
UniqueConstraint("room_id", "number", name="uq_negotiation_round_number"),
)
class NegotiationComment(UUIDPkMixin, Base):
__tablename__ = "negotiation_comment"
room_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("negotiation_room.id", ondelete="RESTRICT"), nullable=False
)
#: The round it is about, if the author said; a number, as round 1 has no row.
round: Mapped[int | None] = mapped_column(Integer)
author_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("app_user.id"), nullable=False)
body: Mapped[str] = mapped_column(Text, nullable=False)
created_at: Mapped[dt.datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=text("now()")
)
deleted_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
__table_args__ = (Index("ix_negotiation_comment_room", "room_id", "created_at"),)
+2 -8
View File
@@ -13,7 +13,7 @@ from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import get_current_user
from ..models import AppUser
from ..services import example as service
from ..services import rooms as service
router = APIRouter(tags=["dashboard"])
@@ -21,10 +21,4 @@ router = APIRouter(tags=["dashboard"])
@router.get("/dashboard")
def dashboard(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 service.dashboard(db, user)
-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"}
+162
View File
@@ -0,0 +1,162 @@
"""Negotiation rooms over HTTP (spec 2026-10-13 negocjacje §2, on a room instead of a contract):
the rooms, their participants, rounds, comparison and thread. No SQL here: `services/rooms.py` and
`services/negotiation.py` own the queries and the access checks (a room somebody may not enter is a
404). `add_round` commits itself, as an upload does, because it moves bytes; the rest commit here.
"""
from __future__ import annotations
import uuid
from typing import Literal
from dredd_core.plain_files import MAX_FILE_BYTES
from fastapi import APIRouter, Depends, File, Form, Query, Request, UploadFile
from fastapi.responses import Response
from sqlalchemy.orm import Session
from ..db import get_db
from ..deps import client_ip, extract_token, get_current_user
from ..errors import ValidationError
from ..models import AppUser
from ..schemas import CommentIn, ParticipantIn, RoomDocumentIn, RoomUpdateIn
from ..services import negotiation
from ..services import rooms as service
router = APIRouter(prefix="/rooms", tags=["rooms"])
async def _read_upload(file: UploadFile) -> bytes:
data = await file.read(MAX_FILE_BYTES + 1)
if len(data) > MAX_FILE_BYTES:
raise ValidationError("Plik jest za duży.", {"code": "file_too_large"})
return data
@router.get("")
def list_rooms(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user),
q: str = Query("", max_length=200),
status: Literal["open", "closed"] | None = Query(None)) -> list[dict]:
return service.list_rooms(db, user, q=q, status=status)
@router.post("/upload", status_code=201)
async def create_from_file(request: Request, file: UploadFile = File(...),
title: str | None = Form(None, max_length=200),
note: str | None = Form(None, max_length=4000),
db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
data = await _read_upload(file)
out = service.create_from_file(db, user, data=data, name=file.filename or "plik",
title=title, note=note, ip=client_ip(request))
db.commit()
return out
@router.post("/document", status_code=201)
def create_from_document(body: RoomDocumentIn, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
out = service.create_from_document(
db, user, document_id=body.document_id, path=body.path, version=body.version,
token=extract_token(request), title=body.title, note=body.note, ip=client_ip(request))
db.commit()
return out
@router.get("/{room_id}")
def get_room(room_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
return service.as_dict(db, service.for_reading(db, user, room_id), user)
@router.patch("/{room_id}")
def update_room(room_id: uuid.UUID, body: RoomUpdateIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
out = service.update_room(db, user, room_id, title=body.title, note=body.note,
status=body.status, ip=client_ip(request))
db.commit()
return out
@router.get("/{room_id}/participants")
def participants(room_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> list[dict]:
return service.participants(db, user, room_id)
@router.post("/{room_id}/participants")
def add_participant(room_id: uuid.UUID, body: ParticipantIn, request: Request,
db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> list[dict]:
out = service.add_participant(db, user, room_id, email=body.email, ip=client_ip(request))
db.commit()
return out
@router.delete("/{room_id}/participants/{person_id}")
def remove_participant(room_id: uuid.UUID, person_id: uuid.UUID, request: Request,
db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> list[dict]:
out = service.remove_participant(db, user, room_id, person_id, ip=client_ip(request))
db.commit()
return out
@router.get("/{room_id}/rounds")
def rounds(room_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> list[dict]:
return negotiation.rounds(db, service.for_reading(db, user, room_id))
@router.post("/{room_id}/rounds", status_code=201)
async def add_round(room_id: uuid.UUID, request: Request, file: UploadFile = File(...),
side: Literal["nasza", "druga_strona"] = Form(...),
note: str | None = Form(None, max_length=500),
db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> list[dict]:
"""A new round (G1); the service checks access and commits. Answers the whole list."""
data = await _read_upload(file)
negotiation.add_round(db, actor=user, room_id=room_id, side=side, note=note,
filename=file.filename or "", content=data,
token=extract_token(request), ip=client_ip(request))
return negotiation.rounds(db, service.for_reading(db, user, room_id))
@router.get("/{room_id}/rounds/{number}/file")
def round_file(room_id: uuid.UUID, number: int, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> Response:
"""A round's bytes, verified against the pinned hash and audited before they stream."""
data, media, headers = negotiation.download(db, user, room_id, number,
token=extract_token(request),
ip=client_ip(request))
db.commit()
return Response(content=data, media_type=media, headers=headers)
@router.get("/{room_id}/compare")
def compare(room_id: uuid.UUID, request: Request, a: int = Query(..., ge=1),
b: int = Query(..., ge=1), db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
return negotiation.comparison(db, user, room_id, a, b, token=extract_token(request))
@router.get("/{room_id}/comments")
def comments(room_id: uuid.UUID, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> list[dict]:
return negotiation.comments(db, user, room_id)
@router.post("/{room_id}/comments", status_code=201)
def add_comment(room_id: uuid.UUID, body: CommentIn, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
out = negotiation.add_comment(db, actor=user, room_id=room_id, body=body.body,
round_number=body.round, ip=client_ip(request))
db.commit()
return out
@router.delete("/{room_id}/comments/{comment_id}")
def delete_comment(room_id: uuid.UUID, comment_id: uuid.UUID, request: Request,
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
out = negotiation.delete_comment(db, actor=user, room_id=room_id, comment_id=comment_id,
ip=client_ip(request))
db.commit()
return out
+19 -10
View File
@@ -13,8 +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,19 +103,30 @@ class GrantIn(BaseModel):
role: NodeRole
# ── the demo entity ───────────────────────────────────────────────────────────
class RecordCreateIn(BaseModel):
name: str = Field(min_length=1, max_length=200)
# ── negotiation rooms ─────────────────────────────────────────────────────────
class RoomDocumentIn(BaseModel):
"""A room on a Galena document, pinned as it is now on `version`."""
document_id: uuid.UUID
path: str = Field(min_length=1, max_length=1024)
version: str = Field(default="main", min_length=1, max_length=200)
title: str | None = Field(default=None, 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):
class RoomUpdateIn(BaseModel):
"""Every field optional: `None` means "not supplied", never "blank it"."""
name: str | None = Field(default=None, min_length=1, max_length=200)
title: str | None = Field(default=None, min_length=1, max_length=200)
note: str | None = Field(default=None, max_length=4000)
status: RecordStatus | None = None
status: str | None = Field(default=None, pattern="^(open|closed)$")
class ParticipantIn(BaseModel):
email: str = Field(min_length=3, max_length=320)
class CommentIn(BaseModel):
body: str = Field(min_length=1, max_length=10_000)
round: int | None = Field(default=None, ge=1)
# ── administration ────────────────────────────────────────────────────────────
+2 -7
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("agora.seed")
@@ -55,10 +52,8 @@ 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")
# No demo room: a room needs a file, and the seed runs in a one-shot container that need not
# share DATA_DIR with the backend. Demo contracts are Galena's seed (the split plan, "Seed").
db.commit()
finally:
+187
View File
@@ -0,0 +1,187 @@
"""Two versions of a contract, side by side as one text (spec 2026-10-13 negocjacje G3).
Only the standard library: `zipfile` and `xml.etree` read the paragraphs of a .docx in the order of
the document (body text, table cells, then footnotes), `difflib` finds what changed, first by
paragraph and then by word inside a paragraph that was reworded. A PDF is not read (G4).
What a paragraph reads as: its `w:t` runs, a tab as a tab, a line break as a space. Text a Word
document holds as a tracked deletion (`w:delText`) is not read and a tracked insertion is, so a
version still carrying tracked changes reads as if they were accepted, which is what the other
side proposes.
A .docx is the other side's file, so the XML is read with a ceiling on its unpacked size (a zip
bomb stops at `MAX_XML_BYTES`), a part that is not UTF-8 is refused, and a part declaring a DTD
is refused before it is parsed and again by the parser's own handlers (`_parse`): Word
never writes one, and without it there is no entity to expand or to resolve (the XXE and
billion-laughs attacks `defusedxml` guards against, with no new dependency).
"""
from __future__ import annotations
import difflib
import io
import re
import xml.etree.ElementTree as ET
import zipfile
from xml.parsers import expat
from ..errors import ValidationError
W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
#: The unpacked size of one part read; a contract's document.xml is a few megabytes at most.
MAX_XML_BYTES = 50 * 1024 * 1024
_TOKEN = re.compile(r"\s+|\w+|[^\w\s]", re.UNICODE)
#: Tokens (words, spaces, punctuation) on one side of a reworded paragraph diffed word by word:
#: about 1,000 words, far past a contract clause, and under a second at worst (`word_diff`).
#: Longer, the paragraph is shown whole.
MAX_PAIR_TOKENS = 2_000
#: The tokens one compare may spend on word diffs, both sides counted: about ten paragraphs at the
#: cap, a few seconds at worst, so a GET any reader may repeat cannot hold a thread for minutes.
#: Past it, the remaining reworded paragraphs are shown whole (the comparison still answers).
MAX_COMPARE_TOKENS = 40_000
#: Paragraphs per side. The paragraph diff is quadratic at worst too; a long contract has a few
#: thousand. Past it, a 422 rather than a degraded answer: nothing smaller to fall back to.
MAX_PARAGRAPHS = 20_000
def _part(archive: zipfile.ZipFile, name: str) -> bytes | None:
try:
info = archive.getinfo(name)
except KeyError:
return None
with archive.open(info) as part:
data = part.read(MAX_XML_BYTES + 1)
if len(data) > MAX_XML_BYTES:
raise ValidationError("Dokument jest za duży, żeby go porównać.")
return data
class _Refused(Exception):
"""A DTD or an entity declaration met by the parser itself."""
def _refuse(*_args) -> None:
raise _Refused
def _parse(xml: bytes) -> ET.Element:
"""`ET.fromstring` behind a second lock: whatever the byte check missed, a first pass of expat
itself stops at the first doctype or entity declaration, before ElementTree reads anything.
(The C ElementTree parser does not expose its expat handlers, hence the separate pass; it is
a linear scan of a part already capped at `MAX_XML_BYTES`.)"""
guard = expat.ParserCreate()
guard.StartDoctypeDeclHandler = _refuse
guard.EntityDeclHandler = _refuse
guard.UnparsedEntityDeclHandler = _refuse
guard.ExternalEntityRefHandler = _refuse
try:
guard.Parse(xml, True)
except expat.ExpatError as exc:
raise ET.ParseError(str(exc)) from exc
return ET.fromstring(xml)
def _paragraphs(xml: bytes, *, skip_separators: bool = False) -> list[str]:
# Word writes UTF-8. A part in another encoding (UTF-16 without a BOM starts with "<" too)
# would hide the DTD from the byte check, so anything with a NUL or not UTF-8 is refused.
if b"\x00" in xml:
raise ValidationError("Nie udało się odczytać tekstu dokumentu Word.")
try:
xml.decode("utf-8")
except UnicodeDecodeError as exc:
raise ValidationError("Nie udało się odczytać tekstu dokumentu Word.") from exc
if (not xml.removeprefix(b"\xef\xbb\xbf").lstrip().startswith(b"<")
or b"<!DOCTYPE" in xml or b"<!ENTITY" in xml):
raise ValidationError("Nie udało się odczytać tekstu dokumentu Word.")
try:
root = _parse(xml)
except (ET.ParseError, _Refused) as exc:
raise ValidationError("Nie udało się odczytać tekstu dokumentu Word.") from exc
out = []
scopes = root.iter(f"{W}footnote") if skip_separators else [root]
for scope in scopes:
if skip_separators and scope.get(f"{W}type") in ("separator", "continuationSeparator"):
continue
for p in scope.iter(f"{W}p"):
text = "".join(t.text or "" if t.tag == f"{W}t" else "\t" if t.tag == f"{W}tab" else " "
for t in p.iter() if t.tag in (f"{W}t", f"{W}tab", f"{W}br", f"{W}cr"))
text = text.strip()
if text:
out.append(text)
return out
def docx_paragraphs(content: bytes) -> list[str]:
"""The non-empty paragraphs of a .docx: the body (tables included, in place), then footnotes."""
try:
archive = zipfile.ZipFile(io.BytesIO(content))
except zipfile.BadZipFile as exc:
raise ValidationError("Nie udało się odczytać tekstu dokumentu Word.") from exc
with archive:
body = _part(archive, "word/document.xml")
if body is None:
raise ValidationError("Nie udało się odczytać tekstu dokumentu Word.")
notes = _part(archive, "word/footnotes.xml")
return _paragraphs(body) + (_paragraphs(notes, skip_separators=True) if notes else [])
def _whole(old: str, new: str) -> list[list[str]]:
"""The reworded paragraph shown whole: all of `old` removed, all of `new` added."""
return [p for p in (["-", old], ["+", new]) if p[1]]
def word_diff(old: str, new: str, budget: list[int] | None = None) -> list[list[str]]:
"""[["=" | "-" | "+", text], ...] turning `old` into `new`, word by word, runs merged.
`SequenceMatcher` without autojunk is roughly quadratic in the tokens: a 2,000-token pair
takes well under a second at worst, a 10,000-token one most of a minute. So a side longer than
`MAX_PAIR_TOKENS`, or a pair past what is left of `budget` (one compare's shared allowance,
`[tokens left]`, spent here), is shown whole instead of word by word."""
a, b = _TOKEN.findall(old), _TOKEN.findall(new)
cost = len(a) + len(b)
if len(a) > MAX_PAIR_TOKENS or len(b) > MAX_PAIR_TOKENS or (
budget is not None and cost > budget[0]):
return _whole(old, new)
if budget is not None:
budget[0] -= cost
parts: list[list[str]] = []
def put(op: str, tokens: list[str]) -> None:
if not tokens:
return
if parts and parts[-1][0] == op:
parts[-1][1] += "".join(tokens)
else:
parts.append([op, "".join(tokens)])
for tag, i1, i2, j1, j2 in difflib.SequenceMatcher(None, a, b, autojunk=False).get_opcodes():
if tag == "equal":
put("=", a[i1:i2])
else:
put("-", a[i1:i2])
put("+", b[j1:j2])
return parts
def diff(old: list[str], new: list[str]) -> list[dict]:
"""The paragraphs of `new` against `old`, in order: each one `same`, `added`, `removed` or
`changed` (with its word diff). A reworded paragraph pairs with the one it replaced, in order;
a moved one reads as removed where it was and added where it is."""
if len(old) > MAX_PARAGRAPHS or len(new) > MAX_PARAGRAPHS:
raise ValidationError("Dokument ma za dużo akapitów, żeby go porównać.")
out: list[dict] = []
budget = [MAX_COMPARE_TOKENS]
matcher = difflib.SequenceMatcher(None, old, new, autojunk=False)
for tag, i1, i2, j1, j2 in matcher.get_opcodes():
if tag == "equal":
out += [{"op": "same", "text": t} for t in old[i1:i2]]
elif tag == "delete":
out += [{"op": "removed", "text": t} for t in old[i1:i2]]
elif tag == "insert":
out += [{"op": "added", "text": t} for t in new[j1:j2]]
else:
pairs = min(i2 - i1, j2 - j1)
out += [{"op": "changed", "parts": word_diff(old[i1 + k], new[j1 + k], budget)}
for k in range(pairs)]
out += [{"op": "removed", "text": t} for t in old[i1 + pairs:i2]]
out += [{"op": "added", "text": t} for t in new[j1 + pairs:j2]]
return out
-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),
}
+272
View File
@@ -0,0 +1,272 @@
"""The rounds of a room, the comparison of two of them, and the team's thread (ported from Compass's
`services/negotiation.py`, spec 2026-10-13 negocjacje G1-G9; the Compass split plan, M3).
**How a round is stored** (the plan: "Agora a nikt poza Galeną nie wersjonuje"). A round is an
event of the exchange carrying a file, never a document history of Agora's own:
* **With Galena** — the room is on a Galena document (a DocumentRef): the round's bytes are
written as a new commit on THAT document, through Galena's own upload (`POST
/projects/{id}/upload` with `dest` = the document's path), with the acting person's token. So
Galena's write chokepoint applies unchanged: its roles (`editor`), its review policy (the commit
may land on the person's working version rather than the main one), its encryption and its audit.
The round pins the commit Galena answered, and the bytes are read back once to prove the hash.
* **Without Galena** — the room is a plain file (a FileRef): the round is one new `plain_files`
file, never written over.
Round 1 is the room's own reference and has no row (as version 1 had none in Compass). The number
is the next one under the room's row lock, so two uploads at once get two numbers.
**Dropped from Compass with the contract** (they belong to other modules now): the register status
move `szkic → negocjacje` (G8) is Galena's, so a round from the other side is reported as the event
`negotiation.round_received` (dredd-core 0.20.0 `events`, written in this transaction) for Galena to
act on; the real-data gate is Arbiter's; the bell notifications (G7) are not ported (plan P12 leaves
notifications in the modules, and Agora has none yet).
"""
from __future__ import annotations
import datetime as dt
import uuid
from dredd_core import document_ref
from dredd_core import events as core_events
from dredd_core.document_ref import DocumentRef, FileRef
from dredd_core.module_client import multipart
from dredd_core.plain_files import response_headers
from sqlalchemy import select
from sqlalchemy.orm import Session as DbSession
from ..config import get_settings
from ..errors import ConflictError, NotFoundError, ValidationError
from ..models import AppUser, NegotiationComment, NegotiationRoom, NegotiationRound
from ..models.negotiation import SIDES
from . import audit, compare, rooms, uploads
#: G5: a comment is a note, not a document.
MAX_COMMENT = 10_000
MAX_NOTE = 500
#: The event a round from the other side writes (the plan's first events, "Praca w dredd-core").
ROUND_RECEIVED = "negotiation.round_received"
_CONTENT_TYPES = {
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".pdf": "application/pdf",
}
def _iso(value) -> str | None:
return value.isoformat() if value is not None else None
def _round_out(db: DbSession, *, number: int, side: str | None, note: str | None, filename: str,
ref, created_by, created_at) -> dict:
return {"number": number, "side": side, "note": note, "original_filename": filename,
"sha256": ref.sha256, "kind": "document" if isinstance(ref, DocumentRef) else "file",
"commit_sha": ref.commit_sha if isinstance(ref, DocumentRef) else None,
"size_bytes": ref.size if isinstance(ref, FileRef) else None,
"format": uploads.extension(filename).lstrip(".") or None,
"created_by_name": rooms.name_of(db, created_by), "created_at": _iso(created_at)}
def _rows(db: DbSession, room: NegotiationRoom) -> list[NegotiationRound]:
return list(db.scalars(select(NegotiationRound).where(NegotiationRound.room_id == room.id)
.order_by(NegotiationRound.number)).all())
def rounds(db: DbSession, room: NegotiationRoom) -> list[dict]:
"""Every round, 1 first: round 1 is the room's own reference."""
first = _round_out(db, number=1, side=None, note=None, filename=rooms.ref_name(room.ref),
ref=room.ref, created_by=room.created_by, created_at=room.created_at)
return [first, *(_round_out(db, number=r.number, side=r.side, note=r.note,
filename=r.original_filename, ref=r.ref, created_by=r.created_by,
created_at=r.created_at) for r in _rows(db, room))]
def round_ref(db: DbSession, room: NegotiationRoom, number: int) -> tuple[object, str]:
"""The reference and the file name of round `number` (404 if there is none)."""
if number == 1:
return room.ref, rooms.ref_name(room.ref)
row = db.scalar(select(NegotiationRound).where(NegotiationRound.room_id == room.id,
NegotiationRound.number == number))
if row is None:
raise NotFoundError("Not found.")
name = row.original_filename if isinstance(row.ref, FileRef) else rooms.ref_name(row.ref)
return row.ref, name
def round_bytes(db: DbSession, room: NegotiationRoom, number: int, *,
token: str | None) -> tuple[bytes, str]:
ref, name = round_ref(db, room, number)
data = document_ref.read(ref, files=rooms.files(), galena=rooms.galena(), token=token)
return data, name
def download(db: DbSession, user: AppUser, room_id: uuid.UUID, number: int, *,
token: str | None, ip: str | None = None) -> tuple[bytes, str, dict]:
"""A round's bytes, audited before they stream (G9), served by core's one rule for untrusted
bytes. No commit."""
room = rooms.for_reading(db, user, room_id)
data, name = round_bytes(db, room, number, token=token)
audit.record(db, action="room.round_downloaded", entity_type="negotiation_room",
entity_id=room.id, actor_id=user.id, detail=f"{number}: {name}", ip=ip)
media, headers = response_headers(name, download=True)
return data, media, headers
# ── a new round ───────────────────────────────────────────────────────────────
def _commit_to_galena(room: NegotiationRoom, data: bytes, *, token: str | None) -> tuple[
DocumentRef, str]:
"""The round as a new commit on the room's Galena document, as the acting person."""
client = rooms.galena_or_refuse()
ref: DocumentRef = room.ref
name = rooms.ref_name(ref)
body, ctype = multipart({"dest": ref.path},
{"file": (name, data, _CONTENT_TYPES[uploads.extension(name)])})
response = client.request("POST", f"/projects/{ref.document_id}/upload", token=token,
body=body, content_type=ctype)
response.raise_for_status(client.service, "Galena nie zapisała nowej rundy.")
result = response.json() or {}
commit = result.get("sha")
if not isinstance(commit, str) or not commit:
raise ConflictError("Galena nie podała zapisanej wersji.", {"code": "galena_no_commit"})
pinned = DocumentRef(document_id=ref.document_id, path=ref.path, commit_sha=commit,
sha256=document_ref.sha256_of(data))
document_ref.read_document(client, pinned, token=token) # proves the bytes, raises on a mismatch
return pinned, str(result.get("mode") or "")
def add_round(db: DbSession, *, actor: AppUser, room_id: uuid.UUID, side: str, note: str | None,
filename: str, content: bytes, token: str | None,
ip: str | None = None) -> NegotiationRound:
"""A new round (G1). Commits itself, as Compass's `add_version` did: the bytes and the row land
together or not at all, the bytes first, so a committed row always has its file.
A Galena round keeps the document's name: Galena writes it at the document's own path, so the
file must be of the same format (a PDF never lands at `umowa.docx`)."""
room = rooms.for_writing(db, actor, room_id)
if side not in SIDES:
raise ValidationError("Nieznana strona rundy.", {"code": "side_unknown"})
note = (note or "").strip() or None
if note and len(note) > MAX_NOTE:
raise ValidationError(f"Notatka do rundy ma najwyżej {MAX_NOTE} znaków.")
ext = uploads.validate(filename, content)
on_galena = isinstance(room.ref, DocumentRef)
if on_galena and ext != uploads.extension(room.ref.path):
raise ValidationError(f"Ten pokój prowadzi dokument {rooms.ref_name(room.ref)}: runda musi "
f"mieć ten sam format ({uploads.extension(room.ref.path)}).",
{"code": "format_differs"})
db.scalars(select(NegotiationRoom).where(NegotiationRoom.id == room.id).with_for_update()
.execution_options(populate_existing=True)).all()
if room.status != "open":
raise ConflictError("Pokój jest zamknięty.", {"code": "room_closed"})
number = rooms.current_number(db, room) + 1
saved: FileRef | None = None
try:
if on_galena:
ref, mode = _commit_to_galena(room, content, token=token)
detail = f"{number}: galena {ref.commit_sha[:12]}" + (f" ({mode})" if mode else "")
else:
ref = saved = rooms.files().save(content, filename)
detail = f"{number}: {filename}"
row = NegotiationRound(room_id=room.id, number=number, side=side, note=note,
original_filename=filename, created_by=actor.id)
row.set_ref(ref)
db.add(row)
db.flush()
audit.record(db, action="room.round_added", entity_type="negotiation_room",
entity_id=room.id, actor_id=actor.id, detail=detail, ip=ip)
if side == "druga_strona":
core_events.emit(db, ROUND_RECEIVED, source_module=get_settings().module_slug,
payload=round_event_payload(room, number, ref))
db.commit()
except Exception:
db.rollback()
if saved is not None:
rooms.files().delete(saved.file_id)
# A Galena commit that landed before a failure here stays in Galena's history: it is the
# person's own write there, harmless, and Galena's to show.
raise
return row
def round_event_payload(room: NegotiationRoom, number: int, ref) -> dict:
"""Identifiers only (events.check_payload): never a title, a name or a note."""
payload = {"room_id": room.id, "round": number, "side": "druga_strona"}
if isinstance(ref, DocumentRef):
payload |= {"document_id": ref.document_id, "commit_sha": ref.commit_sha}
return payload
# ── comparison ────────────────────────────────────────────────────────────────
def comparison(db: DbSession, user: AppUser, room_id: uuid.UUID, a: int, b: int, *,
token: str | None) -> dict:
"""Round `a` against round `b` (G3): their paragraphs' diff, both .docx (G4, a 422)."""
room = rooms.for_reading(db, user, room_id)
if a == b:
raise ValidationError("Wybierz dwie różne rundy.")
texts = []
for number in (a, b):
ref, name = round_ref(db, room, number)
if uploads.extension(name) != ".docx":
raise ValidationError("Porównanie działa dla plików Word (.docx).",
{"code": "compare_docx_only"})
data = document_ref.read(ref, files=rooms.files(), galena=rooms.galena(), token=token)
texts.append(compare.docx_paragraphs(data))
rows = compare.diff(*texts)
return {"a": a, "b": b, "changes": sum(r["op"] != "same" for r in rows), "paragraphs": rows}
# ── the thread ────────────────────────────────────────────────────────────────
def comment_out(db: DbSession, user: AppUser, c: NegotiationComment) -> dict:
return {"id": str(c.id), "round": c.round, "author_name": rooms.name_of(db, c.author_id),
"mine": c.author_id == user.id, "body": c.body, "created_at": _iso(c.created_at),
"deleted": c.deleted_at is not None}
def comments(db: DbSession, user: AppUser, room_id: uuid.UUID) -> list[dict]:
room = rooms.for_reading(db, user, room_id)
rows = db.scalars(select(NegotiationComment).where(NegotiationComment.room_id == room.id)
.order_by(NegotiationComment.created_at, NegotiationComment.id)).all()
return [comment_out(db, user, c) for c in rows]
def add_comment(db: DbSession, *, actor: AppUser, room_id: uuid.UUID, body: str,
round_number: int | None, ip: str | None = None) -> dict:
"""A comment in the thread (G5): plain text, the round it is about if any. No commit."""
room = rooms.for_writing(db, actor, room_id)
body = (body or "").strip()
if not body:
raise ValidationError("Komentarz jest pusty.")
if len(body) > MAX_COMMENT:
raise ValidationError(f"Komentarz ma najwyżej {MAX_COMMENT} znaków.")
if round_number is not None and not 1 <= round_number <= rooms.current_number(db, room):
raise ValidationError("Pokój nie ma takiej rundy.")
comment = NegotiationComment(room_id=room.id, round=round_number, author_id=actor.id,
body=body)
db.add(comment)
db.flush()
audit.record(db, action="room.comment_added", entity_type="negotiation_room",
entity_id=room.id, actor_id=actor.id, detail=str(comment.id), ip=ip)
return comment_out(db, actor, comment)
def delete_comment(db: DbSession, *, actor: AppUser, room_id: uuid.UUID, comment_id: uuid.UUID,
ip: str | None = None) -> dict:
"""The author's own comment only (G9): marked deleted, its text gone, the row kept. Someone
else's is a 404, as if it were not there to delete. No commit."""
room = rooms.for_reading(db, actor, room_id)
comment = db.get(NegotiationComment, comment_id)
if comment is None or comment.room_id != room.id or comment.author_id != actor.id:
raise NotFoundError("Not found.")
if comment.deleted_at is None:
comment.deleted_at = dt.datetime.now(dt.UTC)
comment.body = ""
audit.record(db, action="room.comment_deleted", entity_type="negotiation_room",
entity_id=room.id, actor_id=actor.id, detail=str(comment.id), ip=ip)
return comment_out(db, actor, comment)
+268
View File
@@ -0,0 +1,268 @@
"""Negotiation rooms: Agora's subject of work, its participants, and who may enter.
A room is one row in one of the two `dredd_core.document_ref` shapes (the Compass split plan:
`negotiation_room`), no foreign key across modules: a Galena document pinned at the commit the
negotiation started from, or a plain file under DATA_DIR/files. That reference is round 1.
**Who may do what (plan P5).** Without Galena there is no tree, so access is the room's
participants plus this module's moderators, with no copy of `node`. The owner is always a
participant. Read and write (rounds, comments): a participant or a moderator; a room somebody may
not enter is a 404, never a 403. Managing the room (title, status, participants): its owner or a
moderator. With Galena, Galena still decides whether the person may read or write the document's
bytes: every call there carries the person's own token.
"""
from __future__ import annotations
import uuid
from functools import lru_cache
from dredd_core import document_ref
from dredd_core.document_ref import FileRef
from dredd_core.module_client import ModuleClient
from dredd_core.plain_files import PlainFiles
from sqlalchemy import func, or_, select
from sqlalchemy.orm import Session as DbSession
from ..config import get_settings
from ..errors import ConflictError, NotFoundError, ValidationError
from ..models import AppUser, NegotiationParticipant, NegotiationRoom, NegotiationRound
from ..models.negotiation import ROOM_STATUSES
from . import audit, changes, moderation, uploads
MAX_TITLE = 200
@lru_cache
def files() -> PlainFiles:
return PlainFiles(get_settings().data_dir)
def galena() -> ModuleClient | None:
base = get_settings().galena_base_url
return ModuleClient(base, service="Galena") if base else None
def galena_or_refuse() -> ModuleClient:
client = galena()
if client is None:
raise ConflictError("Galena nie jest włączona dla tego modułu.",
{"code": "galena_disabled"})
return client
def ref_name(ref) -> str:
return ref.name if isinstance(ref, FileRef) else ref.path.rsplit("/", 1)[-1]
# ── access ────────────────────────────────────────────────────────────────────
def is_participant(db: DbSession, room: NegotiationRoom, user: AppUser) -> bool:
if room.owner_id == user.id:
return True
return db.scalar(select(NegotiationParticipant.id).where(
NegotiationParticipant.room_id == room.id,
NegotiationParticipant.user_id == user.id)) is not None
def can_enter(db: DbSession, room: NegotiationRoom, user: AppUser) -> bool:
return is_participant(db, room, user) or moderation.is_moderator(db, user)
def for_reading(db: DbSession, user: AppUser, room_id: uuid.UUID) -> NegotiationRoom:
room = db.get(NegotiationRoom, room_id)
if room is None or not can_enter(db, room, user):
raise NotFoundError("Not found.") # 404, not 403: existence is privileged
return room
def for_writing(db: DbSession, user: AppUser, room_id: uuid.UUID) -> NegotiationRoom:
"""A participant's or moderator's write (a round, a comment): the room must be open."""
room = for_reading(db, user, room_id)
if room.status != "open":
raise ConflictError("Pokój jest zamknięty.", {"code": "room_closed"})
return room
def for_managing(db: DbSession, user: AppUser, room_id: uuid.UUID) -> NegotiationRoom:
room = for_reading(db, user, room_id)
if room.owner_id != user.id and not moderation.is_moderator(db, user):
raise NotFoundError("Not found.")
return room
# ── shapes ────────────────────────────────────────────────────────────────────
def name_of(db: DbSession, user_id: uuid.UUID | None) -> str | None:
user = db.get(AppUser, user_id) if user_id else None
return (user.full_name or user.email) if user else None
def current_number(db: DbSession, room: NegotiationRoom) -> int:
return db.scalar(select(func.coalesce(func.max(NegotiationRound.number), 1))
.where(NegotiationRound.room_id == room.id))
def as_dict(db: DbSession, room: NegotiationRoom, user: AppUser) -> dict:
return {
"id": str(room.id), "title": room.title, "note": room.note, "status": room.status,
"demo": room.demo, "ref": document_ref.to_dict(room.ref),
"kind": "document" if room.ref_document_id is not None else "file",
"name": ref_name(room.ref),
"owner_id": str(room.owner_id) if room.owner_id else None,
"owner_name": name_of(db, room.owner_id),
"current_round": current_number(db, room),
"may_manage": room.owner_id == user.id or moderation.is_moderator(db, user),
"created_at": room.created_at.isoformat() if room.created_at else None,
}
def _visible(db: DbSession, user: AppUser):
if moderation.is_moderator(db, user):
return None
mine = select(NegotiationParticipant.room_id).where(NegotiationParticipant.user_id == user.id)
return or_(NegotiationRoom.owner_id == user.id, NegotiationRoom.id.in_(mine))
def list_rooms(db: DbSession, user: AppUser, *, q: str = "",
status: str | None = None) -> list[dict]:
stmt = select(NegotiationRoom)
visible = _visible(db, user)
if visible is not None:
stmt = stmt.where(visible)
if q:
stmt = stmt.where(NegotiationRoom.title.ilike(f"%{q}%"))
if status:
stmt = stmt.where(NegotiationRoom.status == status)
rows = db.scalars(stmt.order_by(NegotiationRoom.created_at.desc())).all()
return [as_dict(db, r, user) for r in rows]
def _title(value: str | None) -> str:
value = (value or "").strip()
if not value:
raise ValidationError("Nadaj pokojowi tytuł.", {"code": "title_required"})
return value[:MAX_TITLE]
# ── creating ──────────────────────────────────────────────────────────────────
def _new_room(db: DbSession, user: AppUser, ref, *, title: str, note: str | None,
ip: str | None, detail: str) -> NegotiationRoom:
room = NegotiationRoom(title=title, note=(note or "").strip() or None, owner_id=user.id,
created_by=user.id)
room.set_ref(ref)
db.add(room)
db.flush()
db.add(NegotiationParticipant(room_id=room.id, user_id=user.id, added_by=user.id))
db.flush()
audit.record(db, action="room.create", entity_type="negotiation_room", entity_id=room.id,
actor_id=user.id, detail=detail, ip=ip)
return room
def create_from_file(db: DbSession, user: AppUser, *, data: bytes, name: str,
title: str | None = None, note: str | None = None,
ip: str | None = None) -> dict:
"""A room without Galena: round 1 goes to plain_files, one file = one id."""
uploads.validate(name, data)
title = _title(title or name)
ref = files().save(data, name)
try:
room = _new_room(db, user, ref, title=title, note=note, ip=ip, detail=title)
return as_dict(db, room, user)
except Exception:
files().delete(ref.file_id)
raise
def create_from_document(db: DbSession, user: AppUser, *, document_id: uuid.UUID, path: str,
token: str | None, version: str = "main", title: str | None = None,
note: str | None = None, ip: str | None = None) -> dict:
"""A room on a Galena document as it is now on `version` (Galena decides access)."""
client = galena_or_refuse()
uploads.check_name(path)
ref = document_ref.pin_document(client, document_id, path, token=token, ref=version)
room = _new_room(db, user, ref, title=_title(title or path.rsplit("/", 1)[-1]), note=note,
ip=ip, detail=f"galena {document_id}:{path}")
return as_dict(db, room, user)
# ── managing ──────────────────────────────────────────────────────────────────
def update_room(db: DbSession, user: AppUser, room_id: uuid.UUID, *, title: str | None = None,
note: str | None = None, status: str | None = None,
ip: str | None = None) -> dict:
room = for_managing(db, user, room_id)
before = {"title": room.title, "note": room.note, "status": room.status}
# `None` means "not supplied", never "blank it".
if title is not None:
room.title = _title(title)
if note is not None:
room.note = note.strip() or None
if status is not None:
if status not in ROOM_STATUSES:
raise ValidationError("Nieznany status pokoju.", {"code": "status_unknown"})
room.status = status
after = {"title": room.title, "note": room.note, "status": room.status}
db.flush()
audit.record(db, action="room.update", entity_type="negotiation_room", entity_id=room.id,
actor_id=user.id, ip=ip, diff=changes.diff_of(before, after))
return as_dict(db, room, user)
def participants(db: DbSession, user: AppUser, room_id: uuid.UUID) -> list[dict]:
room = for_reading(db, user, room_id)
rows = db.scalars(select(NegotiationParticipant).where(NegotiationParticipant.room_id == room.id)
.order_by(NegotiationParticipant.created_at)).all()
return [{"user_id": str(p.user_id), "name": name_of(db, p.user_id),
"owner": p.user_id == room.owner_id,
"created_at": p.created_at.isoformat() if p.created_at else None} for p in rows]
def add_participant(db: DbSession, user: AppUser, room_id: uuid.UUID, *, email: str,
ip: str | None = None) -> list[dict]:
"""By e-mail, of a person who may use this module (on the platform, a `module_permission`
row; standalone, any active account). Someone already in is not an error."""
room = for_managing(db, user, room_id)
email = (email or "").strip().lower()
person = db.scalar(select(AppUser).where(func.lower(AppUser.email) == email)) if email else None
if person is None or not person.is_active or not moderation.may_use(db, person):
raise ValidationError("Nie ma takiej osoby z dostępem do Agory.",
{"code": "person_unknown"})
if not is_participant(db, room, person):
db.add(NegotiationParticipant(room_id=room.id, user_id=person.id, added_by=user.id))
db.flush()
audit.record(db, action="room.participant_added", entity_type="negotiation_room",
entity_id=room.id, actor_id=user.id, detail=str(person.id), ip=ip)
return participants(db, user, room_id)
def remove_participant(db: DbSession, user: AppUser, room_id: uuid.UUID, person_id: uuid.UUID, *,
ip: str | None = None) -> list[dict]:
room = for_managing(db, user, room_id)
if person_id == room.owner_id:
raise ConflictError("Właściciel pokoju zostaje w nim.", {"code": "owner_stays"})
row = db.scalar(select(NegotiationParticipant).where(
NegotiationParticipant.room_id == room.id, NegotiationParticipant.user_id == person_id))
if row is not None:
db.delete(row)
db.flush()
audit.record(db, action="room.participant_removed", entity_type="negotiation_room",
entity_id=room.id, actor_id=user.id, detail=str(person_id), ip=ip)
return participants(db, user, room_id)
def dashboard(db: DbSession, user: AppUser) -> dict:
rows = list_rooms(db, user)
cards = {
"rooms": len(rows),
"open": sum(1 for r in rows if r["status"] == "open"),
"documents": sum(1 for r in rows if r["kind"] == "document"),
"rounds": sum(r["current_round"] for r in rows),
}
return {"cards": cards, "recent": rows[:8]}
+55
View File
@@ -0,0 +1,55 @@
"""What a round's file may be (spec 2026-10-13 negocjacje G1, as Compass checked a contract upload):
a Word document (.docx) or a PDF, under the size limit, without macros. Standard library only.
Checked before the bytes go anywhere — into `plain_files`, or into Galena as a new commit — so a
round is never a file the comparison or a reader would choke on for a reason known up front.
"""
from __future__ import annotations
import io
import zipfile
from dredd_core.plain_files import MAX_FILE_BYTES
from ..errors import ValidationError
#: The formats a round may have. Negotiations go in Word; a PDF arrives at signing (G4).
EXTENSIONS = (".docx", ".pdf")
def extension(name: str) -> str:
name = (name or "").strip().lower()
dot = name.rfind(".")
return name[dot:] if dot > 0 else ""
def check_name(name: str) -> str:
ext = extension(name)
if ext not in EXTENSIONS:
raise ValidationError("Runda to plik Word (.docx) albo PDF.", {"code": "format_unsupported"})
return ext
def validate(name: str, data: bytes) -> str:
"""The extension, after checking the bytes say the same thing. Raises a Polish 422."""
ext = check_name(name)
if not data:
raise ValidationError("Plik jest pusty.", {"code": "file_empty"})
if len(data) > MAX_FILE_BYTES:
raise ValidationError("Plik jest za duży.", {"code": "file_too_large"})
if ext == ".pdf":
if not data.startswith(b"%PDF-"):
raise ValidationError("To nie jest plik PDF.", {"code": "format_mismatch"})
return ext
try:
with zipfile.ZipFile(io.BytesIO(data)) as archive:
names = set(archive.namelist())
except zipfile.BadZipFile as exc:
raise ValidationError("To nie jest dokument Word (.docx).",
{"code": "format_mismatch"}) from exc
if "word/document.xml" not in names:
raise ValidationError("To nie jest dokument Word (.docx).", {"code": "format_mismatch"})
if any(n.lower().endswith("vbaproject.bin") for n in names):
raise ValidationError("Dokument zawiera makra; zapisz go jako .docx bez makr.",
{"code": "macros"})
return ext
+164
View File
@@ -0,0 +1,164 @@
"""Reading a .docx and diffing two versions (spec 2026-10-13 negocjacje G3), without a database."""
from __future__ import annotations
import io
import time
import zipfile
import pytest
from app.errors import ValidationError
from app.services import compare
from app.services.compare import diff, docx_paragraphs, word_diff
NS = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"'
def p(*runs: str) -> str:
return "<w:p>" + "".join(f"<w:r>{r}</w:r>" for r in runs) + "</w:p>"
def t(text: str) -> str:
return f'<w:t xml:space="preserve">{text}</w:t>'
def docx(body: str, footnotes: str | None = None, *, raw: str | None = None) -> bytes:
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w") as archive:
archive.writestr("word/document.xml",
raw or f'<?xml version="1.0"?><w:document {NS}><w:body>{body}</w:body></w:document>')
if footnotes is not None:
archive.writestr("word/footnotes.xml",
f'<?xml version="1.0"?><w:footnotes {NS}>{footnotes}</w:footnotes>')
return buffer.getvalue()
def test_paragraphs_in_order_with_tables_in_place_and_footnotes_last():
body = (p(t("§ 1. Strony")) + p() +
f"<w:tbl><w:tr><w:tc>{p(t('Cena'))}</w:tc><w:tc>{p(t('100 zł'))}</w:tc></w:tr></w:tbl>" +
p(t("Zdanie "), t("dalej"), "<w:tab/>", t("po tabulatorze"), "<w:br/>", t("i po łamaniu")))
notes = ('<w:footnote w:type="separator" w:id="-1">' + p(t("———")) + "</w:footnote>"
'<w:footnote w:id="1">' + p(t("Przypis jeden")) + "</w:footnote>")
assert docx_paragraphs(docx(body, notes)) == [
"§ 1. Strony", "Cena", "100 zł", "Zdanie dalej\tpo tabulatorze i po łamaniu", "Przypis jeden"]
def test_tracked_changes_read_as_accepted():
body = ("<w:p><w:r>" + t("Kara ") + "</w:r><w:del><w:r><w:delText>10%</w:delText></w:r></w:del>"
"<w:ins><w:r>" + t("5%") + "</w:r></w:ins></w:p>")
assert docx_paragraphs(docx(body)) == ["Kara 5%"]
@pytest.mark.parametrize("content", [
b"not a zip",
docx("", raw="<w:document"), # broken XML
docx("", raw=f'<?xml version="1.0"?><!DOCTYPE w [<!ENTITY a "aaaa">]><w:document {NS}/>'),
docx("", raw=f'<?xml version="1.0"?><!DOCTYPE w SYSTEM "file:///etc/passwd"><w:document {NS}/>'),
])
def test_what_is_not_a_readable_word_document_is_a_polish_refusal(content):
with pytest.raises(ValidationError):
docx_paragraphs(content)
def test_a_document_without_its_body_part_is_refused():
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w") as archive:
archive.writestr("word/other.xml", "<x/>")
with pytest.raises(ValidationError):
docx_paragraphs(buffer.getvalue())
def test_a_part_unpacking_past_the_ceiling_stops_there(monkeypatch):
monkeypatch.setattr(compare, "MAX_XML_BYTES", 1000)
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
archive.writestr("word/document.xml", f"<w:document {NS}>" + " " * 5000 + "</w:document>")
with pytest.raises(ValidationError, match="za duży"):
docx_paragraphs(buffer.getvalue())
def test_a_word_diff_keeps_the_unchanged_words_and_merges_runs():
assert word_diff("Kara umowna wynosi 10% ceny.", "Kara umowna wynosi 5% ceny netto.") == [
["=", "Kara umowna wynosi "], ["-", "10"], ["+", "5"], ["=", "% ceny"], ["+", " netto"],
["=", "."]]
assert word_diff("Bez zmian.", "Bez zmian.") == [["=", "Bez zmian."]]
def test_the_paragraph_diff_names_each_paragraph_once_in_the_new_order():
old = ["Tytuł", "§ 1 stary", "§ 2 usunięty", "§ 3", "Przeniesiony", "§ 4"]
new = ["Tytuł", "§ 1 nowy", "§ 3", "§ 3a dodany", "§ 4", "Przeniesiony"]
got = diff(old, new)
assert [d["op"] for d in got[:5]] == ["same", "changed", "removed", "same", "added"]
assert got[1]["parts"] == [["=", "§ 1 "], ["-", "stary"], ["+", "nowy"]]
# Of two paragraphs that swapped places one stays and the other reads as moved: removed where
# it was, added where it is; which one difflib keeps is its choice.
added = {d["text"] for d in got if d["op"] == "added"}
removed = {d["text"] for d in got if d["op"] == "removed"}
assert added - {"§ 3a dodany"} == removed - {"§ 2 usunięty"}
assert len(added - {"§ 3a dodany"}) == 1 and added - {"§ 3a dodany"} <= {"§ 4", "Przeniesiony"}
# The new version reads off it whole and in its order.
assert [d["text"] if "text" in d else "".join(x for o, x in d["parts"] if o != "-")
for d in got if d["op"] != "removed"] == new
assert diff(old, old) == [{"op": "same", "text": t} for t in old]
def test_a_replaced_block_of_unequal_length_pairs_in_order_and_lists_the_rest():
got = diff(["a b", "c d"], ["a x", "c y", "e f"])
assert [d["op"] for d in got] == ["changed", "changed", "added"]
def test_a_part_not_in_utf8_is_refused_before_parsing():
xml = '<?xml version="1.0" encoding="UTF-16"?><!DOCTYPE x [<!ENTITY a "b">]><x/>'
with pytest.raises(ValidationError):
compare._paragraphs(xml.encode("utf-16"))
def test_utf16_without_a_bom_cannot_slip_a_dtd_past_the_byte_check():
# Starts with "<" and spells no "<!DOCTYPE" in bytes (every character is followed by a NUL),
# yet expat detects the encoding and would expand the entity.
xml = (f'<?xml version="1.0" encoding="UTF-16LE"?><!DOCTYPE d [<!ENTITY a "AAAA">'
f'<!ENTITY b "&a;&a;&a;&a;">]><w:document {NS}><w:body>{p(t("&b;"))}</w:body></w:document>')
raw = xml.encode("utf-16-le")
assert raw.startswith(b"<") and b"<!DOCTYPE" not in raw
with pytest.raises(ValidationError):
compare._paragraphs(raw)
with pytest.raises(ValidationError):
buffer = io.BytesIO() # the same bytes inside a .docx
with zipfile.ZipFile(buffer, "w") as archive:
archive.writestr("word/document.xml", raw)
docx_paragraphs(buffer.getvalue())
@pytest.mark.parametrize("decl", ['<!DOCTYPE d [<!ENTITY a "x">]>', '<!DOCTYPE d SYSTEM "x.dtd">'])
def test_the_parser_itself_stops_at_a_doctype(decl):
# The second lock, without the byte check in front of it.
with pytest.raises(compare._Refused):
compare._parse(f'<?xml version="1.0"?>{decl}<d/>'.encode())
assert compare._parse(b"<d><e>ok</e></d>").find("e").text == "ok"
def test_a_long_reworded_paragraph_is_shown_whole_and_fast():
old = " ".join(f"a{i}" for i in range(10_000)) # 20,000 tokens with the spaces
new = " ".join(f"b{i % 97}" for i in range(10_000))
assert len(compare._TOKEN.findall(old)) > compare.MAX_PAIR_TOKENS
started = time.perf_counter()
got = word_diff(old, new)
assert time.perf_counter() - started < 0.5
assert got == [["-", old], ["+", new]]
started = time.perf_counter()
rows = diff(["Tytuł", old], ["Tytuł", new])
assert time.perf_counter() - started < 0.5
assert rows[1] == {"op": "changed", "parts": [["-", old], ["+", new]]}
def test_one_compare_spends_a_shared_token_budget_then_shows_paragraphs_whole(monkeypatch):
monkeypatch.setattr(compare, "MAX_COMPARE_TOKENS", 10)
rows = diff(["a b c", "d e f"], ["a x c", "d y f"]) # 5 + 5 tokens each pair
assert rows[0]["parts"] == [["=", "a "], ["-", "b"], ["+", "x"], ["=", " c"]]
assert rows[1]["parts"] == [["-", "d e f"], ["+", "d y f"]]
def test_too_many_paragraphs_is_a_polish_refusal(monkeypatch):
monkeypatch.setattr(compare, "MAX_PARAGRAPHS", 3)
with pytest.raises(ValidationError, match="akapitów"):
diff(["a"] * 4, ["a"])
+107
View File
@@ -0,0 +1,107 @@
"""The negotiation room in the console (ported from Compass's `test_console_negotiation`): the room's
rounds and thread, the participants and the comparison, rendered by the console itself in a bare
V8 context. What is checked: everything a person wrote is escaped, delete is offered on the reader's
own comment only, a Galena round shows its commit, and every Polish string on these screens has an
English entry. Skipped without `node`.
"""
from __future__ import annotations
import json
import re
import shutil
import subprocess
from pathlib import Path
import pytest
CONSOLE = Path(__file__).resolve().parents[2] / "frontend" / "app.js"
pytestmark = pytest.mark.skipif(shutil.which("node") is None, reason="node is not installed")
XSS = '<img src=x onerror="alert(1)">'
ROOM = {"id": "r1", "title": XSS, "note": None, "status": "open", "kind": "document",
"name": "umowa.docx", "owner_name": "Anna", "may_manage": True, "current_round": 3}
def rnd(number, side, fmt="docx", **kw):
return {"number": number, "side": side, "note": None, "original_filename": f"najem-{number}.{fmt}",
"sha256": "ab" * 32, "kind": "document", "commit_sha": "c0ffee" * 6 + "abcd",
"size_bytes": None, "format": fmt, "created_by_name": "Anna",
"created_at": "2026-10-13T08:00:00+00:00", **kw}
ROUNDS = [rnd(1, None), rnd(2, "druga_strona", note=XSS), rnd(3, "nasza")]
COMMENTS = [{"id": "m1", "round": 2, "author_name": XSS, "mine": True, "body": XSS,
"created_at": "2026-10-13T09:00:00+00:00", "deleted": False},
{"id": "m2", "round": None, "author_name": "Jan", "mine": False, "body": "",
"created_at": "2026-10-13T10:00:00+00:00", "deleted": True},
{"id": "m3", "round": None, "author_name": "Jan", "mine": False, "body": "Zgoda",
"created_at": "2026-10-13T11:00:00+00:00", "deleted": False}]
PEOPLE = [{"user_id": "u1", "name": "Anna", "owner": True}, {"user_id": "u2", "name": XSS,
"owner": False}]
def run(expr: str):
script = f"""
const vm = require('vm'), fs = require('fs');
const box = {{ window: {{ addEventListener() {{}} }}, navigator: {{ language: 'pl' }},
localStorage: {{ getItem: () => null, setItem() {{}} }},
document: {{ baseURI: 'http://localhost/agora/', addEventListener() {{}},
getElementById: () => null, querySelectorAll: () => [] }},
location: {{ hash: '' }}, URL, URLSearchParams, console }};
vm.createContext(box);
vm.runInContext(fs.readFileSync({json.dumps(str(CONSOLE))}, 'utf8'), box);
process.stdout.write(JSON.stringify(vm.runInContext({json.dumps(expr)}, box)));"""
done = subprocess.run(["node", "-e", script], capture_output=True, text=True, encoding="utf-8")
assert done.returncode == 0, done.stderr
return json.loads(done.stdout)
def section() -> str:
return run(f"""(() => {{
Object.assign(neg, {{ room: {json.dumps(ROOM)}, rounds: {json.dumps(ROUNDS)},
comments: {json.dumps(COMMENTS)}, people: {json.dumps(PEOPLE)} }});
return negotiationBody() + peopleBody();
}})()""")
def test_what_people_wrote_is_escaped():
html = section()
assert "<img" not in html and "&lt;img src=x onerror=&quot;alert(1)&quot;&gt;" in html
def test_delete_is_offered_on_the_readers_own_comment_only():
html = section()
assert "deleteComment('m1')" in html
assert "deleteComment('m2')" not in html and "deleteComment('m3')" not in html
assert "Komentarz usunięty." in html
def test_a_galena_round_shows_its_commit_and_downloads_relative_to_the_module():
html = section()
assert "wersja w Galenie" in html and "c0ffeec0ff" in html
assert 'href="/agora/api/v1/rooms/r1/rounds/2/file"' in html
assert 'href="#/rooms/r1/compare?a=2&b=3"' in html
def test_the_owner_cannot_be_removed_from_the_screen():
html = section()
assert "removePerson('u2')" in html and "removePerson('u1')" not in html
def test_a_changed_paragraph_is_escaped_word_by_word():
out = run("""comparedParagraph({op: 'changed', parts: [['=', 'Cena '], ['-', '<b>10</b>'],
['+', '12']]})""")
assert out == '<p class="chg">Cena <del>&lt;b&gt;10&lt;/b&gt;</del><ins>12</ins></p>'
def test_every_polish_string_on_these_screens_has_an_english_entry():
source = CONSOLE.read_text(encoding="utf-8")
start = source.index("/* ── dashboard ──")
end = source.index("/* ── administration ──")
screens = source[start:end]
dictionary = set(run("Object.keys(I18N)"))
# Text between tags and quoted labels with a Polish letter, the way `localize` meets them.
candidates = set(re.findall(r">([^<>${}`]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^<>${}`]*)<", screens))
candidates |= set(re.findall(r"'([^'${}<>]*[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ][^'${}<>]*)'", screens))
missing = sorted(c.strip() for c in candidates if c.strip() and c.strip() not in dictionary)
assert missing == []
+3 -1
View File
@@ -353,7 +353,9 @@ 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 ("negotiation_room", "owner_id") in found # the app's own subject table
assert ("negotiation_participant", "user_id") in found
assert ("negotiation_comment", "author_id") in found
# 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)
+185 -27
View File
@@ -34,11 +34,21 @@ 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)
def _docx(*paragraphs: str) -> bytes:
import io
import zipfile
body = "".join(f"<w:p><w:r><w:t>{p}</w:t></w:r></w:p>" for p in paragraphs)
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w") as archive:
archive.writestr("word/document.xml",
'<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/'
f'2006/main"><w:body>{body}</w:body></w:document>')
return buffer.getvalue()
def _room(client, headers, title: str, *paragraphs: str) -> dict:
r = client.post("/api/v1/rooms/upload", headers=headers, data={"title": title},
files={"file": ("umowa.docx", _docx(*paragraphs), "application/octet-stream")})
assert r.status_code == 201, r.text
return r.json()
@@ -66,7 +76,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/rooms").status_code == 401
def test_the_admin_boundary(admin_client, make_user):
@@ -101,32 +111,180 @@ 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)
# ── negotiation rooms: access, rounds, compare, thread (spec negocjacje G1-G9, plan P5) ─
def test_a_room_is_its_participants_and_the_moderators(admin_client, make_user):
owner, guest, stranger = make_user("owner"), make_user("partner"), make_user("stranger")
h_owner, h_guest, h_other = (bearer(u["token"]) for u in (owner, guest, stranger))
room = _room(admin_client, h_owner, f"Pokój {RUN}", "§ 1. Cena 100 zł", "§ 2. Termin")
assert room["current_round"] == 1 and room["kind"] == "file"
rid = room["id"]
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
# 404, never 403, for somebody outside the room; the moderator (the admin here) sees it.
for path in (f"/api/v1/rooms/{rid}", f"/api/v1/rooms/{rid}/rounds",
f"/api/v1/rooms/{rid}/comments", f"/api/v1/rooms/{rid}/rounds/1/file"):
assert admin_client.get(path, headers=h_other).status_code == 404, path
assert rid not in {x["id"] for x in admin_client.get("/api/v1/rooms", headers=h_other).json()}
assert admin_client.get(f"/api/v1/rooms/{rid}").status_code == 200
# `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"
# Only the owner (or a moderator) manages participants.
r = admin_client.post(f"/api/v1/rooms/{rid}/participants", json={"email": guest["email"]},
headers=h_other)
assert r.status_code == 404
r = admin_client.post(f"/api/v1/rooms/{rid}/participants", json={"email": guest["email"]},
headers=h_owner)
assert r.status_code == 200 and {p["user_id"] for p in r.json()} == {owner["id"], guest["id"]}
assert admin_client.post(f"/api/v1/rooms/{rid}/participants",
json={"email": f"nikt-{RUN}@example.com"},
headers=h_owner).status_code == 422
assert admin_client.post(f"/api/v1/rooms/{rid}/participants", json={"email": stranger["email"]},
headers=h_guest).status_code == 404
# A round from the other side: a new plain file, number 2.
r = admin_client.post(f"/api/v1/rooms/{rid}/rounds", headers=h_guest,
data={"side": "druga_strona", "note": "uwagi kontrahenta"},
files={"file": ("od nich.docx", _docx("§ 1. Cena 120 zł", "§ 2. Termin"),
"application/octet-stream")})
assert r.status_code == 201, r.text
assert [x["number"] for x in r.json()] == [1, 2] and r.json()[1]["side"] == "druga_strona"
assert r.json()[1]["kind"] == "file"
got = admin_client.get(f"/api/v1/rooms/{rid}/rounds/2/file", headers=h_owner)
assert got.status_code == 200 and got.content == _docx("§ 1. Cena 120 zł", "§ 2. Termin")
assert "sandbox" in got.headers["content-security-policy"]
cmp = admin_client.get(f"/api/v1/rooms/{rid}/compare?a=1&b=2", headers=h_guest).json()
assert cmp["changes"] == 1 and cmp["paragraphs"][0]["op"] == "changed"
assert admin_client.get(f"/api/v1/rooms/{rid}/compare?a=2&b=2",
headers=h_guest).status_code == 422
assert admin_client.get(f"/api/v1/rooms/{rid}/compare?a=1&b=9",
headers=h_guest).status_code == 404
pdf = admin_client.post(f"/api/v1/rooms/{rid}/rounds", headers=h_owner, data={"side": "nasza"},
files={"file": ("podpis.pdf", b"%PDF-1.7\n", "application/pdf")})
assert pdf.status_code == 201
assert admin_client.get(f"/api/v1/rooms/{rid}/compare?a=2&b=3",
headers=h_owner).status_code == 422 # G4: PDF not compared
# The thread: plain text, about a round; only the author deletes, the row stays.
c = admin_client.post(f"/api/v1/rooms/{rid}/comments", json={"body": "Za drogo", "round": 2},
headers=h_owner)
assert c.status_code == 201 and c.json()["round"] == 2
cid = c.json()["id"]
assert admin_client.post(f"/api/v1/rooms/{rid}/comments", json={"body": "x", "round": 9},
headers=h_owner).status_code == 422
assert admin_client.delete(f"/api/v1/rooms/{rid}/comments/{cid}",
headers=h_guest).status_code == 404
d = admin_client.delete(f"/api/v1/rooms/{rid}/comments/{cid}", headers=h_owner).json()
assert d["deleted"] and d["body"] == ""
thread = admin_client.get(f"/api/v1/rooms/{rid}/comments", headers=h_guest).json()
assert [t["id"] for t in thread] == [cid] and thread[0]["deleted"]
# A closed room is read-only; removing the guest takes the room away from them.
assert admin_client.patch(f"/api/v1/rooms/{rid}", json={"status": "closed"},
headers=h_guest).status_code == 404
assert admin_client.patch(f"/api/v1/rooms/{rid}", json={"status": "closed"},
headers=h_owner).json()["status"] == "closed"
assert admin_client.post(f"/api/v1/rooms/{rid}/comments", json={"body": "x"},
headers=h_guest).status_code == 409
assert admin_client.delete(f"/api/v1/rooms/{rid}/participants/{owner['id']}",
headers=h_owner).status_code == 409
assert admin_client.delete(f"/api/v1/rooms/{rid}/participants/{guest['id']}",
headers=h_owner).status_code == 200
assert admin_client.get(f"/api/v1/rooms/{rid}", headers=h_guest).status_code == 404
rows = admin_client.get("/api/v1/admin/audit?action=room.").json()
actions = {e["action"] for e in rows if e.get("entity_id") == rid}
assert {"room.create", "room.round_added", "room.round_downloaded", "room.comment_added",
"room.comment_deleted", "room.participant_added", "room.participant_removed",
"room.update"} <= actions
def test_a_round_from_the_other_side_writes_the_event(admin_client, make_user):
from app.db import SessionLocal
owner = make_user("evowner")
room = _room(admin_client, bearer(owner["token"]), f"Zdarzenie {RUN}", "a")
r = admin_client.post(f"/api/v1/rooms/{room['id']}/rounds", headers=bearer(owner["token"]),
data={"side": "druga_strona"},
files={"file": ("b.docx", _docx("b"), "application/octet-stream")})
assert r.status_code == 201, r.text
r = admin_client.post(f"/api/v1/rooms/{room['id']}/rounds", headers=bearer(owner["token"]),
data={"side": "nasza"},
files={"file": ("c.docx", _docx("c"), "application/octet-stream")})
assert r.status_code == 201, r.text
with SessionLocal() as db:
rows = db.execute(text(
"SELECT kind, payload FROM module_event "
"WHERE payload->>'room_id' = :r ORDER BY id"), {"r": room["id"]}).all()
assert [(k, p["round"], p["side"]) for k, p in rows] == [
("negotiation.round_received", 2, "druga_strona")]
def test_a_galena_room_writes_each_round_as_a_commit(admin_client, make_user, monkeypatch):
"""Galena itself is faked at the HTTP client: what is proven here is Agora's half — the
upload at the document's own path with the person's token, the pinned commit, the refusal of
another format, and 409 galena_disabled once Galena is switched off (D9)."""
import hashlib
import json as _json
from dredd_core.module_client import ModuleResponse
from app.services import rooms as room_service
first = "1" * 40
store = {first: _docx("§ 1. Cena 100 zł")}
commits: list[str] = []
class Galena:
service = "Galena"
def request(self, method, path, *, token, params=None, body=None, content_type=None,
headers=None, accept="application/json", json=None):
assert token, "every call carries the acting person's credential"
if path.endswith("/file-info"):
return ModuleResponse(200, {}, _json.dumps(
{"exists": True, "last_commit": {"sha": first}}).encode())
if path.endswith("/raw"):
return ModuleResponse(200, {}, store[params["ref"]])
if path.endswith("/upload"):
assert b'name="dest"\r\n\r\numowy/umowa.docx' in body
sha = f"{len(commits) + 2}" * 40
commits.append(sha)
store[sha] = body.split(b"\r\n\r\n", 2)[2].rsplit(b"\r\n--", 1)[0]
return ModuleResponse(200, {}, _json.dumps(
{"path": "umowy/umowa.docx", "mode": "published", "sha": sha}).encode())
return ModuleResponse(404, {}, b"")
monkeypatch.setattr(room_service, "galena", lambda: Galena())
owner = make_user("galowner")
h = bearer(owner["token"])
r = admin_client.post("/api/v1/rooms/document", headers=h,
json={"document_id": str(uuid.uuid4()), "path": "umowy/umowa.docx"})
assert r.status_code == 201, r.text
room = r.json()
assert room["kind"] == "document" and room["ref"]["commit_sha"] == first
new = _docx("§ 1. Cena 150 zł")
r = admin_client.post(f"/api/v1/rooms/{room['id']}/rounds", headers=h,
data={"side": "druga_strona"},
files={"file": ("cokolwiek.docx", new, "application/octet-stream")})
assert r.status_code == 201, r.text
second = r.json()[1]
assert second["kind"] == "document" and second["commit_sha"] == commits[0]
assert second["sha256"] == hashlib.sha256(new).hexdigest()
assert admin_client.get(f"/api/v1/rooms/{room['id']}/compare?a=1&b=2",
headers=h).json()["changes"] == 1
pdf = admin_client.post(f"/api/v1/rooms/{room['id']}/rounds", headers=h, data={"side": "nasza"},
files={"file": ("x.pdf", b"%PDF-1.7\n", "application/pdf")})
assert pdf.status_code == 422 and pdf.json()["code"] == "format_differs"
monkeypatch.setattr(room_service, "galena", lambda: None)
off = admin_client.get(f"/api/v1/rooms/{room['id']}/rounds/2/file", headers=h)
assert off.status_code == 409 and off.json()["code"] == "galena_disabled"
@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/rooms/not-a-uuid", None),
("PATCH", f"/api/v1/rooms/{uuid.uuid4()}", {"status": "archived-forever"}),
("GET", "/api/v1/rooms?status=bogus", None),
])
def test_bad_input_is_422_never_500(admin_client, method, path, body):
r = admin_client.request(method, path, json=body)
+8 -3
View File
@@ -30,7 +30,9 @@ 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 {"negotiation_room", "negotiation_participant", "negotiation_round",
"negotiation_comment", "module_event", "module_event_cursor",
"module_event_receipt"} <= set(_metadata().tables)
def test_every_model_enum_is_derived_for_the_migration():
@@ -46,8 +48,11 @@ 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_app_creates_no_enum_type_of_its_own():
"""Agora keeps its states as text with a CHECK; only core's types are derived."""
own = [t for t in _metadata().tables.values() if t.name.startswith("negotiation_")]
assert len(own) == 4
assert not any(isinstance(c.type, PGEnum) for t in own for c in t.columns)
def test_every_evidence_table_is_a_real_table():
+147
View File
@@ -0,0 +1,147 @@
"""Rounds without a database: what a round's file may be, how a round becomes a Galena commit, and
the event a round from the other side writes (spec 2026-10-13 negocjacje G1, the split plan M3)."""
from __future__ import annotations
import hashlib
import io
import uuid
import zipfile
import pytest
from dredd_core import events as core_events
from dredd_core.document_ref import DocumentRef, FileRef
from dredd_core.module_client import ModuleResponse
from app.errors import ConflictError, ValidationError
from app.models import NegotiationRoom
from app.services import negotiation, rooms, uploads
def docx(text: str = "Umowa", *, macros: bool = False) -> bytes:
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w") as archive:
archive.writestr("word/document.xml",
'<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/'
f'2006/main"><w:body><w:p><w:r><w:t>{text}</w:t></w:r></w:p></w:body>'
"</w:document>")
if macros:
archive.writestr("word/vbaProject.bin", b"x")
return buffer.getvalue()
# ── the file ──────────────────────────────────────────────────────────────────
def test_a_round_is_a_docx_or_a_pdf():
assert uploads.validate("Umowa.DOCX", docx()) == ".docx"
assert uploads.validate("a.pdf", b"%PDF-1.7\n...") == ".pdf"
@pytest.mark.parametrize("name,data,code", [
("a.txt", b"x", "format_unsupported"),
("bez_rozszerzenia", b"x", "format_unsupported"),
("a.docx", b"", "file_empty"),
("a.docx", b"not a zip", "format_mismatch"),
("a.pdf", b"PK\x03\x04", "format_mismatch"),
("a.docx", docx(macros=True), "macros"),
])
def test_what_is_not_a_round_is_a_polish_refusal(name, data, code):
with pytest.raises(ValidationError) as exc:
uploads.validate(name, data)
assert exc.value.extra["code"] == code
# ── with Galena: a round is a commit ─────────────────────────────────────────
class FakeGalena:
"""Galena's upload and raw endpoints, as `ModuleClient.request` sees them."""
service = "Galena"
def __init__(self, *, commit: str | None = "c0ffee" * 6 + "abcd", stored: bytes | None = None):
self.commit, self.stored, self.calls = commit, stored, []
def request(self, method, path, *, token, params=None, body=None, content_type=None,
headers=None, accept="application/json", json=None):
self.calls.append((method, path, token, params, body, content_type))
if method == "POST" and path.endswith("/upload"):
if self.stored is None:
self.stored = body.split(b"\r\n\r\n", 2)[2].rsplit(b"\r\n--", 1)[0]
import json as _json
payload = {"path": "umowy/umowa.docx", "mode": "working", "branch": "draft/x",
"sha": self.commit}
return ModuleResponse(200, {"content-type": "application/json"},
_json.dumps(payload).encode())
if method == "GET" and path.endswith("/raw"):
return ModuleResponse(200, {}, self.stored)
return ModuleResponse(404, {}, b"")
def _room(ref) -> NegotiationRoom:
room = NegotiationRoom(id=uuid.uuid4(), title="t")
room.set_ref(ref)
return room
def _doc_ref() -> DocumentRef:
return DocumentRef(document_id=uuid.uuid4(), path="umowy/umowa.docx", commit_sha="a" * 40,
sha256="0" * 64)
def test_a_galena_round_is_an_upload_at_the_documents_own_path_with_the_persons_token(monkeypatch):
data = docx("runda 2")
fake = FakeGalena(stored=data)
monkeypatch.setattr(rooms, "galena", lambda: fake)
room = _room(_doc_ref())
ref, mode = negotiation._commit_to_galena(room, data, token="osoba-token")
method, path, token, _, body, ctype = fake.calls[0]
assert (method, path, token) == ("POST", f"/projects/{room.ref.document_id}/upload",
"osoba-token")
assert b'name="dest"\r\n\r\numowy/umowa.docx' in body and ctype.startswith("multipart/")
assert b'filename="umowa.docx"' in body
assert ref == DocumentRef(document_id=room.ref.document_id, path="umowy/umowa.docx",
commit_sha=fake.commit, sha256=hashlib.sha256(data).hexdigest())
assert mode == "working"
# The bytes are read back at the new commit, as the same person, to prove the hash.
assert fake.calls[1][1].endswith("/raw") and fake.calls[1][3]["ref"] == fake.commit
assert fake.calls[1][2] == "osoba-token"
def test_a_galena_round_whose_bytes_come_back_different_is_refused(monkeypatch):
fake = FakeGalena(stored=b"something else")
monkeypatch.setattr(rooms, "galena", lambda: fake)
with pytest.raises(ConflictError):
negotiation._commit_to_galena(_room(_doc_ref()), docx(), token="t")
def test_a_galena_answer_without_a_commit_is_refused(monkeypatch):
monkeypatch.setattr(rooms, "galena", lambda: FakeGalena(commit=None, stored=docx()))
with pytest.raises(ConflictError) as exc:
negotiation._commit_to_galena(_room(_doc_ref()), docx(), token="t")
assert exc.value.extra["code"] == "galena_no_commit"
def test_without_galena_a_document_room_is_galena_disabled(monkeypatch):
monkeypatch.setattr(rooms, "galena", lambda: None)
with pytest.raises(ConflictError) as exc:
negotiation._commit_to_galena(_room(_doc_ref()), docx(), token="t")
assert exc.value.extra["code"] == "galena_disabled"
def test_galena_is_off_by_default():
assert rooms.galena() is None
# ── the event ─────────────────────────────────────────────────────────────────
def test_the_round_received_event_is_identifiers_only_and_passes_cores_checks():
assert core_events.check_kind(negotiation.ROUND_RECEIVED) == "negotiation.round_received"
room = _room(_doc_ref())
commit = DocumentRef(document_id=room.ref.document_id, path="umowy/umowa.docx",
commit_sha="b" * 40, sha256="1" * 64)
payload = core_events.check_payload(negotiation.round_event_payload(room, 3, commit))
assert set(payload) == {"room_id", "round", "side", "document_id", "commit_sha"}
plain = FileRef(file_id=uuid.uuid4(), sha256="2" * 64, size=3, name="Umowa z X.docx")
payload = core_events.check_payload(negotiation.round_event_payload(_room(plain), 2, plain))
assert set(payload) == {"room_id", "round", "side"} # never a file name
+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"
+6 -11
View File
@@ -90,19 +90,14 @@ avoids.
```bash
python -m dredd_core.managed provision --sql-only --schema agora --app-role agora_app \
--migrator-role agora_migrator --output db/managed/provision.sql
--migrator-role agora_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.
**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 agora --app-role agora_app --migrator-role agora_migrator --identity-schema dredd --identity-owner atrium_migrator --output db/managed/provision.sql
```
The committed file is the **platform** rendering: Agora is split out of Compass to run as a module
of Atrium, so it ships with the identity flags, exactly as Galena, Sygna, Counsel and Lexicon 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.
(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 agora, migrator agora_migrator, app agora_app, extensions: none, migrator statement_timeout 30min
-- search_path agora, extensions; no shared identity schema (this app owns its own accounts)
-- search_path agora, 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 agora --app-role agora_app --migrator-role agora_migrator \
-- --schema agora --app-role agora_app --migrator-role agora_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 agora --app-role agora_app --migrator-role agora_migrator \
-- --schema agora --app-role agora_app --migrator-role agora_migrator --identity-schema dredd --identity-owner atrium_migrator \
-- --migrator-password-env AGORA_MIGRATOR_PASSWORD --app-password-env AGORA_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 := 'agora_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 agora_migrator
ALTER ROLE agora_migrator SET search_path = agora, 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 agora_app
ALTER ROLE agora_app SET search_path = agora, extensions;
-- 10. schema dredd: USAGE for agora_migrator and agora_app
GRANT USAGE ON SCHEMA dredd TO agora_migrator, agora_app;
-- 11. statement_timeout of agora_migrator
-- 11. schema dredd: check that the USAGE grant took
DO $dredd_provision_identity_usage$
DECLARE
identity_schema text := 'dredd';
migrator_role text := 'agora_migrator';
app_role text := 'agora_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 agora_migrator
ALTER ROLE agora_migrator SET search_path = agora, dredd, extensions;
-- 13. search_path of agora_app
ALTER ROLE agora_app SET search_path = agora, dredd, extensions;
-- 14. statement_timeout of agora_migrator
ALTER ROLE agora_migrator SET statement_timeout = '30min';
-- 12. end the temporary membership: no standing SET ROLE agora_migrator for the admin
-- 15. end the temporary membership: no standing SET ROLE agora_migrator for the admin
REVOKE agora_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 := 'agora';
@@ -220,9 +251,9 @@ DECLARE
app_role text := 'agora_app';
extension_names text[] := '{}'::text[];
timeout_setting text := 'statement_timeout=30min';
path_setting text := 'search_path=agora, extensions';
identity_schema text := '';
identity_owner text := '';
path_setting text := 'search_path=agora, 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[];
+15
View File
@@ -510,3 +510,18 @@ 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; }
}
/* The negotiation room: the thread and the round comparison (ported from Compass). */
.thread { display: flex; flex-direction: column; gap: 10px; }
.comment { padding: 8px 10px; border: 1px solid var(--border); border-radius: var(--radius-sm); }
.comment .body { white-space: pre-wrap; overflow-wrap: anywhere; margin-top: 4px; }
.comment.gone { opacity: .7; }
.commentform { margin-top: 12px; }
.commentform textarea { width: 100%; }
.cmp { line-height: 1.6; max-width: 80ch; }
.cmp p { margin: 0 0 10px; padding: 2px 8px; border-left: 3px solid transparent; overflow-wrap: anywhere; }
.cmp p.chg { border-left-color: var(--warn); }
.cmp p.at { background: var(--warn-bg); }
.cmp ins, .cmpkey ins { background: var(--ok-bg); color: var(--ok); text-decoration: underline; }
.cmp del, .cmpkey del { background: var(--err-bg); color: var(--err); text-decoration: line-through; }
.cmpkey { display: flex; gap: 10px; margin-bottom: 12px; }
+361 -98
View File
@@ -20,7 +20,7 @@
depend on the trailing slash — bare `/agora` would resolve to `/api/v1` — which is why a
platform proxy must redirect `/agora` to `/agora/`. */
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: a room is its participants + the moderators. */
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,13 +210,72 @@ 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',
'Zapisano.': 'Saved.',
'Tej operacji nie da się cofnąć.': 'This cannot be undone.',
'zamknięty': 'closed',
'Pokoje': 'Rooms',
'Pokoje negocjacji': 'Negotiation rooms',
'Nowy pokój': 'New room',
'Brak pokojów.': 'No rooms yet.',
'Otwarte': 'Open',
'Na dokumentach Galeny': 'On Galena documents',
'Rundy': 'Rounds',
'Runda': 'Round',
'runda': 'round',
'Ostatnie pokoje': 'Recent rooms',
'Tytuł': 'Title',
'Źródło': 'Source',
'dokument Galeny': 'Galena document',
'plik': 'file',
'Plik': 'File',
'Skąd jest pierwsza runda': 'Where the first round comes from',
'Plik z dysku': 'A file from disk',
'Dokument w Galenie': 'A document in Galena',
'Identyfikator projektu w Galenie': 'Galena project id',
'Ścieżka dokumentu': 'Document path',
'Każda kolejna runda zapisze się w Galenie jako nowa wersja tego dokumentu, Twoim kontem.': 'Every later round is saved in Galena as a new version of this document, with your account.',
'PDF albo DOCX. Pokój widzą jego uczestnicy i moderatorzy modułu.': 'PDF or DOCX. The room is seen by its participants and the module\'s moderators.',
'Pokój widzą jego uczestnicy i moderatorzy modułu.': 'The room is seen by its participants and the module\'s moderators.',
'Wybierz plik.': 'Choose a file.',
'Właściciel': 'Owner',
'właściciel': 'owner',
'Nasza': 'Ours',
'Druga strona': 'Other side',
'Pierwotna': 'Original',
'Strona': 'Side',
'Dodał': 'Added by',
'Kiedy': 'When',
'wersja w Galenie': 'version in Galena',
'Dodaj rundę': 'Add a round',
'Porównaj': 'Compare',
'Porównanie działa dla dwóch rund w formacie Word (.docx).': 'Comparison works for two rounds in Word format (.docx).',
'Komentarze zespołu': 'Team comments',
'Widzą je tylko uczestnicy pokoju; druga strona nie.': 'Only the room\'s participants see them; the other side does not.',
'Komentarz usunięty.': 'Comment deleted.',
'Brak komentarzy.': 'No comments yet.',
'Dodaj komentarz': 'Add a comment',
'Dotyczy rundy': 'About round',
'Bez rundy': 'No round',
'Uczestnicy': 'Participants',
'Adres e-mail': 'E-mail address',
'Dodaj uczestnika': 'Add a participant',
'Czyja to wersja': 'Whose version is it',
'Runda zapisze się w Galenie jako nowa wersja dokumentu, Twoim kontem, w tym samym formacie.': 'The round is saved in Galena as a new version of the document, with your account, in the same format.',
'PDF albo DOCX. Plik nie zastępuje poprzednich rund.': 'PDF or DOCX. The file does not replace earlier rounds.',
'Komentarz jest pusty.': 'The comment is empty.',
'Usunąć ten komentarz?': 'Delete this comment?',
'Porównanie rund': 'Round comparison',
'Runda wcześniejsza': 'Earlier round',
'Runda późniejsza': 'Later round',
'zmienionych akapitów': 'changed paragraphs',
'Poprzednia zmiana': 'Previous change',
'Następna zmiana': 'Next change',
'dopisane': 'added',
'usunięte': 'removed',
'Wróć do pokoju': 'Back to the room',
};
let LANG = (function () {
@@ -372,7 +429,7 @@ const isModerator = () => !!(state.user && state.user.is_moderator);
/* ── navigation ─────────────────────────────────────────────────────────── */
const NAV = [
{ hash: '#/', icon: 'dashboard', label: 'Pulpit' },
{ hash: '#/records', icon: 'file', label: 'Rekordy' },
{ hash: '#/rooms', icon: 'users', label: 'Pokoje', badge: 'rooms' },
];
function renderNav(counts) {
@@ -426,8 +483,9 @@ 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] === 'rooms' && seg[1] && seg[2] === 'compare') await viewCompare(C, seg[1], q);
else if (seg[0] === 'rooms' && seg[1]) await viewRoom(C, seg[1]);
else if (seg[0] === 'rooms') await viewRooms(C, q);
else if (seg[0] === 'admin') await viewAdmin(C);
else C.innerHTML = '<div class="empty">Nie znaleziono strony.</div>';
} catch (ex) {
@@ -443,158 +501,363 @@ async function router() {
async function viewDashboard(C) {
const d = await api('GET', '/dashboard');
const c = d.cards || {};
state.counts = { records: c.total };
state.counts = { rooms: c.open };
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: '' },
{ k: 'Pokoje', v: c.rooms ?? 0 },
{ k: 'Otwarte', v: c.open ?? 0 },
{ k: 'Na dokumentach Galeny', v: c.documents ?? 0 },
{ k: 'Rundy', v: c.rounds ?? 0 },
];
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>`;
`<button class="btn primary" onclick="openRoomNew()">${svg(ICN.plus)}Nowy pokój</button>`)
+ `<div class="tiles">${tiles.map((t) => `<div class="tile"><div class="k">${esc(t.k)}</div><div class="v" data-no-i18n>${esc(String(t.v))}</div></div>`).join('')}</div>`
+ `<div class="card" style="margin-top:14px"><h3>Ostatnie pokoje<span class="n" data-no-i18n>${(d.recent || []).length}</span></h3>${roomTable(d.recent || [])}</div>`;
}
function statusChip(s) {
const cls = s === 'done' ? 'ok' : '';
const label = s === 'done' ? 'zamknięty' : 'otwarty';
return `<span class="chip ${cls}">${esc(label)}</span>`;
/* ── rooms (the Compass split plan, M3: Agora = the room, the rounds, the thread) ── */
const SIDE_LABEL = { nasza: 'Nasza', druga_strona: 'Druga strona' };
function roomStatusChip(s) {
return s === 'closed' ? '<span class="chip">zamknięty</span>' : '<span class="chip ok">otwarty</span>';
}
function recordTable(rows) {
if (!rows.length) return '<div class="empty">Brak rekordów.</div>';
function kindChip(kind) {
return kind === 'document' ? '<span class="chip">dokument Galeny</span>' : '<span class="chip">plik</span>';
}
function roomTable(rows) {
if (!rows.length) return '<div class="empty">Brak pokojó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>
<th>Tytuł</th><th>Status</th><th>Źródło</th><th>Runda</th><th>Utworzono</th>
</tr></thead><tbody>${rows.map((r) => `<tr class="click" onclick="location.hash='#/rooms/${encodeURIComponent(r.id)}'">
<td><div data-no-i18n>${esc(r.title)}${r.note ? `<div class="faint tiny">${esc(r.note)}</div>` : ''}</div></td>
<td${lbl('Status')}>${roomStatusChip(r.status)}</td>
<td${lbl('Źródło')}>${kindChip(r.kind)}</td>
<td${lbl('Runda')} data-no-i18n>${esc(String(r.current_round))}</td>
<td class="faint tiny"${lbl('Utworzono')}>${fmtDate(r.created_at)}</td>
</tr>`).join('')}</tbody></table></div>`;
}
/* ── records ────────────────────────────────────────────────────────────── */
async function viewRecords(C, q) {
async function viewRooms(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' }]);
const rows = await api('GET', '/rooms' + (params.toString() ? '?' + params : ''));
setCrumb([{ label: 'Pokoje' }]);
C.innerHTML = pageHead('Rekordy', rows.length + '',
`<button class="btn primary" onclick="openRecordNew()">${svg(ICN.plus)}Nowy rekord</button>`)
C.innerHTML = pageHead('Pokoje negocjacji', rows.length + '',
`<button class="btn primary" onclick="openRoomNew()">${svg(ICN.plus)}Nowy pokój</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('')}
${['', 'open', 'closed'].map((s) => `<option value="${s}" ${q.status === s ? 'selected' : ''}>${s ? (s === 'closed' ? 'zamknięty' : 'otwarty') : '—'}</option>`).join('')}
</select>
</div>`
+ (rows.length ? `<div class="card">${recordTable(rows)}</div>` : '<div class="empty">Brak rekordów.</div>');
+ (rows.length ? `<div class="card">${roomTable(rows)}</div>` : '<div class="empty">Brak pokojów.</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 : '');
location.hash = '#/rooms' + (p.toString() ? '?' + p : '');
};
$('rq').addEventListener('change', go);
$('rstatus').addEventListener('change', go);
}
async function viewRecord(C, id) {
const r = await api('GET', '/records/' + encodeURIComponent(id));
setCrumb([{ label: 'Rekordy', href: '#/records' }, { label: r.name }]);
/* A file to send as multipart: the JSON `api()` cannot carry one. Same credentials, same errors. */
async function apiForm(method, path, form) {
const opt = { method, body: form, headers: {}, credentials: 'same-origin' };
if (state.token) opt.headers.Authorization = 'Bearer ' + state.token;
const res = await fetch(API + path, opt);
const text = await res.text();
let data = null;
if (text) { try { data = JSON.parse(text); } catch { data = { detail: text }; } }
if (!res.ok) {
const err = new Error((data && (data.detail || data.title)) || ('HTTP ' + res.status));
err.status = res.status;
err.problem = data;
throw err;
}
return data;
}
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>` : ''))
function openRoomNew() {
modal('Nowy pokój', '',
`<label class="field">Tytuł<input id="rnTitle" maxlength="200" /></label>
<label class="field" style="margin-top:12px">Notatka<textarea id="rnNote" maxlength="4000"></textarea></label>
<label class="field" style="margin-top:12px">Skąd jest pierwsza runda
<select id="rnKind" onchange="$('rnFileBox').hidden = this.value !== 'file'; $('rnDocBox').hidden = this.value !== 'document'">
<option value="file">Plik z dysku</option><option value="document">Dokument w Galenie</option></select></label>
<div id="rnFileBox"><label class="field" style="margin-top:12px">Plik<input id="rnFile" type="file" accept=".pdf,.docx" /></label></div>
<div id="rnDocBox" hidden>
<label class="field" style="margin-top:12px">Identyfikator projektu w Galenie<input id="rnDoc" data-no-i18n /></label>
<label class="field" style="margin-top:12px">Ścieżka dokumentu<input id="rnPath" placeholder="umowy/umowa.docx" data-no-i18n /></label>
<div class="tiny faint" style="margin-top:8px">Każda kolejna runda zapisze się w Galenie jako nowa wersja tego dokumentu, Twoim kontem.</div>
</div>
<div class="tiny faint" style="margin-top:8px">PDF albo DOCX. Pokój widzą jego uczestnicy i moderatorzy modułu.</div>`,
`<button class="btn" onclick="closeModal()">Anuluj</button>
<button class="btn primary" onclick="saveRoomNew()">Zapisz</button>`);
}
function saveRoomNew() {
guard(async () => {
let room;
if ($('rnKind').value === 'document') {
room = await api('POST', '/rooms/document', {
document_id: $('rnDoc').value.trim(), path: $('rnPath').value.trim(),
title: $('rnTitle').value.trim() || null, note: $('rnNote').value || null });
} else {
const file = $('rnFile').files[0];
if (!file) { toast('Wybierz plik.'); return; }
const form = new FormData();
form.append('file', file);
if ($('rnTitle').value.trim()) form.append('title', $('rnTitle').value.trim());
if ($('rnNote').value) form.append('note', $('rnNote').value);
room = await apiForm('POST', '/rooms/upload', form);
}
closeModal();
toast('Zapisano.');
location.hash = '#/rooms/' + encodeURIComponent(room.id);
});
}
/* One room on screen: its rounds, the thread, the participants. */
const neg = { room: null, rounds: [], comments: [], people: [] };
async function viewRoom(C, id) {
const rid = encodeURIComponent(id);
const [room, rounds, comments, people] = await Promise.all([
api('GET', `/rooms/${rid}`), api('GET', `/rooms/${rid}/rounds`),
api('GET', `/rooms/${rid}/comments`), api('GET', `/rooms/${rid}/participants`)]);
Object.assign(neg, { room, rounds, comments, people });
setCrumb([{ label: 'Pokoje', href: '#/rooms' }, { label: room.title }]);
C.innerHTML = pageHead(room.title, room.name,
room.may_manage ? `<button class="btn" onclick="openRoomEdit()">${svg(ICN.check)}Edytuj</button>` : '')
+ `<div class="card"><div class="grid3">
${field('Status', r.status === 'done' ? 'zamknięty' : 'otwarty')}
${field('Utworzono', fmtDateTime(r.created_at))}
<div><div class="tiny faint">Status</div><div>${roomStatusChip(room.status)}</div></div>
<div><div class="tiny faint">Źródło</div><div>${kindChip(room.kind)}</div></div>
<div><div class="tiny faint">Właściciel</div><div data-no-i18n>${esc(room.owner_name || '—')}</div></div>
</div>
${r.note ? `<div style="margin-top:14px"><div class="tiny faint">Notatka</div><div>${esc(r.note)}</div></div>` : ''}
</div>`;
${room.note ? `<div style="margin-top:14px" data-no-i18n>${esc(room.note)}</div>` : ''}</div>
<div class="card" style="margin-top:14px" id="negotiation">${negotiationBody()}</div>
<div class="card" style="margin-top:14px" id="people">${peopleBody()}</div>`;
}
function containerOptions(selected) {
return state.containers.map((n) =>
`<option value="${esc(n.id)}" ${n.id === selected ? 'selected' : ''}>${esc(n.path)}</option>`).join('');
function comparePair(rounds) {
const words = rounds.filter((r) => r.format === 'docx');
return words.length >= 2 ? [words[words.length - 2].number, words[words.length - 1].number] : null;
}
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}`,
function negotiationBody() {
const { room, rounds, comments } = neg;
const id = encodeURIComponent(room.id);
const open = room.status === 'open';
const pair = comparePair(rounds);
const rows = rounds.map((r) => `<tr>
<td data-no-i18n>${esc(String(r.number))}</td>
<td>${esc(r.side ? SIDE_LABEL[r.side] : 'Pierwotna')}</td>
<td data-no-i18n>${r.note ? esc(r.note) : '—'}</td>
<td data-no-i18n>${esc(r.created_by_name || '—')}</td>
<td class="faint tiny">${fmtDateTime(r.created_at)}</td>
<td>${r.kind === 'document' ? `<span class="tiny faint">wersja w Galenie</span> <code data-no-i18n>${esc((r.commit_sha || '').slice(0, 10))}</code> ` : ''}<a href="${esc(API)}/rooms/${id}/rounds/${esc(String(r.number))}/file" data-no-i18n>${esc(r.original_filename)}</a></td>
</tr>`).join('');
const thread = comments.length ? comments.map((m) => `<div class="comment${m.deleted ? ' gone' : ''}">
<div class="tiny faint"><span data-no-i18n>${esc(m.author_name || '—')}</span> · ${fmtDateTime(m.created_at)}${m.round ? ` · <span>runda</span> <span data-no-i18n>${esc(String(m.round))}</span>` : ''}
${m.mine && !m.deleted ? `<button class="btn sm" onclick="deleteComment('${esc(m.id)}')">Usuń</button>` : ''}</div>
${m.deleted ? '<div class="faint">Komentarz usunięty.</div>' : `<div class="body" data-no-i18n>${esc(m.body)}</div>`}
</div>`).join('') : '<div class="empty">Brak komentarzy.</div>';
return `<h3>Rundy<span class="n" data-no-i18n>${rounds.length}</span></h3>
<div class="row" style="margin-bottom:10px">
${open ? `<button class="btn" onclick="openAddRound()">${svg(ICN.file)}Dodaj rundę</button>` : ''}
${pair ? `<a class="btn" href="#/rooms/${id}/compare?a=${pair[0]}&b=${pair[1]}">Porównaj</a>`
: '<span class="tiny faint">Porównanie działa dla dwóch rund w formacie Word (.docx).</span>'}
</div>
<div class="tablewrap"><table><thead><tr>
<th>Runda</th><th>Strona</th><th>Notatka</th><th>Dodał</th><th>Kiedy</th><th>Plik</th>
</tr></thead><tbody>${rows}</tbody></table></div>
<h3 style="margin-top:18px">Komentarze zespołu</h3>
<div class="tiny faint" style="margin-bottom:8px">Widzą je tylko uczestnicy pokoju; druga strona nie.</div>
<div class="thread">${thread}</div>
${open ? `<div class="commentform">
<textarea id="ngBody" rows="3" maxlength="10000" placeholder="Dodaj komentarz"></textarea>
<div class="row" style="margin-top:8px">
<select id="ngRound" aria-label="Dotyczy rundy"><option value="">Bez rundy</option>${
rounds.map((r) => `<option value="${esc(String(r.number))}" data-no-i18n>${esc(String(r.number))}</option>`).join('')}</select>
<div class="spacer"></div>
<button class="btn primary" onclick="addComment()">Dodaj komentarz</button>
</div></div>` : ''}`;
}
function peopleBody() {
const { room, people } = neg;
const rows = people.map((p) => `<tr>
<td data-no-i18n>${esc(p.name || '—')}</td>
<td>${p.owner ? '<span class="chip">właściciel</span>' : ''}</td>
<td>${room.may_manage && !p.owner ? `<button class="btn sm" onclick="removePerson('${esc(p.user_id)}')">Usuń</button>` : ''}</td>
</tr>`).join('');
return `<h3>Uczestnicy<span class="n" data-no-i18n>${people.length}</span></h3>
<div class="tiny faint" style="margin-bottom:8px">Pokój widzą jego uczestnicy i moderatorzy modułu.</div>
<div class="tablewrap"><table><tbody>${rows}</tbody></table></div>
${room.may_manage ? `<div class="row" style="margin-top:10px">
<input id="ppEmail" type="email" placeholder="Adres e-mail" data-no-i18n />
<button class="btn" onclick="addPerson()">${svg(ICN.users)}Dodaj uczestnika</button></div>` : ''}`;
}
function redrawNegotiation() {
const box = $('negotiation');
if (box) { box.innerHTML = negotiationBody(); localize(box); }
const people = $('people');
if (people) { people.innerHTML = peopleBody(); localize(people); }
}
function openAddRound() {
modal('Dodaj rundę', '',
`<label class="field">Plik<input id="nvFile" type="file" accept=".pdf,.docx" /></label>
<label class="field" style="margin-top:12px">Czyja to wersja
<select id="nvSide"><option value="druga_strona">Druga strona</option><option value="nasza">Nasza</option></select></label>
<label class="field" style="margin-top:12px">Notatka<input id="nvNote" maxlength="500" /></label>
<div class="tiny faint" style="margin-top:8px">${neg.room.kind === 'document'
? 'Runda zapisze się w Galenie jako nowa wersja dokumentu, Twoim kontem, w tym samym formacie.'
: 'PDF albo DOCX. Plik nie zastępuje poprzednich rund.'}</div>`,
`<button class="btn" onclick="closeModal()">Anuluj</button>
<button class="btn primary" onclick="saveRecordNew()">Zapisz</button>`);
<button class="btn primary" onclick="saveRound()">Zapisz</button>`);
}
function saveRecordNew() {
function saveRound() {
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);
const file = $('nvFile').files[0];
if (!file) { toast('Wybierz plik.'); return; }
const form = new FormData();
form.append('file', file);
form.append('side', $('nvSide').value);
if ($('nvNote').value.trim()) form.append('note', $('nvNote').value.trim());
neg.rounds = await apiForm('POST', `/rooms/${encodeURIComponent(neg.room.id)}/rounds`, form);
closeModal();
toast('Zapisano.');
location.hash = '#/records/' + encodeURIComponent(r.id);
await router();
redrawNegotiation();
});
}
function openRecordEdit(id) {
function addComment() {
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>`);
const body = $('ngBody').value.trim();
if (!body) { toast('Komentarz jest pusty.'); return; }
const round = $('ngRound').value;
const comment = await api('POST', `/rooms/${encodeURIComponent(neg.room.id)}/comments`,
{ body, round: round ? Number(round) : null });
neg.comments = [...neg.comments, comment];
redrawNegotiation();
});
}
function saveRecordEdit(id) {
function deleteComment(commentId) {
if (!confirm(_tr('Usunąć ten komentarz?'))) return;
guard(async () => {
await api('PATCH', '/records/' + encodeURIComponent(id), {
name: $('reName').value,
note: $('reNote').value,
status: $('reStatus').value,
});
closeModal();
toast('Zapisano.');
await router();
const gone = await api('DELETE', `/rooms/${encodeURIComponent(neg.room.id)}/comments/${encodeURIComponent(commentId)}`);
neg.comments = neg.comments.map((m) => (m.id === gone.id ? gone : m));
redrawNegotiation();
});
}
function deleteRecord(id) {
modal('Usuń', '',
'<div class="banner warn">Tej operacji nie da się cofnąć.</div>',
function addPerson() {
guard(async () => {
const email = $('ppEmail').value.trim();
if (!email) return;
neg.people = await api('POST', `/rooms/${encodeURIComponent(neg.room.id)}/participants`, { email });
redrawNegotiation();
});
}
function removePerson(userId) {
guard(async () => {
neg.people = await api('DELETE', `/rooms/${encodeURIComponent(neg.room.id)}/participants/${encodeURIComponent(userId)}`);
redrawNegotiation();
});
}
function openRoomEdit() {
const r = neg.room;
modal('Edytuj', r.title,
`<label class="field">Tytuł<input id="reTitle" value="${esc(r.title)}" maxlength="200" /></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="closed" ${r.status === 'closed' ? 'selected' : ''}>zamknięty</option>
</select></label>`,
`<button class="btn" onclick="closeModal()">Anuluj</button>
<button class="btn danger" onclick="confirmDeleteRecord('${esc(id)}')">Usuń</button>`);
<button class="btn primary" onclick="saveRoomEdit()">Zapisz</button>`);
}
function confirmDeleteRecord(id) {
function saveRoomEdit() {
guard(async () => {
await api('DELETE', '/records/' + encodeURIComponent(id));
await api('PATCH', '/rooms/' + encodeURIComponent(neg.room.id), {
title: $('reTitle').value, note: $('reNote').value, status: $('reStatus').value });
closeModal();
toast('Zapisano.');
location.hash = '#/records';
await router();
});
}
/* Two rounds as one text (G3), from the server's paragraph diff: what the later one added
underlined in green, what it dropped struck through in red, a reworded paragraph word by word.
The arrows walk the changes. */
async function viewCompare(C, id, q) {
const rid = encodeURIComponent(id);
const [room, rounds] = await Promise.all([api('GET', `/rooms/${rid}`),
api('GET', `/rooms/${rid}/rounds`)]);
setCrumb([{ label: 'Pokoje', href: '#/rooms' }, { label: room.title, href: `#/rooms/${rid}` },
{ label: 'Porównanie rund' }]);
const pair = comparePair(rounds);
const a = Number(q.a) || (pair && pair[0]);
const b = Number(q.b) || (pair && pair[1]);
const words = rounds.filter((r) => r.format === 'docx');
const pick = (name, chosen) => `<select aria-label="${esc(_tr(name === 'a' ? 'Runda wcześniejsza' : 'Runda późniejsza'))}"
onchange="location.hash = '#/rooms/${rid}/compare?a=' + (${name === 'a' ? 'this.value' : `'${esc(String(a))}'`}) + '&b=' + (${name === 'b' ? 'this.value' : `'${esc(String(b))}'`})">${
words.map((r) => `<option value="${esc(String(r.number))}"${r.number === chosen ? ' selected' : ''}>${esc(String(r.number))} · ${esc(_tr(r.side ? SIDE_LABEL[r.side] : 'Pierwotna'))}</option>`).join('')}</select>`;
let body;
try {
if (!a || !b) throw new Error(_tr('Porównanie działa dla dwóch rund w formacie Word (.docx).'));
const d = await api('GET', `/rooms/${rid}/compare?a=${encodeURIComponent(a)}&b=${encodeURIComponent(b)}`);
body = `<div class="row" style="margin-bottom:12px">
<span><b data-no-i18n>${esc(String(d.changes))}</b> <span class="faint">zmienionych akapitów</span></span>
<div class="spacer"></div>
<button class="btn" onclick="jumpChange(-1)" aria-label="${esc(_tr('Poprzednia zmiana'))}" title="Poprzednia zmiana">↑</button>
<button class="btn" onclick="jumpChange(1)" aria-label="${esc(_tr('Następna zmiana'))}" title="Następna zmiana">↓</button>
</div>
<div class="cmpkey tiny faint"><ins>dopisane</ins> <del>usunięte</del></div>
<div class="cmp" data-no-i18n>${d.paragraphs.map(comparedParagraph).join('')}</div>`;
} catch (ex) {
if (ex.status === 401) throw ex;
body = `<div class="banner err" data-no-i18n>${esc(ex.message)}</div>`;
}
C.innerHTML = pageHead('Porównanie rund', room.title,
`<a class="btn" href="#/rooms/${rid}">Wróć do pokoju</a>`)
+ `<div class="card"><div class="row" style="margin-bottom:12px">${pick('a', a)} <span class="faint">→</span> ${pick('b', b)}</div>${body}</div>`;
cmpAt = -1;
}
function comparedParagraph(p) {
if (p.op === 'same') return `<p>${esc(p.text)}</p>`;
if (p.op === 'added') return `<p class="chg"><ins>${esc(p.text)}</ins></p>`;
if (p.op === 'removed') return `<p class="chg"><del>${esc(p.text)}</del></p>`;
return `<p class="chg">${p.parts.map(([op, text]) => (op === '+' ? `<ins>${esc(text)}</ins>`
: op === '-' ? `<del>${esc(text)}</del>` : esc(text))).join('')}</p>`;
}
let cmpAt = -1;
function jumpChange(by) {
const all = [...document.querySelectorAll('.cmp .chg')];
if (!all.length) return;
cmpAt = (cmpAt + by + all.length) % all.length;
all.forEach((el, i) => el.classList.toggle('at', i === cmpAt));
all[cmpAt].scrollIntoView({ block: 'center', behavior: 'smooth' });
}
/* ── administration ─────────────────────────────────────────────────────── */
async function viewAdmin(C) {
setCrumb([{ label: 'Administracja' }]);
@@ -723,13 +986,13 @@ function openSearch() {
const q = input.value.trim();
if (!q) { $('sres').innerHTML = ''; return; }
try {
const rows = await api('GET', '/records?q=' + encodeURIComponent(q));
const rows = await api('GET', '/rooms?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="sgroup">Pokoje</div>` + rows.slice(0, 12).map((r) =>
`<button class="sitem" onclick="closeModal();location.hash='#/rooms/${encodeURIComponent(r.id)}'">
<span class="ic">${svg(ICN.users)}</span>
<span class="sb"><span class="st" data-no-i18n>${esc(r.title)}</span>
<span class="ss" data-no-i18n>${esc(r.note || '')}</span></span></button>`).join('')
: '<div class="search-empty">Brak wyników</div>';
localize($('sres'));
} catch { $('sres').innerHTML = ''; }