K2: link organisations to the shared counterparty register (dredd-core 0.21.0)
party.counterparty_id; create/update sync an organisation through core's link_or_create when Sygna may write the register (natural persons never). Revision 0006 links existing organisations, through the hub's import door on the platform. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -253,7 +253,7 @@ jobs:
|
||||
python -m dredd_core.managed check --url "$url" --expect-schema sygna \
|
||||
--app-role sygna_app --migrator-role sygna_migrator \
|
||||
--append-only audit_log --no-delete conflict_check aml_assessment \
|
||||
--identity-schema dredd --identity-tier reader
|
||||
--identity-schema dredd --identity-tier reader --counterparties writer
|
||||
done
|
||||
- name: Everything is in schema sygna, and the evidence holds
|
||||
run: |
|
||||
|
||||
@@ -605,6 +605,8 @@ BOOTSTRAP_ADMIN_PASSWORD=… python scripts/walkthrough.py # drive the whole p
|
||||
the transition machinery to tick, and when frames are throttled it gets stuck in whichever
|
||||
state it was in. `transform` transitions; `visibility` flips instantly.
|
||||
|
||||
- **Counterparty register (dredd-core 0.21.0, revision `0006`; the Compass split's K2).** Sygna WRITES the platform's one register (`counterparty`, `counterparty_alias`, `counterparty_contact`): standalone in its own schema, on the platform in the identity schema, granted by the hub (`COUNTERPARTY_WRITER_ROLES=sygna_app`, `COUNTERPARTY_MIGRATOR_ROLES` incl. `sygna_migrator`; check with `--counterparties writer`). A party is not a counterparty: `party.counterparty_id` (RESTRICT) links an **organisation** to the one it is; natural persons are never put in the register (GDPR). `services/parties.sync_counterparty` runs on create/update: no-op when `counterparties.writable(db)` is false, links via core `link_or_create` (NIP, KRS, then match_key), afterwards only FILLS empty fields, and a race on a number leaves the party unlinked instead of failing the save. `0006` backfills unlinked organisations (through the hub's import door on the platform), is idempotent, and its downgrade drops only an empty register. Backups and `0001` exclude `COUNTERPARTY_TABLES` on the platform (`models.SHARED_TABLES`); `assert_identity_schema` covers them.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- On Windows, write `.env` **without a BOM** (PowerShell `Out-File -Encoding utf8` adds one, and
|
||||
|
||||
@@ -107,8 +107,11 @@ def _own_tables() -> list:
|
||||
which stops the usual route; this closes the one that goes round it (unset the variable, then
|
||||
downgrade), and it costs nothing.
|
||||
"""
|
||||
from app.models import SHARED_TABLES
|
||||
|
||||
# Since dredd-core 0.21.0 the counterparty register is the platform's too (revision 0006).
|
||||
return own_tables(Base.metadata,
|
||||
shared=SHARED_IDENTITY_TABLES if get_settings().shares_identity else ())
|
||||
shared=SHARED_TABLES if get_settings().shares_identity else ())
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
|
||||
@@ -113,7 +113,7 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from dredd_core.identity import SHARED_IDENTITY_TABLES
|
||||
from dredd_core.identity import COUNTERPARTY_TABLES, SHARED_IDENTITY_TABLES
|
||||
from dredd_core.identity_schema import (
|
||||
permission_grant_orphans_query,
|
||||
permission_grant_orphans_sql,
|
||||
@@ -172,8 +172,8 @@ def _person_columns() -> list[tuple[str, str, str]]:
|
||||
"""
|
||||
found: list[tuple[str, str, str]] = []
|
||||
for table in Base.metadata.sorted_tables:
|
||||
if table.name in SHARED_IDENTITY_TABLES:
|
||||
continue
|
||||
if table.name in SHARED_IDENTITY_TABLES | COUNTERPARTY_TABLES:
|
||||
continue # the counterparty register is the hub's too (dredd-core 0.21.0)
|
||||
for column in table.columns:
|
||||
for fk in column.foreign_keys:
|
||||
if fk.column.table.name == "app_user":
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
"""The platform's counterparty register (dredd-core 0.21.0, the Compass split's K2): Sygna writes it.
|
||||
|
||||
A party is not a counterparty. It keeps what only Sygna keeps (PESEL, PEP, risk rating, the links the
|
||||
conflict engine walks), and it now LINKS to the counterparty it is: `party.counterparty_id`, RESTRICT
|
||||
(a counterparty is archived, never deleted). Organisations only: a natural person stays Sygna's alone
|
||||
(GDPR art. 5(1)(c)), so their names and numbers are never put in front of every module.
|
||||
|
||||
**Standalone** the register is Sygna's own: the three tables are created in this schema (a fresh
|
||||
database already has them, `0001` builds from the metadata), the column + index + foreign key are
|
||||
added, and every unlinked organisation is entered and linked, deduplicated by NIP, KRS, then
|
||||
`match_key` (`dredd_core.counterparties.plan_import`). `counterparty` joins the runtime grants'
|
||||
NO_DELETE list.
|
||||
|
||||
**On the platform** the register is the hub's, in the identity schema (Atrium's `0012` creates it and
|
||||
lists `sygna_app` as a writer, `sygna_migrator` as a migrator). The column's foreign key points there,
|
||||
and the organisations go in through the hub's import door, `<identity>.import_counterparties`, which
|
||||
Atrium keeps open while a `party` table lacks `counterparty_id` — i.e. until this revision ran and
|
||||
the hub migrated once more. No local copy is ever created: `assert_identity_schema` would refuse it.
|
||||
|
||||
Every step is idempotent (catalog checks; the import inserts by fresh id but only for parties still
|
||||
unlinked). Downgrade drops the link column; standalone it also drops the three tables, but only when
|
||||
empty — rows other modules never saw are still rows somebody typed.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
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
|
||||
|
||||
revision = "0006"
|
||||
down_revision = "0005"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
log = logging.getLogger("alembic.sygna.0006")
|
||||
|
||||
FK_NAME = "fk_party_counterparty_id_counterparty"
|
||||
INDEX_NAME = "ix_party_counterparty_id"
|
||||
|
||||
# `0005`'s evidence tables, plus the register standalone (KH10: archived, never deleted).
|
||||
APPEND_ONLY = ("audit_log",)
|
||||
NO_DELETE: tuple[str, ...] = ("conflict_check", "aml_assessment")
|
||||
READ_ONLY = ("alembic_version",)
|
||||
|
||||
|
||||
class Refused(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _q(name: str) -> str:
|
||||
return '"' + name.replace('"', '""') + '"'
|
||||
|
||||
|
||||
def _one(bind, sql: str, **params):
|
||||
return bind.execute(text(sql), params).scalar()
|
||||
|
||||
|
||||
def _has_table(bind, schema: str, table: str) -> bool:
|
||||
return bool(_one(bind, "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))
|
||||
|
||||
|
||||
def _has_column(bind, schema: str) -> bool:
|
||||
return bool(_one(bind, "SELECT count(*) FROM information_schema.columns WHERE table_schema = :s "
|
||||
"AND table_name = 'party' AND column_name = 'counterparty_id'", s=schema))
|
||||
|
||||
|
||||
def _has_constraint(bind, schema: str) -> bool:
|
||||
return bool(_one(bind, "SELECT count(*) FROM pg_constraint k JOIN pg_class t ON t.oid = "
|
||||
"k.conrelid JOIN pg_namespace n ON n.oid = t.relnamespace WHERE "
|
||||
"n.nspname = :s AND t.relname = 'party' AND k.conname = :k",
|
||||
s=schema, k=FK_NAME))
|
||||
|
||||
|
||||
def _link_column(bind, own: str, target_schema: str) -> None:
|
||||
if not _has_column(bind, own):
|
||||
op.execute("ALTER TABLE party ADD COLUMN counterparty_id uuid")
|
||||
if not _has_constraint(bind, own):
|
||||
op.execute(f"ALTER TABLE party ADD CONSTRAINT {FK_NAME} FOREIGN KEY (counterparty_id) "
|
||||
f"REFERENCES {_q(target_schema)}.counterparty (id) ON DELETE RESTRICT")
|
||||
op.execute(f"CREATE INDEX IF NOT EXISTS {INDEX_NAME} ON party (counterparty_id)")
|
||||
|
||||
|
||||
def _unlinked(bind) -> list[cp.Incoming]:
|
||||
"""Every organisation not linked yet, oldest first (the first of two equal names wins)."""
|
||||
parties = [dict(r) for r in bind.execute(text(
|
||||
"SELECT id, name, nip, krs, regon, address, email, phone, created_by FROM party "
|
||||
"WHERE kind::text = 'organisation' AND counterparty_id IS NULL "
|
||||
"ORDER BY created_at, id")).mappings()]
|
||||
aliases: dict = {}
|
||||
for pid, alias in bind.execute(text("SELECT party_id, alias FROM party_alias ORDER BY alias, id")):
|
||||
aliases.setdefault(pid, []).append(alias)
|
||||
return [cp.Incoming(source_id=p["id"],
|
||||
values={"kind": "organisation", **{k: v for k, v in p.items() if k != "id"}},
|
||||
aliases=aliases.get(p["id"], []), keep_id=False)
|
||||
for p in parties]
|
||||
|
||||
|
||||
def _backfill(bind, register_schema: str | None, door: str | None) -> None:
|
||||
incoming = _unlinked(bind)
|
||||
if not incoming:
|
||||
return
|
||||
plan = cp.plan_import(cp.read_register(bind, register_schema), incoming)
|
||||
added = cp.import_counterparties(bind, plan, schema=door)
|
||||
for party_id, counterparty_id in plan.mapping.items():
|
||||
bind.execute(text("UPDATE party SET counterparty_id = CAST(:c AS uuid) "
|
||||
"WHERE id = CAST(:p AS uuid) AND counterparty_id IS NULL"),
|
||||
{"c": str(counterparty_id), "p": str(party_id)})
|
||||
log.info("sygna 0006: %s; %d new counterparties, %d parties linked",
|
||||
plan.summary(), added, len(plan.mapping))
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
settings = get_settings()
|
||||
bind = op.get_bind()
|
||||
own = _one(bind, "SELECT current_schema()")
|
||||
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.")
|
||||
_link_column(bind, own, identity)
|
||||
if _unlinked(bind):
|
||||
if not _one(bind, "SELECT count(*) FROM pg_proc p JOIN pg_namespace n ON n.oid = "
|
||||
"p.pronamespace WHERE n.nspname = :s AND p.proname = :f",
|
||||
s=identity, f=cp.IMPORT_FUNCTION):
|
||||
raise Refused(f"{identity}.{cp.IMPORT_FUNCTION} does not exist: the hub opens that "
|
||||
"door while Sygna's parties are unlinked. List sygna_migrator in "
|
||||
"COUNTERPARTY_MIGRATOR_ROLES and migrate the hub again.")
|
||||
_backfill(bind, identity, identity)
|
||||
op.execute(runtime_grants_sql(settings.db_app_role, append_only=APPEND_ONLY,
|
||||
no_delete=NO_DELETE, read_only=READ_ONLY))
|
||||
return
|
||||
cp.create_counterparty_tables(bind, own)
|
||||
_link_column(bind, own, own)
|
||||
_backfill(bind, None, None)
|
||||
op.execute(runtime_grants_sql(settings.db_app_role, append_only=APPEND_ONLY,
|
||||
no_delete=(*NO_DELETE, "counterparty"), read_only=READ_ONLY))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
settings = get_settings()
|
||||
bind = op.get_bind()
|
||||
own = _one(bind, "SELECT current_schema()")
|
||||
op.execute(f"ALTER TABLE party DROP CONSTRAINT IF EXISTS {FK_NAME}")
|
||||
op.execute(f"DROP INDEX IF EXISTS {INDEX_NAME}")
|
||||
op.execute("ALTER TABLE party DROP COLUMN IF EXISTS counterparty_id")
|
||||
if settings.shares_identity:
|
||||
return # the register is the hub's: what Sygna wrote there stays, other modules read it
|
||||
for table in ("counterparty_contact", "counterparty_alias", "counterparty"):
|
||||
if _has_table(bind, own, table):
|
||||
if _one(bind, f"SELECT count(*) FROM {_q(table)}"):
|
||||
raise Refused(f"{table} holds rows: refusing to drop the counterparty register.")
|
||||
op.execute(f"DROP TABLE {_q(table)}")
|
||||
op.execute(runtime_grants_sql(settings.db_app_role, append_only=APPEND_ONLY,
|
||||
no_delete=NO_DELETE, read_only=READ_ONLY))
|
||||
+5
-1
@@ -8,6 +8,7 @@ import os
|
||||
from collections.abc import AsyncIterator
|
||||
from pathlib import Path
|
||||
|
||||
from dredd_core.identity import COUNTERPARTY_TABLES, SHARED_IDENTITY_TABLES
|
||||
from dredd_core.identity_schema import assert_identity_schema
|
||||
from fastapi import Depends, FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
@@ -87,7 +88,10 @@ def _assert_shared_identity() -> None:
|
||||
return
|
||||
with engine.connect() as conn:
|
||||
own = conn.scalar(text("SELECT current_schema()")) or ""
|
||||
assert_identity_schema(conn, own_schema=own, identity_schema=settings.identity_schema)
|
||||
# The counterparty register too (dredd-core 0.21.0): a local copy would be a private
|
||||
# register the other modules never see.
|
||||
assert_identity_schema(conn, own_schema=own, identity_schema=settings.identity_schema,
|
||||
tables=SHARED_IDENTITY_TABLES | COUNTERPARTY_TABLES)
|
||||
log.info("Shared identity schema %s: every identity table resolves there",
|
||||
settings.identity_schema)
|
||||
|
||||
|
||||
@@ -8,6 +8,12 @@ from __future__ import annotations
|
||||
from dredd_core import (
|
||||
AppSetting, AppUser, AuditLog, Base, Favorite, Node, PermissionGrant, Session,
|
||||
)
|
||||
# The platform's counterparty register (dredd-core 0.21.0, the Compass split's K2): standalone
|
||||
# Sygna's own tables, on the platform the hub's in the identity schema, which Sygna WRITES (the
|
||||
# owner's decision: "zapisuje Sygna"). A party links to its counterparty (`party.counterparty_id`);
|
||||
# the party itself, with what only Sygna keeps (PESEL, PEP, risk, links), stays Sygna's.
|
||||
from dredd_core.counterparties import Counterparty, CounterpartyAlias, CounterpartyContact
|
||||
from dredd_core.identity import COUNTERPARTY_TABLES, SHARED_IDENTITY_TABLES
|
||||
|
||||
from .aml import AmlAssessment
|
||||
from .template import DocumentTemplate
|
||||
@@ -22,6 +28,10 @@ from .party import Party, PartyAlias, PartyLink
|
||||
from .rate import LawyerProfile, RateCard, RateCardEntry
|
||||
from .timelog import TimeEntry
|
||||
|
||||
#: The tables that are the platform's, not Sygna's, when it is a module of it: never created by
|
||||
#: `0001`, never in the backup, and required in the identity schema by the boot assertion.
|
||||
SHARED_TABLES: frozenset[str] = SHARED_IDENTITY_TABLES | COUNTERPARTY_TABLES
|
||||
|
||||
__all__ = [
|
||||
"AmlAssessment",
|
||||
"UpstreamCredential",
|
||||
@@ -35,6 +45,11 @@ __all__ = [
|
||||
"Node",
|
||||
"PermissionGrant",
|
||||
"Favorite",
|
||||
# the platform's counterparty register (dredd-core 0.21.0)
|
||||
"Counterparty",
|
||||
"CounterpartyAlias",
|
||||
"CounterpartyContact",
|
||||
"SHARED_TABLES",
|
||||
# Sygna
|
||||
"Party",
|
||||
"PartyAlias",
|
||||
|
||||
@@ -45,9 +45,15 @@ class Party(UUIDPkMixin, TimestampMixin, Base):
|
||||
notes: Mapped[str | None] = mapped_column(Text)
|
||||
|
||||
created_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
|
||||
# The platform's counterparty this party is (dredd-core 0.21.0): set for organisations when
|
||||
# Sygna writes the register (services/parties.sync_counterparty, revision 0006). RESTRICT: a
|
||||
# counterparty is archived, never deleted.
|
||||
counterparty_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||
ForeignKey("counterparty.id", ondelete="RESTRICT"))
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_party_search_key", "search_key"),
|
||||
Index("ix_party_counterparty_id", "counterparty_id"),
|
||||
Index("ix_party_nip", "nip"),
|
||||
Index("ix_party_krs", "krs"),
|
||||
)
|
||||
|
||||
@@ -478,7 +478,9 @@ def party_out(p: Party) -> dict:
|
||||
"pesel": p.pesel, "krs": p.krs, "regon": p.regon, "email": p.email,
|
||||
"phone": p.phone, "address": p.address,
|
||||
"edoreczenia_address": p.edoreczenia_address,
|
||||
"is_pep": p.is_pep, "risk_rating": p.risk_rating.value, "notes": p.notes}
|
||||
"is_pep": p.is_pep, "risk_rating": p.risk_rating.value, "notes": p.notes,
|
||||
# The platform's counterparty this party is (dredd-core 0.21.0), or None.
|
||||
"counterparty_id": str(p.counterparty_id) if p.counterparty_id else None}
|
||||
|
||||
|
||||
def matter_out(m: Matter, *, client: Party | None = None, case_file_url: str | None = None,
|
||||
|
||||
@@ -42,7 +42,7 @@ from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
from dredd_core.db import make_engine
|
||||
from dredd_core.identity import SHARED_IDENTITY_TABLES
|
||||
from dredd_core.identity import COUNTERPARTY_TABLES, SHARED_IDENTITY_TABLES
|
||||
from dredd_core.schema import own_tables
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
from sqlalchemy.pool import NullPool
|
||||
@@ -74,8 +74,10 @@ def _tables() -> list:
|
||||
|
||||
Read per call rather than computed once at import, so a test may vary the setting.
|
||||
"""
|
||||
# The counterparty register (dredd-core 0.21.0) is the platform's too: the hub's backup.
|
||||
return own_tables(Base.metadata,
|
||||
shared=SHARED_IDENTITY_TABLES if settings.shares_identity else ())
|
||||
shared=SHARED_IDENTITY_TABLES | COUNTERPARTY_TABLES
|
||||
if settings.shares_identity else ())
|
||||
|
||||
|
||||
ARCHIVE_PREFIX = "sygna-"
|
||||
|
||||
@@ -13,10 +13,14 @@ English-language product gets wrong:
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from dredd_core import counterparties as register
|
||||
from dredd_core.errors import ValidationError as CoreValidationError
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..enums import PartyKind
|
||||
@@ -121,6 +125,7 @@ def create_party(db: DbSession, user: AppUser, *, kind: PartyKind, name: str, **
|
||||
)
|
||||
db.add(party)
|
||||
db.flush()
|
||||
sync_counterparty(db, party, actor_id=user.id)
|
||||
return party
|
||||
|
||||
|
||||
@@ -131,9 +136,70 @@ def update_party(db: DbSession, party: Party, **fields) -> Party:
|
||||
if "name" in fields and fields["name"]:
|
||||
party.search_key = normalize(party.name)
|
||||
db.flush()
|
||||
sync_counterparty(db, party, actor_id=party.created_by)
|
||||
return party
|
||||
|
||||
|
||||
# ── the platform's counterparty register (dredd-core 0.21.0) ──────────────────
|
||||
# Sygna WRITES the register (the owner's decision, 2026-11-06: "zapisuje Sygna"); every module reads
|
||||
# it. A party is not a counterparty: it carries what only Sygna keeps (PESEL, PEP, risk rating, the
|
||||
# links the conflict engine walks), and it LINKS to the counterparty it is (`counterparty_id`).
|
||||
|
||||
log = logging.getLogger("sygna.parties")
|
||||
|
||||
#: Which parties Sygna puts in the platform's register: organisations. A natural person stays
|
||||
#: Sygna's alone — a client's name and numbers are not every module's business (GDPR art. 5(1)(c));
|
||||
#: another module that needs a person as a counterparty enters it itself.
|
||||
REGISTER_KINDS = (PartyKind.organisation,)
|
||||
_FILLABLE = ("address", "email", "phone")
|
||||
|
||||
|
||||
def _clean_numbers(party: Party) -> dict[str, str | None]:
|
||||
"""The party's numbers as the register stores them; one that fails its check is left out (Sygna
|
||||
accepts what intake typed, the register only valid numbers)."""
|
||||
out: dict[str, str | None] = {}
|
||||
for column, clean in (("nip", register.clean_nip), ("krs", register.clean_krs),
|
||||
("regon", register.clean_regon)):
|
||||
try:
|
||||
out[column] = clean(getattr(party, column))
|
||||
except CoreValidationError:
|
||||
out[column] = None
|
||||
return out
|
||||
|
||||
|
||||
def sync_counterparty(db: DbSession, party: Party, *, actor_id: uuid.UUID | None) -> uuid.UUID | None:
|
||||
"""Link `party` to the platform's counterparty it is, creating it when there is none, and fill
|
||||
that counterparty's EMPTY fields from the party (never overwriting what another module wrote).
|
||||
Organisations only (`REGISTER_KINDS`). A no-op where Sygna may not write the register (the hub
|
||||
has not listed it), and a race on a number (another writer took it a moment ago) leaves the
|
||||
party unlinked rather than failing the party's own change: the next save links it. No commit."""
|
||||
if party.kind not in REGISTER_KINDS or not register.writable(db):
|
||||
return party.counterparty_id
|
||||
numbers = _clean_numbers(party)
|
||||
try:
|
||||
with db.begin_nested():
|
||||
if party.counterparty_id is None:
|
||||
row, how = register.link_or_create(
|
||||
db, kind=str(party.kind), name=party.name, actor_id=actor_id, source="sygna",
|
||||
values={**numbers, **{c: getattr(party, c) for c in _FILLABLE}},
|
||||
aliases=[a.alias for a in aliases_for(db, party)] if party.id else ())
|
||||
party.counterparty_id = row.id
|
||||
log.info("party %s linked to counterparty %s (%s)", party.id, row.id, how)
|
||||
else:
|
||||
row = db.get(register.Counterparty, party.counterparty_id, with_for_update=True)
|
||||
if row is not None and not row.archived:
|
||||
for column in (*_FILLABLE, "nip", "krs", "regon"):
|
||||
value = numbers.get(column) if column in numbers else getattr(party, column)
|
||||
if value and getattr(row, column) is None:
|
||||
setattr(row, column, value)
|
||||
db.flush()
|
||||
except IntegrityError:
|
||||
log.info("party %s: the register changed under us, left unlinked for now", party.id)
|
||||
except CoreValidationError:
|
||||
pass
|
||||
return party.counterparty_id
|
||||
|
||||
|
||||
def add_alias(db: DbSession, party: Party, alias: str) -> PartyAlias:
|
||||
alias = (alias or "").strip()
|
||||
if not alias:
|
||||
|
||||
@@ -76,4 +76,6 @@ cryptography==46.0.3 # AES-256-GCM (Apache-2.0/BSD)
|
||||
# edge changes nothing here — but `0004` is not optional: `0001` built the table under its old name
|
||||
# on every database migrated before this bump, and nothing else would ever rename it.
|
||||
# dredd_core.search_contract, new in 0.17.0).
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.19.0
|
||||
# v0.21.0 adds the platform's counterparty register (K2): Sygna WRITES it; party.counterparty_id links
|
||||
# an organisation to its counterparty (revision 0006, services/parties.sync_counterparty).
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.21.0
|
||||
|
||||
@@ -22,6 +22,7 @@ from __future__ import annotations
|
||||
import os
|
||||
import sys
|
||||
|
||||
from dredd_core import counterparties as cp
|
||||
from dredd_core.db import make_engine
|
||||
from dredd_core.identity import SHARED_IDENTITY_TABLES
|
||||
from dredd_core.identity_schema import create_identity_tables
|
||||
@@ -63,6 +64,20 @@ def main() -> int:
|
||||
conn.execute(text(account_delete_guard_sql(IDENTITY_SCHEMA, owner_role=OWNER_ROLE)))
|
||||
print("delete guard installed")
|
||||
|
||||
# The counterparty register (dredd-core 0.21.0), as Atrium's revision 0012 builds it: in the
|
||||
# identity schema, Sygna the writer, its migrator a migrator, and the import door open (the
|
||||
# hub opens it while a `party` table has no `counterparty_id`; Sygna's 0006 backfills
|
||||
# through it on a database that predates it, and on this fresh one finds nothing to move).
|
||||
made = cp.create_counterparty_tables(conn, IDENTITY_SCHEMA)
|
||||
print("counterparty register in", IDENTITY_SCHEMA + ":", ", ".join(made) or "already there")
|
||||
conn.execute(text(cp.counterparty_grants_sql(
|
||||
IDENTITY_SCHEMA, owner_role=OWNER_ROLE, writer_roles=["sygna_app"],
|
||||
migrator_roles=MIGRATOR_ROLES)))
|
||||
for statement in cp.counterparty_import_sql(IDENTITY_SCHEMA, owner_role=OWNER_ROLE,
|
||||
importer_roles=MIGRATOR_ROLES):
|
||||
conn.execute(text(statement))
|
||||
print("counterparty tiers applied, import door open")
|
||||
|
||||
# The one account every app in the family seeds. On a real platform this row is Atrium's,
|
||||
# created by its own seed; here it is the survivor Sygna's cutover will match on e-mail.
|
||||
email = os.environ.get("BOOTSTRAP_ADMIN_EMAIL", "admin@example.com")
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Sygna writes the platform's counterparty register (dredd-core 0.21.0, revision 0006). DB-free."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.enums import PartyKind
|
||||
from app.models import SHARED_TABLES, Party
|
||||
from app.services import parties
|
||||
from dredd_core.identity import COUNTERPARTY_TABLES, SHARED_IDENTITY_TABLES
|
||||
|
||||
REVISION = Path(__file__).resolve().parents[1] / "alembic" / "versions" / "0006_counterparties.py"
|
||||
|
||||
|
||||
def test_the_register_is_shared_on_the_platform():
|
||||
assert SHARED_TABLES == SHARED_IDENTITY_TABLES | COUNTERPARTY_TABLES
|
||||
|
||||
|
||||
def test_a_party_links_to_its_counterparty_restrict():
|
||||
fk = next(iter(Party.__table__.c.counterparty_id.foreign_keys))
|
||||
assert fk.column.table.name == "counterparty" and fk.ondelete == "RESTRICT"
|
||||
|
||||
|
||||
def test_a_person_never_reaches_the_register(monkeypatch):
|
||||
def boom(db):
|
||||
raise AssertionError("asked the register about a person")
|
||||
monkeypatch.setattr(parties.register, "writable", boom)
|
||||
person = SimpleNamespace(kind=PartyKind.person, counterparty_id=None)
|
||||
assert parties.sync_counterparty(object(), person, actor_id=uuid.uuid4()) is None
|
||||
|
||||
|
||||
def test_nothing_happens_where_sygna_may_not_write(monkeypatch):
|
||||
monkeypatch.setattr(parties.register, "writable", lambda db: False)
|
||||
org = SimpleNamespace(kind=PartyKind.organisation, counterparty_id=None)
|
||||
assert parties.sync_counterparty(object(), org, actor_id=None) is None
|
||||
|
||||
|
||||
def test_invalid_numbers_are_left_out():
|
||||
party = SimpleNamespace(nip="1234567890", krs="12", regon="123")
|
||||
assert parties._clean_numbers(party) == {"nip": None, "krs": "0000000012", "regon": None}
|
||||
|
||||
|
||||
def test_revision_0006_sql_has_no_bind_parameter_lookalikes():
|
||||
source = REVISION.read_text(encoding="utf-8")
|
||||
for sql in re.findall(r'op\.execute\(f?"([^"]*)"', source):
|
||||
assert "%" not in sql and not re.search(r"(?<!:):[A-Za-z_]", sql), sql
|
||||
assert 'down_revision = "0005"' in source
|
||||
# 0005's evidence tables are kept: re-running grants with a shorter list re-opens them.
|
||||
assert 'NO_DELETE: tuple[str, ...] = ("conflict_check", "aml_assessment")' in source
|
||||
@@ -128,12 +128,12 @@ def test_the_repoint_names_every_column_that_could_name_a_person():
|
||||
remembering to — and the one column that carries no foreign key is added by hand, because
|
||||
metadata cannot know about it. Miss `permission_grant.principal_id` and the only symptom is
|
||||
somebody who cannot see a matter they could see yesterday."""
|
||||
from dredd_core.identity import SHARED_IDENTITY_TABLES
|
||||
|
||||
from app.models import Base
|
||||
from app.models import SHARED_TABLES, Base
|
||||
|
||||
# SHARED_TABLES: the identity tables and (dredd-core 0.21.0) the counterparty register, both
|
||||
# the hub's on the platform, where this migrator holds no DDL.
|
||||
expected = {(t.name, c.name)
|
||||
for t in Base.metadata.sorted_tables if t.name not in SHARED_IDENTITY_TABLES
|
||||
for t in Base.metadata.sorted_tables if t.name not in SHARED_TABLES
|
||||
for c in t.columns
|
||||
for fk in c.foreign_keys if fk.column.table.name == "app_user"}
|
||||
expected.add(("permission_grant", "principal_id"))
|
||||
|
||||
@@ -234,7 +234,8 @@ for url in DATABASE_URL MIGRATION_DATABASE_URL; do
|
||||
done
|
||||
```
|
||||
|
||||
On the platform, add `--identity-schema dredd --identity-tier reader` — `reader` is a module's
|
||||
On the platform, add `--identity-schema dredd --identity-tier reader --counterparties writer` (Sygna
|
||||
writes the shared counterparty register since dredd-core 0.21.0) — `reader` is a module's
|
||||
tier; the hub's own roles are checked as `owner`. Without the flag the check would sweep `dredd`
|
||||
as "another app's schema" and fail Sygna for holding privileges there, which is exactly the
|
||||
privilege it is supposed to hold.
|
||||
|
||||
Reference in New Issue
Block a user