feat: the other side as a guest of one room (room invite links)
Atrium#53, stage 3. The room's owner or a moderator makes a link for the counterparty: a random token shown once, of which only the sha256 is kept, valid 30 days by default (1-180), revocable. Whoever holds it, through guest.html (token after "#", sent as X-Agora-Guest, never in a logged URL): - sees that room only: its rounds (ours without internal notes or names) and the comments marked "także dla drugiej strony", plus their own; - downloads rounds; a round kept in Galena reaches them as a guest_copy, made with a person's token when inviting or sending a round while an invite is active (a guest has no Galena account); - sends a counter-round (always druga_strona, kept as Agora's own file, and negotiation.round_received still names the room's Galena document) and comments, while the room is open. Unknown, expired and revoked tokens are one and the same 404. Every guest act is audited with no actor and the invite's id. Module identity invariants hold: no app_user, no session. Revision 0006: room_invite (NO-DELETE), guest_copy, guest_invite_id on rounds and comments, comment.shared, author_id nullable with a CHECK. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -8,7 +8,7 @@ Guidance for Claude Code when working in this repository.
|
||||
M3 of the Compass split plan, 2026-11-06): a negotiation **room** on one document (`negotiation_room`),
|
||||
the **rounds** of the exchange (`negotiation_round`, Compass's `contract_version`), the team's
|
||||
internal **thread** (`negotiation_comment`, Compass's `contract_comment`), the comparison of two
|
||||
.docx rounds, and the room's **participants**. A counterparty guest is a later work package. Built on **dredd-core**, the shared substrate of this app family:
|
||||
.docx rounds, and the room's **participants**. The counterparty takes part as a **guest of one room** through a room invite (`services/guests.py`: a hashed token, no account, the `X-Agora-Guest` header, `guest.html`; it sees our rounds without notes or names and only the comments marked for it; a Galena round reaches it as a `guest_copy`). Built on **dredd-core**, the shared substrate of this app family:
|
||||
identity, sessions, auth, the access-control resolver, the org tree, audit and the security
|
||||
primitives are an installed dependency, not source in this repo. Stack: **FastAPI + SQLAlchemy 2
|
||||
+ Alembic + PostgreSQL 16 / 17**, Argon2id auth + server-side cookie sessions, a
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"""The other side as a guest of one room (Atrium#53, stage 3): `room_invite`, and who sent a round or
|
||||
wrote a comment through it.
|
||||
|
||||
* `room_invite` and `guest_copy` (a Galena round copied for the guests), each created from the
|
||||
metadata when this schema has none (`0001` builds them on a fresh database already), checked in
|
||||
`current_schema()` only, as `0005` does.
|
||||
* `negotiation_round.guest_invite_id` and `negotiation_comment.guest_invite_id`, `ADD COLUMN IF NOT
|
||||
EXISTS`, each referencing the invite.
|
||||
* `negotiation_comment.shared` (false): a comment the team writes FOR the other side; the thread is
|
||||
otherwise the team's alone, and a guest sees only shared comments and their own.
|
||||
* A guest's comment has no `author_id`: the column loses NOT NULL, and the CHECK
|
||||
`ck_negotiation_comment_author` (an author or an invite, always one) is put in its place, dropped
|
||||
`IF EXISTS` first so a second run changes nothing.
|
||||
* The runtime grants again, `room_invite` NO-DELETE (`models.NO_DELETE_TABLES`): revoking stamps it.
|
||||
|
||||
Downgrade refuses while anything a guest sent is in the database (it would be orphaned), then takes
|
||||
all of this back.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dredd_core.schema import 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 = "0006"
|
||||
down_revision = "0005"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
INVITE = "room_invite"
|
||||
COPY = "guest_copy"
|
||||
CHECK = "ck_negotiation_comment_author"
|
||||
|
||||
|
||||
def _grants() -> str:
|
||||
return runtime_grants_sql(get_settings().db_app_role, append_only=APPEND_ONLY_TABLES,
|
||||
no_delete=NO_DELETE_TABLES)
|
||||
|
||||
|
||||
def _exists(bind, table: str) -> bool:
|
||||
return bind.execute(text("SELECT to_regclass(quote_ident(current_schema()) || '.' || :t) "
|
||||
"IS NOT NULL"), {"t": table}).scalar()
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
if op.get_context().as_sql:
|
||||
op.execute(_grants())
|
||||
return
|
||||
bind = op.get_bind()
|
||||
missing = [Base.metadata.tables[t] for t in (INVITE, COPY) if not _exists(bind, t)]
|
||||
if missing:
|
||||
Base.metadata.create_all(bind=bind, tables=missing, checkfirst=False)
|
||||
for table in ("negotiation_round", "negotiation_comment"):
|
||||
op.execute(f"ALTER TABLE {table} ADD COLUMN IF NOT EXISTS guest_invite_id uuid "
|
||||
f"REFERENCES {INVITE}(id)")
|
||||
op.execute("ALTER TABLE negotiation_comment ADD COLUMN IF NOT EXISTS shared boolean NOT NULL "
|
||||
"DEFAULT false")
|
||||
op.execute("ALTER TABLE negotiation_comment ALTER COLUMN author_id DROP NOT NULL")
|
||||
op.execute(f"ALTER TABLE negotiation_comment DROP CONSTRAINT IF EXISTS {CHECK}")
|
||||
op.execute(f"ALTER TABLE negotiation_comment ADD CONSTRAINT {CHECK} "
|
||||
"CHECK (author_id IS NOT NULL OR guest_invite_id IS NOT NULL)")
|
||||
op.execute(_grants())
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
sent = sum(bind.execute(text(f"SELECT count(*) FROM {t} WHERE guest_invite_id IS NOT NULL"))
|
||||
.scalar() for t in ("negotiation_round", "negotiation_comment"))
|
||||
if sent:
|
||||
raise RuntimeError(f"guest invites: {sent} round(s)/comment(s) came from a guest; they "
|
||||
"would lose their sender. Nothing was changed.")
|
||||
op.execute(f"ALTER TABLE negotiation_comment DROP CONSTRAINT IF EXISTS {CHECK}")
|
||||
op.execute("ALTER TABLE negotiation_comment ALTER COLUMN author_id SET NOT NULL")
|
||||
for table in ("negotiation_round", "negotiation_comment"):
|
||||
op.execute(f"ALTER TABLE {table} DROP COLUMN IF EXISTS guest_invite_id")
|
||||
op.execute("ALTER TABLE negotiation_comment DROP COLUMN IF EXISTS shared")
|
||||
op.execute(f"DROP TABLE IF EXISTS {COPY}")
|
||||
op.execute(f"DROP TABLE IF EXISTS {INVITE}")
|
||||
+2
-2
@@ -22,7 +22,7 @@ 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, health, rooms, stats, users
|
||||
from .routers import admin, auth, dashboard, guest, health, rooms, stats, users
|
||||
|
||||
API_PREFIX = "/api/v1"
|
||||
|
||||
@@ -118,7 +118,7 @@ if settings.cors_origins_list:
|
||||
|
||||
for router in (
|
||||
health.router, auth.router, users.router, admin.router,
|
||||
rooms.router, dashboard.router, stats.router,
|
||||
rooms.router, guest.router, dashboard.router, stats.router,
|
||||
):
|
||||
app.include_router(router, prefix=API_PREFIX)
|
||||
|
||||
|
||||
@@ -47,6 +47,8 @@ from .negotiation import (
|
||||
NegotiationParticipant,
|
||||
NegotiationRoom,
|
||||
NegotiationRound,
|
||||
GuestCopy,
|
||||
RoomInvite,
|
||||
)
|
||||
|
||||
#: The tables that belong to the platform, not to this app, when it is a module of it: the shared
|
||||
@@ -68,7 +70,8 @@ APPEND_ONLY_TABLES: tuple[str, ...] = ("audit_log", "module_event", "module_even
|
||||
#: The runtime role may never DELETE or TRUNCATE (a decision that must survive; supersede it instead).
|
||||
#: 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")
|
||||
NO_DELETE_TABLES: tuple[str, ...] = ("negotiation_room", "negotiation_round", "negotiation_comment",
|
||||
"room_invite")
|
||||
|
||||
__all__ = [
|
||||
"Base", "TimestampMixin", "UUIDPkMixin", "SafeInet", "pg_enum",
|
||||
@@ -78,6 +81,7 @@ __all__ = [
|
||||
# shared=SHARED_IDENTITY_TABLES)` would be excluding a name this app never imported.
|
||||
"AppUser", "Session", "ModulePermission", "AppSetting", "AuditLog",
|
||||
"NegotiationRoom", "NegotiationParticipant", "NegotiationRound", "NegotiationComment",
|
||||
"RoomInvite", "GuestCopy",
|
||||
"ModuleEvent", "EventCursor", "EventReceipt", "SHARED_TABLES",
|
||||
"APPEND_ONLY_TABLES", "NO_DELETE_TABLES",
|
||||
]
|
||||
|
||||
@@ -40,6 +40,7 @@ from sqlalchemy import (
|
||||
Integer,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
Uuid,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
@@ -105,6 +106,8 @@ class NegotiationRound(UUIDPkMixin, SubjectRefMixin, Base):
|
||||
#: 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"))
|
||||
#: Sent by the other side through a room invite (a guest, no account): `created_by` is NULL.
|
||||
guest_invite_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("room_invite.id"))
|
||||
created_at: Mapped[dt.datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=text("now()")
|
||||
)
|
||||
@@ -125,11 +128,76 @@ class NegotiationComment(UUIDPkMixin, Base):
|
||||
)
|
||||
#: 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)
|
||||
#: A person here, or NULL for the other side writing through a room invite (`guest_invite_id`).
|
||||
author_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
|
||||
guest_invite_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("room_invite.id"))
|
||||
#: Seen by the other side too (their own always are). The thread is otherwise the team's alone.
|
||||
shared: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("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"),)
|
||||
__table_args__ = (
|
||||
Index("ix_negotiation_comment_room", "room_id", "created_at"),
|
||||
CheckConstraint("author_id IS NOT NULL OR guest_invite_id IS NOT NULL", name="author"),
|
||||
)
|
||||
|
||||
|
||||
class RoomInvite(UUIDPkMixin, Base):
|
||||
"""A link for the other side of one room (Atrium#53, stage 3): no account, no session.
|
||||
|
||||
Whoever holds the link reads that room's rounds and comments, sends a counter-round and comments,
|
||||
and nothing else - no other room, no list, no participants. Only the token's sha256 is kept (the
|
||||
link is shown once, when it is made); it ends at `expires_at` or when revoked. Evidence of who
|
||||
could act in the room, so `NO_DELETE`: revoking stamps `revoked_at`.
|
||||
"""
|
||||
|
||||
__tablename__ = "room_invite"
|
||||
|
||||
room_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("negotiation_room.id", ondelete="RESTRICT"), nullable=False
|
||||
)
|
||||
token_sha256: Mapped[str] = mapped_column(Text, nullable=False, unique=True)
|
||||
#: Who it is for, in the inviter's words ("Kancelaria X, mec. Nowak"): shown beside what they send.
|
||||
label: 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()")
|
||||
)
|
||||
expires_at: Mapped[dt.datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
revoked_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
revoked_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
|
||||
last_used_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
__table_args__ = (
|
||||
CheckConstraint("token_sha256 ~ '^[0-9a-f]{64}$'", name="token_sha256"),
|
||||
Index("ix_room_invite_room", "room_id"),
|
||||
)
|
||||
|
||||
|
||||
class GuestCopy(UUIDPkMixin, Base):
|
||||
"""A round kept in Galena, copied into this module's own files for the room's guests.
|
||||
|
||||
A guest has no Galena account, so a round that is a Galena commit (and round 1 of a Galena
|
||||
room) cannot be read for them there. The copy is made with a PERSON's token when they invite
|
||||
or send a round while an invite is active, and it is the same bytes: `sha256` equals the
|
||||
round's own pinned hash (`document_ref.read` verified it). One per round.
|
||||
"""
|
||||
|
||||
__tablename__ = "guest_copy"
|
||||
|
||||
room_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("negotiation_room.id", ondelete="RESTRICT"), nullable=False
|
||||
)
|
||||
number: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
file_id: Mapped[uuid.UUID] = mapped_column(Uuid(as_uuid=True), nullable=False)
|
||||
sha256: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
size: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
name: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
created_at: Mapped[dt.datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=text("now()")
|
||||
)
|
||||
|
||||
__table_args__ = (UniqueConstraint("room_id", "number", name="uq_guest_copy_round"),)
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""The other side of a negotiation, as a guest of one room (`services/guests`): no account, no
|
||||
session, only the room invite's token in the `X-Agora-Guest` header. Nothing here depends on
|
||||
`get_current_user`, and nothing here reaches anything but that one room.
|
||||
|
||||
The app-wide same-origin guard (`deps.refuse_cross_site_write`) still covers the writes below: the
|
||||
guest console is this module's own page.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dredd_core.plain_files import MAX_FILE_BYTES
|
||||
from fastapi import APIRouter, Depends, File, Form, Header, Request, UploadFile
|
||||
from fastapi.responses import Response
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..deps import client_ip
|
||||
from ..errors import ValidationError
|
||||
from ..models import NegotiationRoom, RoomInvite
|
||||
from ..schemas import CommentIn
|
||||
from ..services import guests
|
||||
|
||||
router = APIRouter(prefix="/guest", tags=["guest"])
|
||||
|
||||
|
||||
def _invite(db: Session = Depends(get_db),
|
||||
x_agora_guest: str | None = Header(None)) -> tuple[RoomInvite, NegotiationRoom]:
|
||||
return guests.resolve(db, x_agora_guest)
|
||||
|
||||
|
||||
@router.get("/room")
|
||||
def room(db: Session = Depends(get_db), seat=Depends(_invite)) -> dict:
|
||||
out = guests.room_view(db, *seat)
|
||||
db.commit() # last_used_at
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/rounds/{number}/file")
|
||||
def round_file(number: int, request: Request, db: Session = Depends(get_db),
|
||||
seat=Depends(_invite)) -> Response:
|
||||
data, media, headers = guests.download(db, *seat, number, ip=client_ip(request))
|
||||
db.commit()
|
||||
return Response(content=data, media_type=media, headers=headers)
|
||||
|
||||
|
||||
@router.post("/rounds", status_code=201)
|
||||
async def add_round(request: Request, file: UploadFile = File(...),
|
||||
note: str | None = Form(None, max_length=500),
|
||||
db: Session = Depends(get_db), seat=Depends(_invite)) -> dict:
|
||||
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 guests.add_round(db, *seat, note=note, filename=file.filename or "", content=data,
|
||||
ip=client_ip(request))
|
||||
|
||||
|
||||
@router.post("/comments", status_code=201)
|
||||
def add_comment(body: CommentIn, request: Request, db: Session = Depends(get_db),
|
||||
seat=Depends(_invite)) -> dict:
|
||||
out = guests.add_comment(db, *seat, body=body.body, round_number=body.round,
|
||||
ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
@@ -17,8 +17,8 @@ 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 ..schemas import CommentIn, InviteIn, ParticipantIn, RoomDocumentIn, RoomUpdateIn
|
||||
from ..services import guests, negotiation
|
||||
from ..services import rooms as service
|
||||
|
||||
router = APIRouter(prefix="/rooms", tags=["rooms"])
|
||||
@@ -148,7 +148,8 @@ def comments(room_id: uuid.UUID, db: Session = Depends(get_db),
|
||||
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))
|
||||
round_number=body.round, shared=body.shared,
|
||||
ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
@@ -160,3 +161,30 @@ def delete_comment(room_id: uuid.UUID, comment_id: uuid.UUID, request: Request,
|
||||
ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
# ── the other side's links (services/guests) ─────────────────────────────────
|
||||
|
||||
|
||||
@router.get("/{room_id}/invites")
|
||||
def invites(room_id: uuid.UUID, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> list[dict]:
|
||||
return guests.list_invites(db, user, room_id)
|
||||
|
||||
|
||||
@router.post("/{room_id}/invites", status_code=201)
|
||||
def create_invite(room_id: uuid.UUID, body: InviteIn, request: Request,
|
||||
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
|
||||
"""A new link for the other side; its token is in this answer and nowhere else, ever."""
|
||||
out = guests.create_invite(db, user, room_id, label=body.label, days=body.days,
|
||||
token=extract_token(request), ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@router.post("/{room_id}/invites/{invite_id}/revoke")
|
||||
def revoke_invite(room_id: uuid.UUID, invite_id: uuid.UUID, request: Request,
|
||||
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = guests.revoke_invite(db, user, room_id, invite_id, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
@@ -127,6 +127,14 @@ class ParticipantIn(BaseModel):
|
||||
class CommentIn(BaseModel):
|
||||
body: str = Field(min_length=1, max_length=10_000)
|
||||
round: int | None = Field(default=None, ge=1)
|
||||
#: Also for the other side (room invites). Ignored on a guest's own comment, which always is.
|
||||
shared: bool = False
|
||||
|
||||
|
||||
class InviteIn(BaseModel):
|
||||
"""A link for the other side of one room (`services/guests`)."""
|
||||
label: str = Field(min_length=1, max_length=200)
|
||||
days: int | None = Field(default=None, ge=1, le=180)
|
||||
|
||||
|
||||
# ── administration ────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
"""The other side of a negotiation as a guest of ONE room (Atrium#53, stage 3).
|
||||
|
||||
The counterparty has no account on the platform, and a module may not make one (it reads identity,
|
||||
the hub writes it). So access is a **room invite**: a random token the room's owner or a moderator
|
||||
makes, shown once as a link, of which only the sha256 is kept. Whoever holds it, until it expires or
|
||||
is revoked, may:
|
||||
|
||||
* read that room: its title, the rounds (and download them) and the comments;
|
||||
* send a counter-round (always the other side's: `druga_strona`) while the room is open;
|
||||
* write a comment.
|
||||
|
||||
Nothing else: no other room, no participant list, no internal note, no search. The token travels in
|
||||
the `X-Agora-Guest` header, never in a URL the server sees (the console link carries it after `#`),
|
||||
so it lands in no access log. A guest's round is this module's own file even on a Galena room (a
|
||||
guest has no Galena account; `negotiation.new_round`), and `negotiation.round_received` still names
|
||||
the room's document, so the contract card moves to negotiations as for any round from the other side.
|
||||
Every guest act is audited with no actor and the invite's id in the detail.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import secrets
|
||||
import uuid
|
||||
|
||||
from dredd_core import document_ref
|
||||
from dredd_core.document_ref import DocumentRef, FileRef
|
||||
from dredd_core.plain_files import response_headers
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..errors import ConflictError, NotFoundError, ValidationError
|
||||
from ..models import AppUser, NegotiationComment, NegotiationRoom, RoomInvite
|
||||
from . import audit, negotiation, rooms
|
||||
|
||||
HEADER = "X-Agora-Guest"
|
||||
DEFAULT_DAYS = 30
|
||||
MAX_DAYS = 180
|
||||
MAX_LABEL = 200
|
||||
|
||||
|
||||
def _now() -> dt.datetime:
|
||||
return dt.datetime.now(dt.UTC)
|
||||
|
||||
|
||||
def _hash(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _iso(value) -> str | None:
|
||||
return value.isoformat() if value is not None else None
|
||||
|
||||
|
||||
def invite_out(invite: RoomInvite, db: DbSession) -> dict:
|
||||
now = _now()
|
||||
state = ("revoked" if invite.revoked_at is not None
|
||||
else "expired" if invite.expires_at <= now else "active")
|
||||
return {"id": str(invite.id), "label": invite.label, "state": state,
|
||||
"created_at": _iso(invite.created_at),
|
||||
"created_by_name": rooms.name_of(db, invite.created_by),
|
||||
"expires_at": _iso(invite.expires_at), "revoked_at": _iso(invite.revoked_at),
|
||||
"last_used_at": _iso(invite.last_used_at)}
|
||||
|
||||
|
||||
# ── the inside: the room's owner or a moderator ──────────────────────────────
|
||||
|
||||
|
||||
def create_invite(db: DbSession, user: AppUser, room_id: uuid.UUID, *, label: str,
|
||||
days: int | None = None, token: str | None, ip: str | None = None) -> dict:
|
||||
"""A new invite. The answer carries the token ONCE (`token`); only its hash is kept. Every round
|
||||
kept in Galena is copied for the guests now, read with the inviter's own token (a guest cannot
|
||||
read Galena); later rounds are copied as they are sent. No commit."""
|
||||
room = rooms.for_managing(db, user, room_id)
|
||||
if room.status != "open":
|
||||
raise ConflictError("Pokój jest zamknięty.", {"code": "room_closed"})
|
||||
label = (label or "").strip()
|
||||
if not label or len(label) > MAX_LABEL:
|
||||
raise ValidationError(f"Podaj, dla kogo jest zaproszenie (do {MAX_LABEL} znaków).",
|
||||
{"code": "label_invalid"})
|
||||
days = DEFAULT_DAYS if days is None else days
|
||||
if not 1 <= days <= MAX_DAYS:
|
||||
raise ValidationError(f"Zaproszenie ważne od 1 do {MAX_DAYS} dni.", {"code": "days_invalid"})
|
||||
copy_galena_rounds(db, room, token=token)
|
||||
secret = secrets.token_urlsafe(32)
|
||||
invite = RoomInvite(room_id=room.id, token_sha256=_hash(secret), label=label,
|
||||
created_by=user.id, expires_at=_now() + dt.timedelta(days=days))
|
||||
db.add(invite)
|
||||
db.flush()
|
||||
audit.record(db, action="room.invite_created", entity_type="negotiation_room", entity_id=room.id,
|
||||
actor_id=user.id, detail=str(invite.id), ip=ip)
|
||||
return {**invite_out(invite, db), "token": secret}
|
||||
|
||||
|
||||
def copy_galena_rounds(db: DbSession, room: NegotiationRoom, *, token: str | None) -> int:
|
||||
"""Copy every round of `room` that lives in Galena and has no guest copy yet, reading each with
|
||||
`token` (a person's) - `document_ref.read` proves the bytes against the round's hash."""
|
||||
made = 0
|
||||
for number in range(1, rooms.current_number(db, room) + 1):
|
||||
ref, name = negotiation.round_ref(db, room, number)
|
||||
if isinstance(ref, DocumentRef) and rooms.guest_copy(db, room, number) is None:
|
||||
data = document_ref.read(ref, files=rooms.files(), galena=rooms.galena(), token=token)
|
||||
rooms.save_guest_copy(db, room, number, data, name)
|
||||
made += 1
|
||||
return made
|
||||
|
||||
|
||||
def list_invites(db: DbSession, user: AppUser, room_id: uuid.UUID) -> list[dict]:
|
||||
room = rooms.for_managing(db, user, room_id)
|
||||
rows = db.scalars(select(RoomInvite).where(RoomInvite.room_id == room.id)
|
||||
.order_by(RoomInvite.created_at.desc(), RoomInvite.id)).all()
|
||||
return [invite_out(i, db) for i in rows]
|
||||
|
||||
|
||||
def revoke_invite(db: DbSession, user: AppUser, room_id: uuid.UUID, invite_id: uuid.UUID, *,
|
||||
ip: str | None = None) -> dict:
|
||||
room = rooms.for_managing(db, user, room_id)
|
||||
invite = db.get(RoomInvite, invite_id)
|
||||
if invite is None or invite.room_id != room.id:
|
||||
raise NotFoundError("Not found.")
|
||||
if invite.revoked_at is None:
|
||||
invite.revoked_at, invite.revoked_by = _now(), user.id
|
||||
db.flush()
|
||||
audit.record(db, action="room.invite_revoked", entity_type="negotiation_room",
|
||||
entity_id=room.id, actor_id=user.id, detail=str(invite.id), ip=ip)
|
||||
return invite_out(invite, db)
|
||||
|
||||
|
||||
# ── the guest ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def resolve(db: DbSession, token: str | None) -> tuple[RoomInvite, NegotiationRoom]:
|
||||
"""The invite and its room, or 404 for anything else - missing, unknown, expired or revoked
|
||||
look the same, so the answer says nothing about which tokens exist."""
|
||||
if not token or len(token) > 200:
|
||||
raise NotFoundError("Not found.")
|
||||
invite = db.scalar(select(RoomInvite).where(RoomInvite.token_sha256 == _hash(token)))
|
||||
if invite is None or invite.revoked_at is not None or invite.expires_at <= _now():
|
||||
raise NotFoundError("Not found.")
|
||||
room = db.get(NegotiationRoom, invite.room_id)
|
||||
if room is None:
|
||||
raise NotFoundError("Not found.")
|
||||
invite.last_used_at = _now()
|
||||
return invite, room
|
||||
|
||||
|
||||
def room_view(db: DbSession, invite: RoomInvite, room: NegotiationRoom) -> dict:
|
||||
"""What the guest sees: the room's title and state, the rounds, the comments. Not the internal
|
||||
note, not the participants, not the owner."""
|
||||
rows = db.scalars(select(NegotiationComment).where(NegotiationComment.room_id == room.id,
|
||||
NegotiationComment.shared.is_(True))
|
||||
.order_by(NegotiationComment.created_at, NegotiationComment.id)).all()
|
||||
return {"title": room.title, "status": room.status, "guest": invite.label,
|
||||
"expires_at": _iso(invite.expires_at),
|
||||
"rounds": [_for_guest(r) for r in negotiation.rounds(db, room)],
|
||||
"comments": [negotiation.comment_out(db, None, c) for c in rows]}
|
||||
|
||||
|
||||
def _for_guest(r: dict) -> dict:
|
||||
"""A round as the other side sees it: a round of ours shows no internal note and no name of who
|
||||
on our side sent it; the other side's own keep both."""
|
||||
if r.get("by_guest"):
|
||||
return r
|
||||
who = {None: "Wersja wyjściowa", "nasza": "Nasza strona", "druga_strona": "Druga strona"}
|
||||
return {**r, "note": None, "created_by_name": who.get(r.get("side"), "Nasza strona")}
|
||||
|
||||
|
||||
def download(db: DbSession, invite: RoomInvite, room: NegotiationRoom, number: int, *,
|
||||
ip: str | None = None) -> tuple[bytes, str, dict]:
|
||||
"""A round's bytes for the guest: this module's own file, or for a round kept in Galena its guest
|
||||
copy (`copy_galena_rounds`). Audited; no commit."""
|
||||
ref, name = negotiation.round_ref(db, room, number)
|
||||
if isinstance(ref, DocumentRef):
|
||||
copy = rooms.guest_copy(db, room, number)
|
||||
if copy is None:
|
||||
raise NotFoundError("Ten plik nie został jeszcze udostępniony.",
|
||||
{"code": "no_guest_copy"})
|
||||
ref = FileRef(file_id=copy.file_id, sha256=copy.sha256, size=copy.size, name=copy.name)
|
||||
data = rooms.files().read(ref)
|
||||
audit.record(db, action="room.round_downloaded", entity_type="negotiation_room",
|
||||
entity_id=room.id, actor_id=None, detail=f"{number}: gość {invite.id}", ip=ip)
|
||||
media, headers = response_headers(name, download=True)
|
||||
return data, media, headers
|
||||
|
||||
|
||||
def add_round(db: DbSession, invite: RoomInvite, room: NegotiationRoom, *, note: str | None,
|
||||
filename: str, content: bytes, ip: str | None = None) -> dict:
|
||||
"""The other side's counter-round. Commits itself (`negotiation.new_round`)."""
|
||||
row = negotiation.new_round(db, room, side="druga_strona", note=note, filename=filename,
|
||||
content=content, token=None, to_galena=False, created_by=None,
|
||||
guest=invite, ip=ip)
|
||||
return {"number": row.number}
|
||||
|
||||
|
||||
def add_comment(db: DbSession, invite: RoomInvite, room: NegotiationRoom, *, body: str,
|
||||
round_number: int | None, ip: str | None = None) -> dict:
|
||||
"""A comment from the other side, while the room is open. No commit."""
|
||||
if room.status != "open":
|
||||
raise ConflictError("Pokój jest zamknięty.", {"code": "room_closed"})
|
||||
body = (body or "").strip()
|
||||
if not body:
|
||||
raise ValidationError("Komentarz jest pusty.")
|
||||
if len(body) > negotiation.MAX_COMMENT:
|
||||
raise ValidationError(f"Komentarz ma najwyżej {negotiation.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=None,
|
||||
guest_invite_id=invite.id, shared=True, body=body)
|
||||
db.add(comment)
|
||||
db.flush()
|
||||
audit.record(db, action="room.comment_added", entity_type="negotiation_room",
|
||||
entity_id=room.id, actor_id=None, detail=f"{comment.id} (gość {invite.id})", ip=ip)
|
||||
return negotiation.comment_out(db, None, comment)
|
||||
@@ -37,7 +37,7 @@ 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 import AppUser, NegotiationComment, NegotiationRoom, NegotiationRound, RoomInvite
|
||||
from ..models.negotiation import SIDES
|
||||
from . import audit, compare, rooms, uploads
|
||||
|
||||
@@ -58,13 +58,15 @@ def _iso(value) -> str | None:
|
||||
|
||||
|
||||
def _round_out(db: DbSession, *, number: int, side: str | None, note: str | None, filename: str,
|
||||
ref, created_by, created_at) -> dict:
|
||||
ref, created_by, created_at, guest_invite_id=None) -> 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)}
|
||||
"created_by_name": (rooms.guest_name(db, guest_invite_id) if guest_invite_id
|
||||
else rooms.name_of(db, created_by)),
|
||||
"by_guest": guest_invite_id is not None, "created_at": _iso(created_at)}
|
||||
|
||||
|
||||
def _rows(db: DbSession, room: NegotiationRoom) -> list[NegotiationRound]:
|
||||
@@ -78,7 +80,7 @@ def rounds(db: DbSession, room: NegotiationRoom) -> list[dict]:
|
||||
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))]
|
||||
created_at=r.created_at, guest_invite_id=r.guest_invite_id) for r in _rows(db, room))]
|
||||
|
||||
|
||||
def round_ref(db: DbSession, room: NegotiationRoom, number: int) -> tuple[object, str]:
|
||||
@@ -145,14 +147,27 @@ def add_round(db: DbSession, *, actor: AppUser, room_id: uuid.UUID, side: str, n
|
||||
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)
|
||||
return new_round(db, room, side=side, note=note, filename=filename, content=content,
|
||||
token=token, to_galena=isinstance(room.ref, DocumentRef),
|
||||
created_by=actor.id, guest=None, ip=ip)
|
||||
|
||||
|
||||
def new_round(db: DbSession, room: NegotiationRoom, *, side: str, note: str | None, filename: str,
|
||||
content: bytes, token: str | None, to_galena: bool, created_by: uuid.UUID | None,
|
||||
guest: RoomInvite | None, ip: str | None) -> NegotiationRound:
|
||||
"""The round itself, once the caller has settled who may send it: a person (`created_by`) or the
|
||||
other side through a room invite (`guest`). Commits itself.
|
||||
|
||||
`to_galena`: the bytes become a commit on the room's Galena document, as the acting person. A
|
||||
guest has no Galena account, so a guest's round is always this module's own file - on a Galena
|
||||
room too, in the document's format, and the people here bring it into Galena if they adopt it."""
|
||||
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):
|
||||
if isinstance(room.ref, DocumentRef) 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"})
|
||||
@@ -163,28 +178,37 @@ def add_round(db: DbSession, *, actor: AppUser, room_id: uuid.UUID, side: str, n
|
||||
number = rooms.current_number(db, room) + 1
|
||||
|
||||
saved: FileRef | None = None
|
||||
copied = None
|
||||
try:
|
||||
if on_galena:
|
||||
if to_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}"
|
||||
if guest is not None:
|
||||
detail += f" (gość {guest.id})"
|
||||
row = NegotiationRound(room_id=room.id, number=number, side=side, note=note,
|
||||
original_filename=filename, created_by=actor.id)
|
||||
original_filename=filename, created_by=created_by,
|
||||
guest_invite_id=guest.id if guest is not None else None)
|
||||
row.set_ref(ref)
|
||||
db.add(row)
|
||||
db.flush()
|
||||
if to_galena and rooms.has_active_invite(db, room):
|
||||
# The room has guests, who cannot read Galena: they get this round as a copy.
|
||||
copy = rooms.save_guest_copy(db, room, number, content, rooms.ref_name(ref))
|
||||
copied = copy.file_id
|
||||
audit.record(db, action="room.round_added", entity_type="negotiation_room",
|
||||
entity_id=room.id, actor_id=actor.id, detail=detail, ip=ip)
|
||||
entity_id=room.id, actor_id=created_by, 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)
|
||||
for file_id in (saved.file_id if saved is not None else None, copied):
|
||||
if file_id is not None:
|
||||
rooms.files().delete(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
|
||||
@@ -192,10 +216,14 @@ def add_round(db: DbSession, *, actor: AppUser, room_id: uuid.UUID, side: str, n
|
||||
|
||||
|
||||
def round_event_payload(room: NegotiationRoom, number: int, ref) -> dict:
|
||||
"""Identifiers only (events.check_payload): never a title, a name or a note."""
|
||||
"""Identifiers only (events.check_payload): never a title, a name or a note. The Galena
|
||||
document is the ROOM's: a round kept as this module's own file (a guest's) still belongs to it,
|
||||
with no commit to name."""
|
||||
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}
|
||||
elif isinstance(room.ref, DocumentRef):
|
||||
payload |= {"document_id": room.ref.document_id}
|
||||
return payload
|
||||
|
||||
|
||||
@@ -224,8 +252,11 @@ def comparison(db: DbSession, user: AppUser, room_id: uuid.UUID, a: int, b: int,
|
||||
|
||||
|
||||
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),
|
||||
return {"id": str(c.id), "round": c.round,
|
||||
"author_name": (rooms.guest_name(db, c.guest_invite_id) if c.guest_invite_id
|
||||
else rooms.name_of(db, c.author_id)),
|
||||
"by_guest": c.guest_invite_id is not None, "shared": c.shared,
|
||||
"mine": user is not None and c.author_id == user.id, "body": c.body, "created_at": _iso(c.created_at),
|
||||
"deleted": c.deleted_at is not None}
|
||||
|
||||
|
||||
@@ -237,7 +268,7 @@ def comments(db: DbSession, user: AppUser, room_id: uuid.UUID) -> list[dict]:
|
||||
|
||||
|
||||
def add_comment(db: DbSession, *, actor: AppUser, room_id: uuid.UUID, body: str,
|
||||
round_number: int | None, ip: str | None = None) -> dict:
|
||||
round_number: int | None, shared: bool = False, 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()
|
||||
@@ -248,7 +279,7 @@ def add_comment(db: DbSession, *, actor: AppUser, room_id: uuid.UUID, body: str,
|
||||
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)
|
||||
shared=bool(shared), body=body)
|
||||
db.add(comment)
|
||||
db.flush()
|
||||
audit.record(db, action="room.comment_added", entity_type="negotiation_room",
|
||||
|
||||
@@ -13,6 +13,7 @@ bytes: every call there carries the person's own token.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import uuid
|
||||
from functools import lru_cache
|
||||
|
||||
@@ -25,7 +26,8 @@ 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 import (AppUser, GuestCopy, NegotiationParticipant, NegotiationRoom,
|
||||
NegotiationRound, RoomInvite)
|
||||
from ..models.negotiation import ROOM_STATUSES
|
||||
from . import audit, changes, moderation, uploads
|
||||
|
||||
@@ -99,6 +101,12 @@ def name_of(db: DbSession, user_id: uuid.UUID | None) -> str | None:
|
||||
return (user.full_name or user.email) if user else None
|
||||
|
||||
|
||||
def guest_name(db: DbSession, invite_id: uuid.UUID | None) -> str | None:
|
||||
"""The other side as the inviter named them, marked as such: what a guest sent shows by it."""
|
||||
invite = db.get(RoomInvite, invite_id) if invite_id else None
|
||||
return f"{invite.label} (druga strona)" if invite 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))
|
||||
@@ -266,3 +274,32 @@ def dashboard(db: DbSession, user: AppUser) -> dict:
|
||||
}
|
||||
return {"cards": cards, "recent": rows[:8]}
|
||||
|
||||
|
||||
|
||||
# ── copies for a room's guests (services/guests) ─────────────────────────────
|
||||
|
||||
|
||||
def has_active_invite(db: DbSession, room: NegotiationRoom) -> bool:
|
||||
return db.scalar(select(RoomInvite.id).where(
|
||||
RoomInvite.room_id == room.id, RoomInvite.revoked_at.is_(None),
|
||||
RoomInvite.expires_at > dt.datetime.now(dt.UTC)).limit(1)) is not None
|
||||
|
||||
|
||||
def guest_copy(db: DbSession, room: NegotiationRoom, number: int) -> GuestCopy | None:
|
||||
return db.scalar(select(GuestCopy).where(GuestCopy.room_id == room.id,
|
||||
GuestCopy.number == number))
|
||||
|
||||
|
||||
def save_guest_copy(db: DbSession, room: NegotiationRoom, number: int, data: bytes,
|
||||
name: str) -> GuestCopy:
|
||||
"""Keep `data` (a Galena round's verified bytes) as this module's own file for the guests. The
|
||||
caller commits; the file is removed again by the caller's rollback path if it must be."""
|
||||
existing = guest_copy(db, room, number)
|
||||
if existing is not None:
|
||||
return existing
|
||||
ref = files().save(data, name)
|
||||
copy = GuestCopy(room_id=room.id, number=number, file_id=ref.file_id, sha256=ref.sha256,
|
||||
size=ref.size, name=ref.name)
|
||||
db.add(copy)
|
||||
db.flush()
|
||||
return copy
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
"""The other side as a guest of one room (Atrium#53, stage 3). DB-free."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import types
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app.errors import NotFoundError, ValidationError
|
||||
from app.models import NO_DELETE_TABLES, NegotiationComment, RoomInvite
|
||||
from app.services import guests, negotiation
|
||||
|
||||
BACKEND = Path(__file__).resolve().parents[1]
|
||||
NOW = dt.datetime.now(dt.UTC)
|
||||
|
||||
|
||||
class _DB:
|
||||
def __init__(self, invite=None, room=None):
|
||||
self.invite, self.room, self.added = invite, room, []
|
||||
|
||||
def scalar(self, _statement):
|
||||
return self.invite
|
||||
|
||||
def get(self, model, _id):
|
||||
return self.room
|
||||
|
||||
def add(self, obj):
|
||||
self.added.append(obj)
|
||||
|
||||
def flush(self):
|
||||
for obj in self.added:
|
||||
if getattr(obj, "id", None) is None:
|
||||
obj.id = uuid.uuid4()
|
||||
|
||||
|
||||
def _invite(**over):
|
||||
kw = dict(id=uuid.uuid4(), room_id=uuid.uuid4(), token_sha256=guests._hash("t"),
|
||||
label="Kancelaria X", expires_at=NOW + dt.timedelta(days=1), revoked_at=None,
|
||||
last_used_at=None)
|
||||
kw.update(over)
|
||||
return types.SimpleNamespace(**kw)
|
||||
|
||||
|
||||
def test_a_live_invite_opens_its_room_and_is_stamped():
|
||||
room = types.SimpleNamespace(id=uuid.uuid4())
|
||||
invite = _invite()
|
||||
got = guests.resolve(_DB(invite, room), "t")
|
||||
assert got == (invite, room) and invite.last_used_at is not None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("token, invite", [
|
||||
(None, None), ("", None), ("x" * 201, None), ("t", None),
|
||||
("t", _invite(revoked_at=NOW)), ("t", _invite(expires_at=NOW - dt.timedelta(seconds=1))),
|
||||
])
|
||||
def test_missing_unknown_expired_or_revoked_is_one_and_the_same_404(token, invite):
|
||||
with pytest.raises(NotFoundError):
|
||||
guests.resolve(_DB(invite, types.SimpleNamespace(id=uuid.uuid4())), token)
|
||||
|
||||
|
||||
def test_only_the_tokens_hash_is_kept_and_the_token_shown_once(monkeypatch):
|
||||
room = types.SimpleNamespace(id=uuid.uuid4(), status="open")
|
||||
monkeypatch.setattr(guests.rooms, "for_managing", lambda *a: room)
|
||||
monkeypatch.setattr(guests, "copy_galena_rounds", lambda *a, **k: 0)
|
||||
monkeypatch.setattr(guests.audit, "record", lambda *a, **k: None)
|
||||
monkeypatch.setattr(guests.rooms, "name_of", lambda *a: None)
|
||||
db = _DB()
|
||||
out = guests.create_invite(db, types.SimpleNamespace(id=uuid.uuid4()), room.id,
|
||||
label=" Kancelaria X ", token="person")
|
||||
[row] = db.added
|
||||
assert isinstance(row, RoomInvite) and row.token_sha256 == guests._hash(out["token"])
|
||||
assert out["token"] not in repr(vars(row)) and row.label == "Kancelaria X"
|
||||
with pytest.raises(ValidationError):
|
||||
guests.create_invite(db, None, room.id, label="x", days=181, token=None)
|
||||
|
||||
|
||||
def test_our_rounds_show_the_guest_no_note_and_no_name():
|
||||
ours = {"number": 2, "side": "nasza", "note": "nie ustępujemy w § 3", "created_by_name": "Ada",
|
||||
"by_guest": False}
|
||||
theirs = {"number": 3, "side": "druga_strona", "note": "propozycja", "by_guest": True,
|
||||
"created_by_name": "Kancelaria X (druga strona)"}
|
||||
assert guests._for_guest(ours)["note"] is None
|
||||
assert guests._for_guest(ours)["created_by_name"] == "Nasza strona"
|
||||
assert guests._for_guest(theirs) == theirs
|
||||
|
||||
|
||||
def test_the_guest_reads_only_shared_comments():
|
||||
import inspect
|
||||
assert "NegotiationComment.shared.is_(True)" in inspect.getsource(guests.room_view)
|
||||
|
||||
|
||||
def test_a_guests_round_names_the_rooms_document_for_the_card():
|
||||
from dredd_core.document_ref import DocumentRef, FileRef
|
||||
doc = DocumentRef(document_id=uuid.uuid4(), path="umowa.docx", commit_sha="a" * 40,
|
||||
sha256="b" * 64)
|
||||
room = types.SimpleNamespace(id=uuid.uuid4(), ref=doc)
|
||||
own = FileRef(file_id=uuid.uuid4(), sha256="c" * 64, size=1, name="umowa.docx")
|
||||
payload = negotiation.round_event_payload(room, 3, own)
|
||||
assert payload["document_id"] == doc.document_id and "commit_sha" not in payload
|
||||
|
||||
|
||||
def test_invites_are_evidence_and_0006_is_idempotent():
|
||||
assert "room_invite" in NO_DELETE_TABLES
|
||||
assert NegotiationComment.__table__.c.author_id.nullable
|
||||
source = (BACKEND / "alembic" / "versions" / "0006_guest_invites.py").read_text(encoding="utf-8")
|
||||
for needle in ("ADD COLUMN IF NOT EXISTS guest_invite_id", "DROP CONSTRAINT IF EXISTS",
|
||||
"ADD COLUMN IF NOT EXISTS shared", "runtime_grants_sql"):
|
||||
assert needle in source
|
||||
+49
-6
@@ -254,7 +254,7 @@ const I18N = {
|
||||
'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.',
|
||||
'Widzą je tylko uczestnicy pokoju; druga strona tylko te oznaczone dla niej.': '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',
|
||||
@@ -647,7 +647,8 @@ async function viewRoom(C, 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 });
|
||||
const invites = room.may_manage ? await api('GET', `/rooms/${rid}/invites`).catch(() => []) : [];
|
||||
Object.assign(neg, { room, rounds, comments, people, invites });
|
||||
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>` : '')
|
||||
@@ -680,7 +681,7 @@ function negotiationBody() {
|
||||
<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>` : ''}
|
||||
<div class="tiny faint"><span data-no-i18n>${esc(m.author_name || '—')}</span>${m.by_guest ? ' <span class="chip">druga strona</span>' : m.shared ? ' <span class="chip">widzi druga strona</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>';
|
||||
@@ -694,13 +695,14 @@ function negotiationBody() {
|
||||
<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="tiny faint" style="margin-bottom:8px">Widzą je tylko uczestnicy pokoju; druga strona tylko te oznaczone dla niej.</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>
|
||||
<label class="check"><input type="checkbox" id="ngShared" /> <span>Także dla drugiej strony</span></label>
|
||||
<div class="spacer"></div>
|
||||
<button class="btn primary" onclick="addComment()">Dodaj komentarz</button>
|
||||
</div></div>` : ''}`;
|
||||
@@ -718,7 +720,48 @@ function peopleBody() {
|
||||
<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>` : ''}`;
|
||||
<button class="btn" onclick="addPerson()">${svg(ICN.users)}Dodaj uczestnika</button></div>` : ''}
|
||||
${room.may_manage ? invitesBody() : ''}`;
|
||||
}
|
||||
|
||||
/* Links for the other side (services/guests): one room, no account. The link is shown once. */
|
||||
const INVITE_STATE = { active: 'aktywny', expired: 'wygasł', revoked: 'unieważniony' };
|
||||
function invitesBody() {
|
||||
const rows = (neg.invites || []).map((i) => `<tr>
|
||||
<td data-no-i18n>${esc(i.label)}</td>
|
||||
<td>${esc(INVITE_STATE[i.state] || i.state)}</td>
|
||||
<td class="faint tiny"><span>do</span> ${fmtDateTime(i.expires_at)}</td>
|
||||
<td>${i.state === 'active' ? `<button class="btn sm" onclick="revokeInvite('${esc(i.id)}')">Unieważnij</button>` : ''}</td>
|
||||
</tr>`).join('');
|
||||
return `<h3 style="margin-top:18px">Druga strona</h3>
|
||||
<div class="tiny faint" style="margin-bottom:8px">Link dla drugiej strony: widzi rundy i komentarze oznaczone dla niej, może wgrać swoją rundę i komentować. Bez konta, tylko ten pokój.</div>
|
||||
${rows ? `<div class="tablewrap"><table><tbody>${rows}</tbody></table></div>` : ''}
|
||||
${neg.room.status === 'open' ? `<div class="row" style="margin-top:10px">
|
||||
<input id="ivLabel" maxlength="200" placeholder="Dla kogo (np. Kancelaria X)" />
|
||||
<button class="btn" onclick="createInvite()">${svg(ICN.users)}Utwórz link</button></div>` : ''}`;
|
||||
}
|
||||
|
||||
function createInvite() {
|
||||
guard(async () => {
|
||||
const label = $('ivLabel').value.trim();
|
||||
if (!label) { toast('Podaj, dla kogo jest link.'); return; }
|
||||
const inv = await api('POST', `/rooms/${encodeURIComponent(neg.room.id)}/invites`, { label });
|
||||
const link = new URL('guest.html#' + inv.token, document.baseURI).href;
|
||||
neg.invites = await api('GET', `/rooms/${encodeURIComponent(neg.room.id)}/invites`);
|
||||
redrawNegotiation();
|
||||
modal('Link dla drugiej strony', '',
|
||||
`<div class="banner warn">Link jest pokazany tylko teraz. Przekaż go drugiej stronie bezpiecznym kanałem.</div>
|
||||
<input class="mono" readonly value="${esc(link)}" onclick="this.select()" style="width:100%" data-no-i18n />`,
|
||||
'<button class="btn primary" onclick="closeModal()">Gotowe</button>');
|
||||
});
|
||||
}
|
||||
|
||||
function revokeInvite(id) {
|
||||
guard(async () => {
|
||||
await api('POST', `/rooms/${encodeURIComponent(neg.room.id)}/invites/${encodeURIComponent(id)}/revoke`);
|
||||
neg.invites = await api('GET', `/rooms/${encodeURIComponent(neg.room.id)}/invites`);
|
||||
redrawNegotiation();
|
||||
});
|
||||
}
|
||||
|
||||
function redrawNegotiation() {
|
||||
@@ -762,7 +805,7 @@ function addComment() {
|
||||
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 });
|
||||
{ body, round: round ? Number(round) : null, shared: !!($('ngShared') && $('ngShared').checked) });
|
||||
neg.comments = [...neg.comments, comment];
|
||||
redrawNegotiation();
|
||||
});
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
<!doctype html>
|
||||
<html lang="pl">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Agora — negocjacje</title>
|
||||
<meta name="robots" content="noindex" />
|
||||
<meta name="referrer" content="no-referrer" />
|
||||
<link rel="icon" type="image/svg+xml" href="favicon.svg" />
|
||||
<link rel="stylesheet" href="app.css" />
|
||||
</head>
|
||||
<body>
|
||||
<!-- The other side of a negotiation, as a guest of ONE room (backend/app/services/guests.py).
|
||||
The link's token comes after "#", so no server ever logs it; guest.js sends it in the
|
||||
X-Agora-Guest header and nothing else of the console runs here. -->
|
||||
<main class="guest" id="guest">
|
||||
<div class="empty" id="gLoading">Wczytuję…</div>
|
||||
</main>
|
||||
<script src="guest.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,102 @@
|
||||
/* The other side of a negotiation (services/guests.py): one room, through the invite's token.
|
||||
No account, no session, no cookie: the token (after "#" in the link) rides in X-Agora-Guest.
|
||||
Everything shown goes through esc(); nothing anyone uploaded is rendered here (downloads only). */
|
||||
'use strict';
|
||||
|
||||
const API = new URL('api/v1', document.baseURI).href;
|
||||
const TOKEN = decodeURIComponent((location.hash || '').replace(/^#/, ''));
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const esc = (v) => String(v ?? '').replace(/[&<>"']/g, (c) =>
|
||||
({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const when = (iso) => (iso ? new Date(iso).toLocaleString('pl-PL') : '');
|
||||
|
||||
async function call(method, path, body, form) {
|
||||
const opt = { method, headers: { 'X-Agora-Guest': TOKEN }, credentials: 'omit' };
|
||||
if (form) opt.body = form;
|
||||
else if (body !== undefined) { opt.headers['Content-Type'] = 'application/json'; opt.body = JSON.stringify(body); }
|
||||
const res = await fetch(API + path, opt);
|
||||
if (!res.ok) {
|
||||
let detail = 'HTTP ' + res.status;
|
||||
try { const d = await res.json(); detail = d.detail || d.title || detail; } catch { /* not JSON */ }
|
||||
const err = new Error(detail);
|
||||
err.status = res.status;
|
||||
throw err;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
async function download(number, name) {
|
||||
try {
|
||||
const res = await call('GET', '/guest/rounds/' + encodeURIComponent(number) + '/file');
|
||||
const a = document.createElement('a');
|
||||
a.href = URL.createObjectURL(await res.blob());
|
||||
a.download = name || 'runda';
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
setTimeout(() => { URL.revokeObjectURL(a.href); a.remove(); }, 1000);
|
||||
} catch (ex) { alert(ex.message); }
|
||||
}
|
||||
|
||||
const SIDE = { nasza: 'nasza strona', druga_strona: 'druga strona' };
|
||||
|
||||
function render(room) {
|
||||
const open = room.status === 'open';
|
||||
const rounds = room.rounds.map((r) => `<tr>
|
||||
<td>${esc(r.number)}</td>
|
||||
<td>${esc(r.side ? SIDE[r.side] || r.side : 'wersja wyjściowa')}</td>
|
||||
<td>${esc(r.created_by_name || '')}</td>
|
||||
<td class="faint tiny">${esc(when(r.created_at))}</td>
|
||||
<td><button class="btn sm" data-n="${esc(r.number)}" data-name="${esc(r.original_filename)}">${esc(r.original_filename)}</button></td>
|
||||
</tr>`).join('');
|
||||
const thread = room.comments.length ? room.comments.map((c) => `<div class="comment">
|
||||
<div class="tiny faint">${esc(c.author_name || '')} · ${esc(when(c.created_at))}${c.round ? ' · runda ' + esc(c.round) : ''}</div>
|
||||
${c.deleted ? '<div class="faint">Komentarz usunięty.</div>' : `<div class="body">${esc(c.body)}</div>`}
|
||||
</div>`).join('') : '<div class="empty">Brak komentarzy.</div>';
|
||||
$('guest').innerHTML = `<div class="page">
|
||||
<div class="page-head"><div><h1>${esc(room.title)}</h1>
|
||||
<div class="sub">Zaproszenie dla: ${esc(room.guest)} · ważne do ${esc(when(room.expires_at))}${open ? '' : ' · pokój zamknięty'}</div></div></div>
|
||||
<div class="card"><h3>Rundy</h3>
|
||||
<div class="tablewrap"><table><thead><tr><th>Runda</th><th>Strona</th><th>Kto</th><th>Kiedy</th><th>Plik</th></tr></thead>
|
||||
<tbody>${rounds}</tbody></table></div>
|
||||
${open ? `<div class="row" style="margin-top:12px;gap:8px;flex-wrap:wrap">
|
||||
<input id="gFile" type="file" accept=".pdf,.docx" />
|
||||
<input id="gNote" maxlength="500" placeholder="Notatka do rundy (opcjonalnie)" />
|
||||
<button class="btn primary" id="gSend">Wyślij swoją wersję</button></div>` : ''}
|
||||
</div>
|
||||
<div class="card" style="margin-top:14px"><h3>Komentarze</h3>
|
||||
<div class="thread">${thread}</div>
|
||||
${open ? `<div class="commentform"><textarea id="gBody" rows="3" maxlength="10000" placeholder="Dodaj komentarz"></textarea>
|
||||
<div class="row" style="margin-top:8px"><div class="spacer"></div><button class="btn primary" id="gComment">Dodaj komentarz</button></div></div>` : ''}
|
||||
</div></div>`;
|
||||
document.querySelectorAll('[data-n]').forEach((b) => { b.onclick = () => download(b.dataset.n, b.dataset.name); });
|
||||
if ($('gSend')) $('gSend').onclick = sendRound;
|
||||
if ($('gComment')) $('gComment').onclick = sendComment;
|
||||
}
|
||||
|
||||
async function load() {
|
||||
if (!TOKEN) { $('guest').innerHTML = '<div class="empty">Ten link jest niepełny.</div>'; return; }
|
||||
try {
|
||||
render(await (await call('GET', '/guest/room')).json());
|
||||
} catch (ex) {
|
||||
$('guest').innerHTML = `<div class="empty">${ex.status === 404
|
||||
? 'Ten link wygasł, został unieważniony albo jest nieprawidłowy.' : esc(ex.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function sendRound() {
|
||||
const f = $('gFile').files[0];
|
||||
if (!f) { alert('Wybierz plik (PDF albo DOCX).'); return; }
|
||||
const form = new FormData();
|
||||
form.append('file', f, f.name);
|
||||
const note = $('gNote').value.trim();
|
||||
if (note) form.append('note', note);
|
||||
try { await call('POST', '/guest/rounds', undefined, form); await load(); } catch (ex) { alert(ex.message); }
|
||||
}
|
||||
|
||||
async function sendComment() {
|
||||
const body = $('gBody').value.trim();
|
||||
if (!body) return;
|
||||
try { await call('POST', '/guest/comments', { body }); await load(); } catch (ex) { alert(ex.message); }
|
||||
}
|
||||
|
||||
load();
|
||||
Reference in New Issue
Block a user