324 lines
12 KiB
Python
324 lines
12 KiB
Python
from __future__ import annotations
|
|
|
|
from datetime import UTC, datetime
|
|
from typing import Any, Mapping, Sequence
|
|
|
|
from sqlalchemy import or_
|
|
from sqlalchemy.orm import Session
|
|
|
|
from govoplan_core.core.institutional import (
|
|
InstitutionalContextError,
|
|
InstitutionalReference,
|
|
PartyRepresentation,
|
|
ProcedureParty,
|
|
TemporalRevision,
|
|
revise_procedure_party,
|
|
revoke_party_representation,
|
|
)
|
|
from govoplan_parties.backend.db.models import ProcedurePartyRevision
|
|
|
|
|
|
MAX_PARTY_CANDIDATES = 1_000
|
|
|
|
|
|
class PartyStoreError(ValueError):
|
|
pass
|
|
|
|
|
|
def record_procedure_party(
|
|
session: Session,
|
|
principal: object,
|
|
*,
|
|
party: ProcedureParty,
|
|
expected_revision: str | None = None,
|
|
) -> ProcedureParty:
|
|
tenant_id = _principal_tenant(principal)
|
|
_validate_party(party, tenant_id=tenant_id)
|
|
payload = party.to_dict(include_inspection=True)
|
|
replay = (
|
|
session.query(ProcedurePartyRevision)
|
|
.filter(
|
|
ProcedurePartyRevision.tenant_id == tenant_id,
|
|
ProcedurePartyRevision.party_id == party.reference.object_id,
|
|
ProcedurePartyRevision.revision == party.temporal.revision,
|
|
)
|
|
.one_or_none()
|
|
)
|
|
if replay is not None:
|
|
if replay.payload != payload:
|
|
raise PartyStoreError(
|
|
"A different Party payload already uses this revision."
|
|
)
|
|
return _party_from_row(replay)
|
|
|
|
current_row = _current_row(
|
|
session,
|
|
tenant_id=tenant_id,
|
|
party_id=party.reference.object_id,
|
|
lock=True,
|
|
)
|
|
_validate_temporal(party.temporal)
|
|
if current_row is None:
|
|
if expected_revision is not None:
|
|
raise PartyStoreError("Party revision conflict: no current revision exists.")
|
|
_validate_new_representations(party.representations)
|
|
else:
|
|
current = _party_from_row(current_row)
|
|
if not _same_reference_identity(current.procedure_ref, party.procedure_ref):
|
|
raise PartyStoreError("A Party cannot move to another procedure.")
|
|
try:
|
|
revised = revise_procedure_party(
|
|
current,
|
|
expected_revision=expected_revision or "",
|
|
temporal=party.temporal,
|
|
status=party.status,
|
|
role=party.role,
|
|
subject=party.subject,
|
|
preferred_channels=party.preferred_channels,
|
|
permitted_channels=party.permitted_channels,
|
|
delivery_recipient=party.delivery_recipient,
|
|
representations=party.representations,
|
|
contact_snapshot_refs=party.contact_snapshot_refs,
|
|
evidence=party.evidence,
|
|
)
|
|
except InstitutionalContextError as exc:
|
|
raise PartyStoreError(str(exc)) from exc
|
|
if revised != party:
|
|
raise PartyStoreError(
|
|
"Party identity and immutable procedure reference must follow the lifecycle revision."
|
|
)
|
|
_validate_representation_changes(current.representations, party.representations)
|
|
current_row.superseded_at = party.temporal.recorded_at
|
|
|
|
row = ProcedurePartyRevision(
|
|
tenant_id=tenant_id,
|
|
party_id=party.reference.object_id,
|
|
procedure_kind=party.procedure_ref.kind,
|
|
procedure_owner_module=party.procedure_ref.owner_module,
|
|
procedure_id=party.procedure_ref.object_id,
|
|
revision=party.temporal.revision,
|
|
previous_revision_id=current_row.id if current_row is not None else None,
|
|
status=party.status,
|
|
valid_from=party.temporal.valid_from,
|
|
valid_to=party.temporal.valid_to,
|
|
recorded_at=_recorded_at(party.temporal),
|
|
payload=payload,
|
|
created_by=_principal_actor(principal),
|
|
)
|
|
session.add(row)
|
|
session.flush()
|
|
return _party_from_row(row)
|
|
|
|
|
|
def get_procedure_party(
|
|
session: Session,
|
|
principal: object,
|
|
*,
|
|
party_id: str,
|
|
revision: str | None = None,
|
|
) -> ProcedureParty | None:
|
|
tenant_id = _principal_tenant(principal)
|
|
query = session.query(ProcedurePartyRevision).filter(
|
|
ProcedurePartyRevision.tenant_id == tenant_id,
|
|
ProcedurePartyRevision.party_id == party_id,
|
|
)
|
|
if revision is None:
|
|
query = query.filter(ProcedurePartyRevision.superseded_at.is_(None))
|
|
else:
|
|
query = query.filter(ProcedurePartyRevision.revision == revision)
|
|
row = query.order_by(ProcedurePartyRevision.recorded_at.desc()).first()
|
|
return _party_from_row(row) if row is not None else None
|
|
|
|
|
|
class SqlPartyResolver:
|
|
def list_procedure_parties(
|
|
self,
|
|
session: object,
|
|
principal: object,
|
|
*,
|
|
procedure_ref: InstitutionalReference,
|
|
effective_at: datetime | None = None,
|
|
) -> Sequence[ProcedureParty]:
|
|
tenant_id = _principal_tenant(principal)
|
|
if procedure_ref.tenant_id != tenant_id or procedure_ref.kind not in {"case", "workflow", "decision"}:
|
|
raise InstitutionalContextError(
|
|
"Party resolution requires a same-tenant case, workflow, or decision reference."
|
|
)
|
|
typed_session = _session(session)
|
|
query = typed_session.query(ProcedurePartyRevision).filter(
|
|
ProcedurePartyRevision.tenant_id == tenant_id,
|
|
ProcedurePartyRevision.procedure_kind == procedure_ref.kind,
|
|
ProcedurePartyRevision.procedure_owner_module == procedure_ref.owner_module,
|
|
ProcedurePartyRevision.procedure_id == procedure_ref.object_id,
|
|
)
|
|
if effective_at is None:
|
|
query = query.filter(ProcedurePartyRevision.superseded_at.is_(None))
|
|
else:
|
|
query = query.filter(
|
|
or_(ProcedurePartyRevision.valid_from.is_(None), ProcedurePartyRevision.valid_from <= effective_at),
|
|
or_(ProcedurePartyRevision.valid_to.is_(None), ProcedurePartyRevision.valid_to > effective_at),
|
|
)
|
|
rows = query.order_by(
|
|
ProcedurePartyRevision.party_id.asc(),
|
|
ProcedurePartyRevision.recorded_at.desc(),
|
|
).limit(MAX_PARTY_CANDIDATES + 1).all()
|
|
if len(rows) > MAX_PARTY_CANDIDATES:
|
|
raise InstitutionalContextError("Party resolution candidate bound was exceeded.")
|
|
latest: dict[str, ProcedureParty] = {}
|
|
for row in rows:
|
|
latest.setdefault(row.party_id, _party_from_row(row))
|
|
return tuple(latest.values())
|
|
|
|
|
|
def party_from_mapping(value: Mapping[str, object]) -> ProcedureParty:
|
|
try:
|
|
return ProcedureParty.from_mapping(value)
|
|
except InstitutionalContextError as exc:
|
|
raise PartyStoreError(str(exc)) from exc
|
|
|
|
|
|
def reference_from_mapping(value: Mapping[str, object]) -> InstitutionalReference:
|
|
try:
|
|
return InstitutionalReference.from_mapping(value)
|
|
except InstitutionalContextError as exc:
|
|
raise PartyStoreError(str(exc)) from exc
|
|
|
|
|
|
def _validate_representation_changes(
|
|
current: Sequence[PartyRepresentation],
|
|
revised: Sequence[PartyRepresentation],
|
|
) -> None:
|
|
next_by_key = {_representation_key(item): item for item in revised}
|
|
if len(next_by_key) != len(revised):
|
|
raise PartyStoreError("Party representations cannot contain duplicate powers.")
|
|
current_keys = {_representation_key(item) for item in current}
|
|
if not current_keys.issubset(next_by_key):
|
|
raise PartyStoreError(
|
|
"Representation powers cannot be removed; revoke them explicitly."
|
|
)
|
|
for previous in current:
|
|
next_item = next_by_key[_representation_key(previous)]
|
|
if next_item == previous:
|
|
continue
|
|
if previous.revoked_at is not None:
|
|
raise PartyStoreError("A revoked representation power is immutable.")
|
|
if next_item.revoked_at is None:
|
|
raise PartyStoreError(
|
|
"An existing representation power can only change through revocation."
|
|
)
|
|
try:
|
|
expected = revoke_party_representation(
|
|
previous,
|
|
expected_revision=previous.temporal.revision,
|
|
temporal=next_item.temporal,
|
|
revoked_at=next_item.revoked_at,
|
|
evidence=next_item.evidence,
|
|
)
|
|
except InstitutionalContextError as exc:
|
|
raise PartyStoreError(str(exc)) from exc
|
|
if expected != next_item:
|
|
raise PartyStoreError(
|
|
"Representation revocation cannot rewrite parties, power, or permitted actions."
|
|
)
|
|
_validate_new_representations(
|
|
tuple(item for item in revised if _representation_key(item) not in current_keys)
|
|
)
|
|
|
|
|
|
def _validate_new_representations(items: Sequence[PartyRepresentation]) -> None:
|
|
seen: set[tuple[str, str, str]] = set()
|
|
for item in items:
|
|
key = _representation_key(item)
|
|
if key in seen:
|
|
raise PartyStoreError("Party representations cannot contain duplicate powers.")
|
|
seen.add(key)
|
|
_validate_temporal(item.temporal)
|
|
if item.revoked_at is not None:
|
|
raise PartyStoreError("A new representation cannot already be revoked.")
|
|
|
|
|
|
def _representation_key(item: PartyRepresentation) -> tuple[str, str, str]:
|
|
return (
|
|
item.power_ref,
|
|
item.representative_party_ref.object_id,
|
|
item.represented_party_ref.object_id,
|
|
)
|
|
|
|
|
|
def _current_row(session: Session, *, tenant_id: str, party_id: str, lock: bool) -> ProcedurePartyRevision | None:
|
|
query = session.query(ProcedurePartyRevision).filter(
|
|
ProcedurePartyRevision.tenant_id == tenant_id,
|
|
ProcedurePartyRevision.party_id == party_id,
|
|
ProcedurePartyRevision.superseded_at.is_(None),
|
|
)
|
|
if lock:
|
|
query = query.with_for_update()
|
|
return query.one_or_none()
|
|
|
|
|
|
def _party_from_row(row: ProcedurePartyRevision) -> ProcedureParty:
|
|
payload: dict[str, Any] = dict(row.payload)
|
|
temporal = dict(payload.get("temporal") or {})
|
|
temporal["superseded_at"] = _datetime_text(row.superseded_at)
|
|
payload["temporal"] = temporal
|
|
return ProcedureParty.from_mapping(payload)
|
|
|
|
|
|
def _validate_party(party: ProcedureParty, *, tenant_id: str) -> None:
|
|
if party.reference.owner_module != "parties":
|
|
raise PartyStoreError("Procedure Parties must be owned by Parties.")
|
|
if party.reference.tenant_id != tenant_id:
|
|
raise PartyStoreError("Procedure Parties cannot cross tenants.")
|
|
if party.reference.version != party.temporal.revision:
|
|
raise PartyStoreError("Party reference version must match its temporal revision.")
|
|
if party.temporal.superseded_at is not None:
|
|
raise PartyStoreError("Clients cannot set Party superseded_at.")
|
|
|
|
|
|
def _validate_temporal(temporal: TemporalRevision) -> None:
|
|
_recorded_at(temporal)
|
|
if not str(temporal.change_reason or "").strip():
|
|
raise PartyStoreError("A Party revision requires recorded_at and change_reason.")
|
|
|
|
|
|
def _recorded_at(temporal: TemporalRevision) -> datetime:
|
|
if temporal.recorded_at is None:
|
|
raise PartyStoreError("A Party revision requires recorded_at.")
|
|
return temporal.recorded_at
|
|
|
|
|
|
def _same_reference_identity(left: InstitutionalReference, right: InstitutionalReference) -> bool:
|
|
return (left.kind, left.owner_module, left.object_id, left.tenant_id) == (right.kind, right.owner_module, right.object_id, right.tenant_id)
|
|
|
|
|
|
def _principal_tenant(principal: object) -> str:
|
|
tenant_id = str(getattr(principal, "tenant_id", "") or "").strip()
|
|
if not tenant_id:
|
|
raise InstitutionalContextError("Party operations require a tenant-bound principal.")
|
|
return tenant_id
|
|
|
|
|
|
def _principal_actor(principal: object) -> str | None:
|
|
for name in ("account_id", "identity_id", "membership_id"):
|
|
value = str(getattr(principal, name, "") or "").strip()
|
|
if value:
|
|
return value
|
|
return None
|
|
|
|
|
|
def _session(value: object) -> Session:
|
|
if not hasattr(value, "query"):
|
|
raise InstitutionalContextError("Party resolver requires a database session.")
|
|
return value # type: ignore[return-value]
|
|
|
|
|
|
def _datetime_text(value: datetime | None) -> str | None:
|
|
if value is None:
|
|
return None
|
|
if value.tzinfo is None:
|
|
value = value.replace(tzinfo=UTC)
|
|
return value.isoformat()
|
|
|
|
|
|
__all__ = ["PartyStoreError", "SqlPartyResolver", "get_procedure_party", "party_from_mapping", "record_procedure_party", "reference_from_mapping"]
|