feat: a room names its counterparty; the guest sees its name from the counterparty register (read only)
Spec 2026-11-25 part A (Kontrahenci), step 3: a nullable counterparty_id (RESTRICT) on the platform's register, a picker over its organisations and a PUT to set or clear it (owner or moderator, else 404). The module only reads the register and never shows counterparty_contact. Idempotent revision ending with runtime_grants_sql; standalone it creates the (empty) local register, on the platform it drops empty local copies. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,112 @@
|
||||
"""A negotiation room may name its counterparty from the platform's register (spec 2026-11-25 part A).
|
||||
|
||||
One nullable column, `negotiation_room.counterparty_id`, a foreign key on `counterparty` ON DELETE RESTRICT
|
||||
(a counterparty is archived, never deleted). This module only READS the register: it never writes a
|
||||
counterparty, and never reads or shows `counterparty_contact`.
|
||||
|
||||
* **Standalone** (`IDENTITY_SCHEMA` empty): the register's three tables live in this schema
|
||||
(`dredd_core.counterparties.create_counterparty_tables`; a fresh database already has them, `0001`
|
||||
builds from the metadata). Nothing here writes them, so standalone they stay empty unless a
|
||||
restore brings rows: the pointer is a platform feature that keeps one code path.
|
||||
`counterparty` joins NO_DELETE.
|
||||
* **On the platform**: the register is the hub's, in the identity schema (Atrium's `0012`; its env
|
||||
lists this module's runtime role as a reader and its migrator for REFERENCES). Local copies that a
|
||||
fresh `0001` built are dropped while empty (the revision refuses when they hold rows), after the
|
||||
foreign key that pointed at them; the key is then added on the unqualified `counterparty`, which
|
||||
the search_path resolves to the hub's.
|
||||
|
||||
Idempotent: catalog checks, `IF [NOT] EXISTS`. Ends with the runtime grants.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dredd_core import counterparties as cp
|
||||
from dredd_core.identity import COUNTERPARTY_TABLES
|
||||
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
|
||||
|
||||
revision = "0008"
|
||||
down_revision = "0007"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
TABLE = "negotiation_room"
|
||||
FK_NAME = "fk_negotiation_room_counterparty_id_counterparty"
|
||||
INDEX_NAME = "ix_negotiation_room_counterparty_id"
|
||||
_LOCAL_DROP_ORDER = ("counterparty_contact", "counterparty_alias", "counterparty")
|
||||
|
||||
|
||||
class Refused(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _q(name: str) -> str:
|
||||
return '"' + name.replace('"', '""') + '"'
|
||||
|
||||
|
||||
def _has_table(bind, schema: str, table: str) -> bool:
|
||||
return bool(bind.execute(text(
|
||||
"SELECT count(*) FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace "
|
||||
"WHERE n.nspname = :s AND c.relname = :t AND c.relkind IN ('r', 'p')"),
|
||||
{"s": schema, "t": table}).scalar())
|
||||
|
||||
|
||||
def _grants(no_delete: tuple[str, ...]) -> None:
|
||||
op.execute(runtime_grants_sql(get_settings().db_app_role, append_only=APPEND_ONLY_TABLES,
|
||||
no_delete=no_delete))
|
||||
|
||||
|
||||
def _link_column() -> None:
|
||||
op.execute(f"ALTER TABLE {TABLE} ADD COLUMN IF NOT EXISTS counterparty_id uuid")
|
||||
op.execute(f"ALTER TABLE {TABLE} DROP CONSTRAINT IF EXISTS {FK_NAME}")
|
||||
op.execute(f"ALTER TABLE {TABLE} ADD CONSTRAINT {FK_NAME} FOREIGN KEY (counterparty_id) "
|
||||
"REFERENCES counterparty (id) ON DELETE RESTRICT")
|
||||
op.execute(f"CREATE INDEX IF NOT EXISTS {INDEX_NAME} ON {TABLE} (counterparty_id)")
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
settings = get_settings()
|
||||
bind = op.get_bind()
|
||||
own = bind.execute(text("SELECT current_schema()")).scalar()
|
||||
if settings.shares_identity:
|
||||
identity = settings.identity_schema
|
||||
for table in sorted(COUNTERPARTY_TABLES):
|
||||
if not _has_table(bind, identity, table):
|
||||
raise Refused(f"{identity}.{table} does not exist: Atrium's revision 0012 creates "
|
||||
"the counterparty register. Migrate the hub first.")
|
||||
if _has_table(bind, own, "counterparty"):
|
||||
for table in _LOCAL_DROP_ORDER:
|
||||
if _has_table(bind, own, table) and bind.execute(
|
||||
text(f"SELECT EXISTS (SELECT 1 FROM {_q(own)}.{_q(table)})")).scalar():
|
||||
raise Refused(f"{own}.{table} holds rows, and on the platform the "
|
||||
"counterparty register is the hub's. Export them if they "
|
||||
"matter, empty the table, and run the upgrade again.")
|
||||
op.execute(f"ALTER TABLE {TABLE} DROP CONSTRAINT IF EXISTS {FK_NAME}")
|
||||
for table in _LOCAL_DROP_ORDER:
|
||||
op.execute(f"DROP TABLE IF EXISTS {_q(own)}.{_q(table)}")
|
||||
_link_column()
|
||||
_grants(NO_DELETE_TABLES)
|
||||
return
|
||||
cp.create_counterparty_tables(bind, own)
|
||||
_link_column()
|
||||
_grants((*NO_DELETE_TABLES, "counterparty"))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Drops the pointer. Standalone also the (read-only, so normally empty) register, only empty."""
|
||||
settings = get_settings()
|
||||
bind = op.get_bind()
|
||||
own = bind.execute(text("SELECT current_schema()")).scalar()
|
||||
op.execute(f"ALTER TABLE {TABLE} DROP CONSTRAINT IF EXISTS {FK_NAME}")
|
||||
op.execute(f"DROP INDEX IF EXISTS {INDEX_NAME}")
|
||||
op.execute(f"ALTER TABLE {TABLE} DROP COLUMN IF EXISTS counterparty_id")
|
||||
if not settings.shares_identity:
|
||||
for table in _LOCAL_DROP_ORDER:
|
||||
if _has_table(bind, own, table):
|
||||
if bind.execute(text(f"SELECT EXISTS (SELECT 1 FROM {_q(table)})")).scalar():
|
||||
raise Refused(f"{table} holds rows: refusing to drop the counterparty register.")
|
||||
op.execute(f"DROP TABLE {_q(table)}")
|
||||
_grants(NO_DELETE_TABLES)
|
||||
@@ -40,7 +40,10 @@ from dredd_core import (
|
||||
pg_enum,
|
||||
)
|
||||
from dredd_core.events import EventCursor, EventReceipt, ModuleEvent
|
||||
from dredd_core.identity import EVENT_TABLES, SHARED_IDENTITY_TABLES
|
||||
from dredd_core.identity import COUNTERPARTY_TABLES, EVENT_TABLES, SHARED_IDENTITY_TABLES
|
||||
# The platform's counterparty register (dredd-core 0.21.0; spec 2026-11-25 part A), READ only:
|
||||
# standalone this schema's own tables, on the platform the hub's in the identity schema.
|
||||
from dredd_core.counterparties import Counterparty, CounterpartyAlias, CounterpartyContact
|
||||
|
||||
from .negotiation import (
|
||||
NegotiationComment,
|
||||
@@ -55,7 +58,7 @@ from .negotiation import (
|
||||
#: 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
|
||||
SHARED_TABLES: frozenset[str] = SHARED_IDENTITY_TABLES | EVENT_TABLES | COUNTERPARTY_TABLES
|
||||
|
||||
# ── evidence tables: what the runtime role may never rewrite ──────────────────────────────────────
|
||||
# The runtime-grants migration (alembic/versions/0002_runtime_grants.py, and every later revision
|
||||
@@ -83,5 +86,6 @@ __all__ = [
|
||||
"NegotiationRoom", "NegotiationParticipant", "NegotiationRound", "NegotiationComment",
|
||||
"RoomInvite", "GuestCopy",
|
||||
"ModuleEvent", "EventCursor", "EventReceipt", "SHARED_TABLES",
|
||||
"Counterparty", "CounterpartyAlias", "CounterpartyContact",
|
||||
"APPEND_ONLY_TABLES", "NO_DELETE_TABLES",
|
||||
]
|
||||
|
||||
@@ -60,6 +60,11 @@ def _one_of(column: str, values: tuple[str, ...]) -> str:
|
||||
class NegotiationRoom(UUIDPkMixin, TimestampMixin, SubjectRefMixin, Base):
|
||||
__tablename__ = "negotiation_room"
|
||||
|
||||
#: The counterparty from the platform's register (spec 2026-11-25 part A), READ only here:
|
||||
#: `services/counterparty_ref.py`. RESTRICT: a counterparty is archived, never deleted.
|
||||
counterparty_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||
ForeignKey("counterparty.id", ondelete="RESTRICT"), index=True)
|
||||
|
||||
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'"))
|
||||
|
||||
@@ -17,8 +17,10 @@ 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, InviteIn, ParticipantIn, RoomDocumentIn, RoomUpdateIn
|
||||
from ..services import guests, negotiation
|
||||
from ..schemas import (
|
||||
CommentIn, InviteIn, ParticipantIn, RoomCounterpartyIn, RoomDocumentIn, RoomUpdateIn,
|
||||
)
|
||||
from ..services import counterparty_ref, guests, negotiation
|
||||
from ..services import rooms as service
|
||||
|
||||
router = APIRouter(prefix="/rooms", tags=["rooms"])
|
||||
@@ -38,6 +40,25 @@ def list_rooms(db: Session = Depends(get_db), user: AppUser = Depends(get_curren
|
||||
return service.list_rooms(db, user, q=q, status=status)
|
||||
|
||||
|
||||
@router.get("/counterparties")
|
||||
def search_counterparties(q: str | None = Query(None, max_length=200),
|
||||
limit: int = Query(20, ge=1, le=counterparty_ref.MAX_SEARCH),
|
||||
db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(get_current_user)) -> list[dict]:
|
||||
"""The room's picker: organisations of the platform's register (read only)."""
|
||||
return counterparty_ref.search(db, q, limit)
|
||||
|
||||
|
||||
@router.put("/{room_id}/counterparty")
|
||||
def set_counterparty(room_id: uuid.UUID, body: RoomCounterpartyIn, request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = service.set_counterparty(db, user, room_id, counterparty_id=body.counterparty_id,
|
||||
ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@router.post("/upload", status_code=201)
|
||||
async def create_from_file(request: Request, file: UploadFile = File(...),
|
||||
title: str | None = Form(None, max_length=200),
|
||||
|
||||
@@ -120,6 +120,13 @@ class RoomUpdateIn(BaseModel):
|
||||
status: str | None = Field(default=None, pattern="^(open|closed)$")
|
||||
|
||||
|
||||
class RoomCounterpartyIn(BaseModel):
|
||||
"""The room's counterparty from the register; `null` clears it (a PUT replaces the one value)."""
|
||||
model_config = {"extra": "forbid"}
|
||||
|
||||
counterparty_id: uuid.UUID | None
|
||||
|
||||
|
||||
class ParticipantIn(BaseModel):
|
||||
email: str = Field(min_length=3, max_length=320)
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""The platform's counterparty register, READ by this module (spec 2026-11-25 part A).
|
||||
|
||||
Sygna and Galena write the register; this module only points at one of its organisations
|
||||
(`counterparty_id` on a negotiation room) and shows its name. It never writes a counterparty and never reads
|
||||
`counterparty_contact`: the other side's people are not this module's to show. Standalone the
|
||||
register is this schema's own (empty unless restored); on the platform the hub's, through the
|
||||
search_path. The pure checks are here; the domain write that uses them is the caller's.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from dredd_core import counterparties as cp
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..errors import ValidationError
|
||||
from ..models import Counterparty
|
||||
|
||||
KIND = "organisation"
|
||||
MAX_SEARCH = 50
|
||||
|
||||
|
||||
def summary(row: Counterparty | None) -> dict[str, Any] | None:
|
||||
"""What a screen shows of a counterparty: never its contacts, address or notes."""
|
||||
if row is None:
|
||||
return None
|
||||
return {"id": str(row.id), "name": row.name, "nip": row.nip, "archived": row.archived}
|
||||
|
||||
|
||||
def of(db: DbSession, counterparty_id: uuid.UUID | None) -> dict[str, Any] | None:
|
||||
return summary(db.get(Counterparty, counterparty_id)) if counterparty_id else None
|
||||
|
||||
|
||||
def search(db: DbSession, q: str | None, limit: int = 20) -> list[dict[str, Any]]:
|
||||
"""Organisations by folded name (`search_key`) or the leading digits of a NIP / KRS; archived
|
||||
ones never offered; an empty phrase finds nothing."""
|
||||
if not 1 <= limit <= MAX_SEARCH:
|
||||
raise ValidationError(f"limit is 1..{MAX_SEARCH}.")
|
||||
key = cp.normalize(q or "")
|
||||
digits = re.sub(r"[\s-]", "", q or "")
|
||||
conditions = []
|
||||
if key:
|
||||
conditions.append(Counterparty.search_key.contains(key, autoescape=True))
|
||||
if digits.isdigit():
|
||||
conditions += [Counterparty.nip.startswith(digits, autoescape=True),
|
||||
Counterparty.krs.startswith(digits, autoescape=True)]
|
||||
if not conditions:
|
||||
return []
|
||||
rows = db.scalars(select(Counterparty)
|
||||
.where(Counterparty.kind == KIND, Counterparty.archived.is_(False),
|
||||
or_(*conditions))
|
||||
.order_by(Counterparty.name, Counterparty.id).limit(limit)).all()
|
||||
return [summary(r) for r in rows]
|
||||
|
||||
|
||||
def checked(db: DbSession, counterparty_id: uuid.UUID | None,
|
||||
current: uuid.UUID | None) -> uuid.UUID | None:
|
||||
"""`counterparty_id` when it may be pointed at: an organisation of the register, not archived
|
||||
unless it is already the `current` one. `None` (clear it) always may. Else a 422."""
|
||||
if counterparty_id is None:
|
||||
return None
|
||||
row = db.get(Counterparty, counterparty_id)
|
||||
if row is None or row.kind != KIND:
|
||||
raise ValidationError("Nie ma takiego kontrahenta.", {"code": "counterparty_unknown",
|
||||
"en": "No such counterparty."})
|
||||
if row.archived and counterparty_id != current:
|
||||
raise ValidationError("Ten kontrahent jest zarchiwizowany.",
|
||||
{"code": "counterparty_archived",
|
||||
"en": "That counterparty is archived."})
|
||||
return counterparty_id
|
||||
@@ -39,7 +39,7 @@ 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, uploads
|
||||
from . import audit, counterparty_ref, negotiation, rooms, uploads
|
||||
|
||||
HEADER = "X-Agora-Guest"
|
||||
DEFAULT_DAYS = 30 # the range itself is `schemas.InviteIn`'s
|
||||
@@ -162,12 +162,15 @@ def resolve(db: DbSession, token: str | None) -> tuple[RoomInvite, NegotiationRo
|
||||
|
||||
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, not a comment the team deleted."""
|
||||
note, not the participants, not the owner, not a comment the team deleted. The counterparty is
|
||||
its NAME from the register only: never its contacts (`counterparty_contact`), nor its numbers."""
|
||||
rows = db.scalars(select(NegotiationComment).where(NegotiationComment.room_id == room.id,
|
||||
NegotiationComment.shared.is_(True),
|
||||
NegotiationComment.deleted_at.is_(None))
|
||||
.order_by(NegotiationComment.created_at, NegotiationComment.id)).all()
|
||||
party = counterparty_ref.of(db, room.counterparty_id)
|
||||
return {"title": room.title, "status": room.status, "guest": invite.label,
|
||||
"counterparty": party["name"] if party else None,
|
||||
"expires_at": _iso(invite.expires_at),
|
||||
"rounds": [_for_guest(r) for r in negotiation.rounds(db, room)],
|
||||
"comments": [_comment_for_guest(c)
|
||||
|
||||
@@ -29,7 +29,7 @@ from ..errors import ConflictError, NotFoundError, ValidationError
|
||||
from ..models import (AppUser, GuestCopy, NegotiationParticipant, NegotiationRoom,
|
||||
NegotiationRound, RoomInvite)
|
||||
from ..models.negotiation import ROOM_STATUSES
|
||||
from . import audit, changes, moderation, uploads
|
||||
from . import audit, changes, counterparty_ref, moderation, uploads
|
||||
|
||||
MAX_TITLE = 200
|
||||
|
||||
@@ -126,6 +126,7 @@ def as_dict(db: DbSession, room: NegotiationRoom, user: AppUser) -> dict:
|
||||
"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),
|
||||
"counterparty": counterparty_ref.of(db, room.counterparty_id),
|
||||
"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),
|
||||
@@ -230,6 +231,24 @@ def update_room(db: DbSession, user: AppUser, room_id: uuid.UUID, *, title: str
|
||||
return as_dict(db, room, user)
|
||||
|
||||
|
||||
def set_counterparty(db: DbSession, user: AppUser, room_id: uuid.UUID, *,
|
||||
counterparty_id: uuid.UUID | None, ip: str | None = None) -> dict:
|
||||
"""Point the room at a counterparty of the platform's register (`None` clears it): the owner or
|
||||
a moderator, anybody else a 404. Read-only on the register (`counterparty_ref.checked`). Audited
|
||||
only when it changes. No commit."""
|
||||
room = for_managing(db, user, room_id)
|
||||
before = room.counterparty_id
|
||||
room.counterparty_id = counterparty_ref.checked(db, counterparty_id, before)
|
||||
if room.counterparty_id != before:
|
||||
db.flush()
|
||||
audit.record(db, action="room.update", entity_type="negotiation_room", entity_id=room.id,
|
||||
actor_id=user.id, ip=ip,
|
||||
diff={"counterparty_id": [str(before) if before else None,
|
||||
str(room.counterparty_id) if room.counterparty_id
|
||||
else None]})
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
"""The read-only counterparty pointer (spec 2026-11-25 part A), DB-free: the checks, what is shown
|
||||
(never the contacts), the model's key and revision 0008's shape."""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import inspect
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.errors import ValidationError
|
||||
from app.models import SHARED_TABLES, Base
|
||||
from app.services import counterparty_ref
|
||||
|
||||
BACKEND = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class _Db:
|
||||
def __init__(self, row):
|
||||
self.row = row
|
||||
|
||||
def get(self, model, key):
|
||||
return self.row if self.row is not None and self.row.id == key else None
|
||||
|
||||
|
||||
def _row(**kw):
|
||||
return SimpleNamespace(**{"id": uuid.uuid4(), "kind": "organisation", "name": "Acme",
|
||||
"nip": "5260250995", "archived": False, **kw})
|
||||
|
||||
|
||||
def test_checked_accepts_an_organisation_and_clearing():
|
||||
row = _row()
|
||||
assert counterparty_ref.checked(_Db(row), row.id, None) == row.id
|
||||
assert counterparty_ref.checked(_Db(row), None, row.id) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("row,current,code", [
|
||||
(None, None, "counterparty_unknown"),
|
||||
(_row(kind="person"), None, "counterparty_unknown"),
|
||||
(_row(archived=True), None, "counterparty_archived")])
|
||||
def test_checked_refuses(row, current, code):
|
||||
with pytest.raises(ValidationError) as err:
|
||||
counterparty_ref.checked(_Db(row), row.id if row else uuid.uuid4(), current)
|
||||
assert err.value.extra["code"] == code
|
||||
|
||||
|
||||
def test_an_archived_one_already_named_stays():
|
||||
row = _row(archived=True)
|
||||
assert counterparty_ref.checked(_Db(row), row.id, row.id) == row.id
|
||||
|
||||
|
||||
def test_summary_shows_no_contact_data():
|
||||
out = counterparty_ref.summary(_row(email="x@y", phone="1", address="a", notes="n"))
|
||||
assert set(out) == {"id", "name", "nip", "archived"}
|
||||
assert counterparty_ref.summary(None) is None
|
||||
|
||||
|
||||
def test_search_of_nothing_asks_nothing():
|
||||
assert counterparty_ref.search(None, " ") == []
|
||||
with pytest.raises(ValidationError):
|
||||
counterparty_ref.search(None, "x", limit=0)
|
||||
|
||||
|
||||
def test_the_pointer_is_a_restrict_key_and_the_register_is_the_platforms():
|
||||
table = Base.metadata.tables["negotiation_room"]
|
||||
fk = next(fk for fk in table.foreign_keys if fk.column.table.name == "counterparty")
|
||||
assert fk.ondelete == "RESTRICT" and table.c.counterparty_id.nullable
|
||||
assert {"counterparty", "counterparty_alias", "counterparty_contact"} <= SHARED_TABLES
|
||||
|
||||
|
||||
def test_revision_0008_is_guarded_and_ends_with_the_grants():
|
||||
path = BACKEND / "alembic" / "versions" / "0008_room_counterparty.py"
|
||||
spec = importlib.util.spec_from_file_location("rev0008", path)
|
||||
rev = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(rev)
|
||||
assert (rev.revision, rev.down_revision) == ("0008", "0007")
|
||||
up = inspect.getsource(rev.upgrade)
|
||||
assert up.count("_grants(") == 2 and "holds rows" in up
|
||||
col = inspect.getsource(rev._link_column)
|
||||
assert "IF NOT EXISTS" in col and "ON DELETE RESTRICT" in col
|
||||
@@ -64,7 +64,8 @@ def test_a_live_invite_opens_its_room_and_is_stamped_at_most_once_a_minute():
|
||||
|
||||
@pytest.mark.parametrize("status", ["accepted", "closed"])
|
||||
def test_an_accepted_or_closed_room_stays_readable_but_not_writable(status, monkeypatch):
|
||||
room = types.SimpleNamespace(id=uuid.uuid4(), status=status, title="Umowa", ref=None)
|
||||
room = types.SimpleNamespace(id=uuid.uuid4(), status=status, title="Umowa", ref=None,
|
||||
counterparty_id=None)
|
||||
invite = _invite()
|
||||
assert guests.resolve(_DB(invite, room), "t") == (invite, room)
|
||||
monkeypatch.setattr(guests.negotiation, "rounds", lambda *a: [])
|
||||
@@ -150,7 +151,8 @@ def test_a_guest_sees_no_internal_name_hash_or_commit():
|
||||
|
||||
|
||||
def test_the_guest_reads_only_shared_comments_and_never_a_deleted_one(monkeypatch):
|
||||
room = types.SimpleNamespace(id=uuid.uuid4(), status="open", title="Umowa")
|
||||
room = types.SimpleNamespace(id=uuid.uuid4(), status="open", title="Umowa",
|
||||
counterparty_id=None)
|
||||
invite = _invite()
|
||||
statements = []
|
||||
live = NegotiationComment(id=uuid.uuid4(), room_id=room.id, author_id=uuid.uuid4(),
|
||||
@@ -226,3 +228,19 @@ def test_invites_are_evidence_and_0006_is_idempotent():
|
||||
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
|
||||
|
||||
|
||||
def test_the_guest_sees_the_counterpartys_name_and_nothing_else_of_it(monkeypatch):
|
||||
"""Spec 2026-11-25 part A: the invitation names the counterparty from the register; its
|
||||
contacts and numbers never reach the other side."""
|
||||
cid = uuid.uuid4()
|
||||
room = types.SimpleNamespace(id=uuid.uuid4(), status="open", title="Umowa", counterparty_id=cid)
|
||||
db = _DB(_invite(), room)
|
||||
db.scalars = lambda _s: types.SimpleNamespace(all=lambda: [])
|
||||
monkeypatch.setattr(guests.negotiation, "rounds", lambda *a: [])
|
||||
monkeypatch.setattr(guests.counterparty_ref, "of", lambda _db, key: {
|
||||
"id": str(key), "name": "Acme sp. z o.o.", "nip": "5260250995", "archived": False}
|
||||
if key == cid else None)
|
||||
out = guests.room_view(db, _invite(), room)
|
||||
assert out["counterparty"] == "Acme sp. z o.o."
|
||||
assert "5260250995" not in repr(out)
|
||||
|
||||
@@ -209,6 +209,13 @@ const I18N = {
|
||||
'Anuluj': 'Cancel',
|
||||
'Usuń': 'Delete',
|
||||
'Edytuj': 'Edit',
|
||||
'Usuń powiązanie': 'Unlink',
|
||||
'Zmień': 'Change',
|
||||
'Kontrahent': 'Counterparty',
|
||||
'Wybierz': 'Choose',
|
||||
'Obecnie:': 'Now:',
|
||||
'Szukaj w kartotece (nazwa, NIP, KRS)': 'Search the register (name, NIP, KRS)',
|
||||
'Nie ma takiego kontrahenta w kartotece.': 'No such counterparty in the register.',
|
||||
'Wczytywanie…': 'Loading…',
|
||||
'Brak wyników': 'Nothing found',
|
||||
'Nie znaleziono strony.': 'Page not found.',
|
||||
@@ -685,6 +692,7 @@ async function viewRoom(C, id) {
|
||||
<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>
|
||||
<div style="margin-top:12px"><div class="tiny faint">Kontrahent</div><div><span data-no-i18n>${esc(room.counterparty ? room.counterparty.name : '—')}</span>${room.may_manage ? ` <button class="btn sm" onclick="openRoomParty()">Zmień</button>` : ''}</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>`;
|
||||
@@ -864,6 +872,34 @@ function removePerson(userId) {
|
||||
});
|
||||
}
|
||||
|
||||
/* The room's counterparty from the platform's register (spec 2026-11-25 part A): read only here,
|
||||
Galena and Sygna write the register. The other side never sees its contacts. */
|
||||
function openRoomParty() {
|
||||
const cur = neg.room.counterparty;
|
||||
modal('Kontrahent', neg.room.title,
|
||||
`<div class="tiny faint">Obecnie: <span data-no-i18n>${esc(cur ? cur.name : '—')}</span></div>
|
||||
<label class="field" style="margin-top:12px">Szukaj w kartotece (nazwa, NIP, KRS)<input id="rpQ" maxlength="200" oninput="roomPartySearch(this.value)" /></label>
|
||||
<div id="rpFound" style="margin-top:8px"></div>`,
|
||||
`${cur ? '<button class="btn" onclick="roomPartySave(null)">Usuń powiązanie</button>' : ''}<button class="btn" onclick="closeModal()">Zamknij</button>`);
|
||||
}
|
||||
let _rpTimer = null;
|
||||
function roomPartySearch(q) {
|
||||
clearTimeout(_rpTimer);
|
||||
_rpTimer = setTimeout(async () => {
|
||||
const el = $('rpFound'); if (!el) return;
|
||||
if (!q.trim()) { el.innerHTML = ''; return; }
|
||||
let rows; try { rows = await api('GET', '/rooms/counterparties?q=' + encodeURIComponent(q.trim())); } catch (e) { modalError(e.message); return; }
|
||||
el.innerHTML = rows.length ? rows.map((c) => `<div style="display:flex;gap:8px;align-items:center;margin-bottom:4px"><span style="flex:1" data-no-i18n>${esc(c.name)}${c.nip ? ' · NIP ' + esc(c.nip) : ''}</span><button class="btn sm" data-id="${esc(c.id)}" onclick="roomPartySave(this.dataset.id)">Wybierz</button></div>`).join('')
|
||||
: '<div class="empty">Nie ma takiego kontrahenta w kartotece.</div>';
|
||||
}, 250);
|
||||
}
|
||||
async function roomPartySave(id) {
|
||||
try {
|
||||
neg.room = await api('PUT', `/rooms/${encodeURIComponent(neg.room.id)}/counterparty`, { counterparty_id: id });
|
||||
closeModal(); viewRoom($('content'), neg.room.id);
|
||||
} catch (e) { modalError(e.message); }
|
||||
}
|
||||
|
||||
function openRoomEdit() {
|
||||
const r = neg.room;
|
||||
modal('Edytuj', r.title,
|
||||
|
||||
+1
-1
@@ -54,7 +54,7 @@ function render(room) {
|
||||
</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="sub">${room.counterparty ? `Kontrahent: ${esc(room.counterparty)} · ` : ''}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>
|
||||
|
||||
Reference in New Issue
Block a user