feat: a signing request names the contract's party 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:
2026-11-26 19:55:35 +01:00
co-authored by Claude Opus 5.5
parent e3eeb4ff67
commit e1a5f8d423
9 changed files with 359 additions and 4 deletions
@@ -0,0 +1,112 @@
"""A signing request (the contract's party) may name its counterparty from the platform's register (spec 2026-11-25 part A).
One nullable column, `signing_request.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 = "0007"
down_revision = "0006"
branch_labels = None
depends_on = None
TABLE = "signing_request"
FK_NAME = "fk_signing_request_counterparty_id_counterparty"
INDEX_NAME = "ix_signing_request_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)
+6 -2
View File
@@ -39,7 +39,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 .signing import SigningRequest
@@ -47,7 +50,7 @@ from .signing import SigningRequest
#: 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
@@ -71,5 +74,6 @@ __all__ = [
# shared=SHARED_IDENTITY_TABLES)` would be excluding a name this app never imported.
"AppUser", "Session", "ModulePermission", "AppSetting", "AuditLog",
"SigningRequest", "ModuleEvent", "EventCursor", "EventReceipt", "SHARED_TABLES",
"Counterparty", "CounterpartyAlias", "CounterpartyContact",
"APPEND_ONLY_TABLES", "NO_DELETE_TABLES",
]
+5
View File
@@ -46,6 +46,11 @@ def _one_of(column: str, values: tuple[str, ...]) -> str:
class SigningRequest(UUIDPkMixin, TimestampMixin, SubjectRefMixin, Base):
__tablename__ = "signing_request"
#: 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)
#: Goes into the signature dictionary's /Reason.
+22 -1
View File
@@ -18,7 +18,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 RequestDocumentIn, SendIn
from ..schemas import RequestCounterpartyIn, RequestDocumentIn, SendIn
from ..services import counterparty_ref
from ..services import providers as providers_service
from ..services import signing as service
@@ -136,6 +137,26 @@ def send(request_id: uuid.UUID, body: SendIn, request: Request, db: Session = De
return out
@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 request's picker: organisations of the platform's register (read only)."""
return counterparty_ref.search(db, q, limit)
@router.put("/requests/{request_id}/counterparty")
def set_counterparty(request_id: uuid.UUID, body: RequestCounterpartyIn, request: Request,
db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
out = service.set_counterparty(db, actor=user, request_id=request_id,
counterparty_id=body.counterparty_id,
token=extract_token(request), ip=client_ip(request))
db.commit()
return out
@router.post("/requests/{request_id}/withdraw")
def withdraw(request_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
+7
View File
@@ -104,6 +104,13 @@ class GrantIn(BaseModel):
# ── signing requests ──────────────────────────────────────────────────────────
class RequestCounterpartyIn(BaseModel):
"""The contract's party from the register; `null` clears it (a PUT replaces the one value)."""
model_config = {"extra": "forbid"}
counterparty_id: uuid.UUID | None
class RequestDocumentIn(BaseModel):
"""A request on a Galena document: the project id, the file's path, the version to pin."""
document_id: uuid.UUID
+73
View File
@@ -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 signing request (the contract's party)) 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
+25 -1
View File
@@ -42,7 +42,7 @@ from sqlalchemy.orm import Session as DbSession
from ..config import get_settings
from ..errors import ConflictError, NotFoundError, ValidationError
from ..models import AppUser, SigningRequest
from . import audit, authz, moderation, pades, providers
from . import audit, authz, counterparty_ref, moderation, pades, providers
MAX_TITLE = 200
MAX_NOTE = 4000
@@ -123,6 +123,9 @@ def as_dict(db: DbSession, row: SigningRequest, user: AppUser, ctx: Viewer | Non
"id": str(row.id), "title": row.title, "note": row.note, "reason": row.reason,
"status": row.status, "ref": document_ref.to_dict(ref), "name": ref_name(ref),
"on_galena": isinstance(ref, DocumentRef),
# The contract's party from the register, for reference and the archive only: the signers
# are still described by their certificate's subject alone.
"counterparty": counterparty_ref.of(db, row.counterparty_id),
"owner_name": _name_of(db, row.owner_id), "mine": row.owner_id == user.id,
"created_at": _iso(row.created_at), "updated_at": _iso(row.updated_at),
"signed": None if row.signed_file_id is None else {
@@ -509,6 +512,27 @@ def send(db: DbSession, *, actor: AppUser, request_id: uuid.UUID, provider: str,
return as_dict(db, row, actor)
def set_counterparty(db: DbSession, *, actor: AppUser, request_id: uuid.UUID,
counterparty_id: uuid.UUID | None, token: str | None,
ip: str | None = None) -> dict:
"""Name the contract's party from the platform's register (`None` clears it), in any status:
it is a reference for the archive, never a signer. Whoever may read the request and is its owner
or a moderator; anybody else a 404. Read-only on the register. Audited when it changes. No commit."""
row = for_reading(db, actor, request_id, token=token)
if row.owner_id != actor.id and not moderation.is_moderator(db, actor):
raise NotFoundError("Not found.")
before = row.counterparty_id
row.counterparty_id = counterparty_ref.checked(db, counterparty_id, before)
if row.counterparty_id != before:
db.flush()
audit.record(db, action="signing.counterparty", entity_type="signing_request",
entity_id=row.id, actor_id=actor.id, ip=ip,
diff={"counterparty_id": [str(before) if before else None,
str(row.counterparty_id) if row.counterparty_id
else None]})
return as_dict(db, row, actor)
def withdraw(db: DbSession, *, actor: AppUser, request_id: uuid.UUID, token: str | None,
ip: str | None = None) -> dict:
"""Take a request back from the provider: `sent -> draft`. No commit."""
@@ -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 0007'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["signing_request"]
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_0007_is_guarded_and_ends_with_the_grants():
path = BACKEND / "alembic" / "versions" / "0007_request_counterparty.py"
spec = importlib.util.spec_from_file_location("rev0007", path)
rev = importlib.util.module_from_spec(spec)
spec.loader.exec_module(rev)
assert (rev.revision, rev.down_revision) == ("0007", "0006")
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
+27
View File
@@ -609,6 +609,7 @@ async function viewRequest(C, id) {
${field('Źródło', (r.on_galena ? 'Galena' : _tr('plik')) + ': ' + (r.on_galena ? r.ref.path : r.name))}
${field('Wnioskodawca', r.owner_name)}
${field('Powód podpisu', r.reason)}
<div><div class="tiny faint">Kontrahent</div><div><span data-no-i18n>${esc(r.counterparty ? r.counterparty.name : '—')}</span>${r.mine || isModerator() ? ` <button class="btn sm" onclick="openRequestParty('${rid}')">Zmień</button>` : ''}</div></div>
${field('Utworzono', fmtDateTime(r.created_at))}
${field('SHA-256', r.ref.sha256)}
</div>
@@ -625,6 +626,32 @@ async function viewRequest(C, id) {
+ '<div id="verifyOut"></div>';
}
/* The contract's party from the platform's register (spec 2026-11-25 part A): read only here, a
reference for the archive. The signers are still the certificate's subject alone. */
function openRequestParty(id) {
modal('Kontrahent', '',
`<label class="field">Szukaj w kartotece (nazwa, NIP, KRS)<input id="rpQ" maxlength="200" oninput="requestPartySearch('${esc(id)}', this.value)" /></label>
<div id="rpFound" style="margin-top:8px"></div>`,
`<button class="btn" onclick="requestPartySave('${esc(id)}', null)">Usuń powiązanie</button><button class="btn" onclick="closeModal()">Zamknij</button>`);
}
let _rpTimer = null;
function requestPartySearch(id, 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', '/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="requestPartySave('${esc(id)}', this.dataset.id)">Wybierz</button></div>`).join('')
: '<div class="empty">Nie ma takiego kontrahenta w kartotece.</div>';
}, 250);
}
async function requestPartySave(id, cid) {
try {
await api('PUT', '/requests/' + encodeURIComponent(id) + '/counterparty', { counterparty_id: cid });
closeModal(); viewRequest($('content'), id);
} catch (e) { modalError(e.message); }
}
/* An external provider by hand (SignuDoc in the Start edition): hand over, then upload the result. */
async function openSend(id) {
const manual = (await api('GET', '/providers')).filter((p) => p.manual);