Walls, evidence and the intake gate: four fixes from a source review
- Correspondence: the inbox's undated list held items already filed in a matter and showed and counted them for everyone. It is now filtered to the reader (correspondence.undated_for), including the dashboard card. assign is authorized on the matter an item leaves as well as the one it enters, and an item with derived deadlines no longer moves. The undated reminder goes only to recipients who may read the item's matter. - Conflict hits: the search still looks across every wall, but a hit in a matter the reader cannot open no longer names it (conflicts.visible_hits, matter_hidden). conflict_out requires the reader's hits. - AML: deleting a matter cascaded to its assessments, and the runtime role's missing DELETE did not stop it (a cascade runs as the table's owner). nodes.delete refuses in words; revision 0007 drops the cascade. - Opening a matter: the conflict check must cover the client (the engine's name match against name and aliases) and the lead named on the request. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
88a4ae6f15
commit
3215c3d569
@@ -224,7 +224,15 @@ BOOTSTRAP_ADMIN_PASSWORD=… python scripts/walkthrough.py # drive the whole p
|
||||
matter node without its `matter` row is an orphan the authz resolver cannot wall.
|
||||
- **The conflict check is a blocking gate, not a report.** `open_matter` refuses a check that is
|
||||
`pending` or `declined`, and refuses one already used to open a matter (one check, one matter).
|
||||
A `waived`/`declined` decision requires a written reason.
|
||||
A `waived`/`declined` decision requires a written reason. **And the check must be a check on
|
||||
that client** (`matters.assert_check_covers`): the engine's own name match against the client's
|
||||
name and aliases, and the lead named on the request must be the check's lead — otherwise a clear
|
||||
check on any unknown name opened a matter for anyone.
|
||||
- **A conflict hit never describes a matter the reader cannot open.** The search looks across
|
||||
every wall (it has to), but on the way out `conflicts.visible_hits` blanks the matter fields of a
|
||||
hit in an unreadable matter and sets `matter_hidden`; the hit itself — kind, severity, party,
|
||||
role — stays. `conflict_out` takes the reader's `hits` as a required argument, so a caller that
|
||||
forgets fails rather than leaks. The frozen `conflict_check.hits` is never rewritten.
|
||||
- **A check's decision note must match its own `hit_count`.** An auto-cleared check with
|
||||
non-blocking hits says how many it found and why none required a human — never "brak trafień"
|
||||
next to a hit count of three. The row is read years later by somebody reconstructing why a
|
||||
@@ -248,7 +256,10 @@ BOOTSTRAP_ADMIN_PASSWORD=… python scripts/walkthrough.py # drive the whole p
|
||||
of mitigating factors** (art. 46): it is not a heavy scoring factor, it is an override, and a
|
||||
PEP who is also a long-standing client of a listed company must not average out to medium.
|
||||
`retain_until` is stored, not computed — art. 49's five years is the clock that was written
|
||||
down at the time, not one recomputed under today's rule.
|
||||
down at the time, not one recomputed under today's rule. **A missing DELETE grant does not stop
|
||||
a cascade** — PostgreSQL runs a referential action as the table's owner — so
|
||||
`aml_assessment.matter_id` carries no ON DELETE rule (revision `0007`, like `invoice.matter_id`)
|
||||
and `nodes.delete` refuses a subtree holding any assessment, in words, before the database does.
|
||||
- **Append-only audit.** The `app` role holds no UPDATE/DELETE on `audit_log` (enforced in the
|
||||
migration). `migrator` owns DDL; `app` is DML-only. In a law firm the audit log is a
|
||||
confidentiality control, not an ops convenience.
|
||||
@@ -320,6 +331,10 @@ BOOTSTRAP_ADMIN_PASSWORD=… python scripts/walkthrough.py # drive the whole p
|
||||
that has lost the document proving where its date came from is worse than a blocked delete.
|
||||
- **Correspondence is assigned to a matter by a human.** Items land unassigned in the inbox;
|
||||
nothing guesses, because a plausible guess files a court letter in the wrong client's records.
|
||||
**Moving a filed item is authorized on the matter it leaves** as well as the one it enters
|
||||
(`correspondence.assign`, the same rule as `unassign`), and an item deadlines were derived from
|
||||
does not move. The inbox's undated list also holds FILED items, so it is filtered to the reader
|
||||
and counted after the filter (`correspondence.undated_for`); only unassigned post is everyone's.
|
||||
- **Connectors write through `services/correspondence.record`.** Phase 2's e-Doręczenia and
|
||||
Portal Informacyjny connectors use the same function the console does, so they inherit the
|
||||
service-date and idempotency rules instead of re-implementing them. Idempotency is
|
||||
@@ -501,7 +516,9 @@ BOOTSTRAP_ADMIN_PASSWORD=… python scripts/walkthrough.py # drive the whole p
|
||||
falling back to the owner when they *are* the only manager, which is most of the market.
|
||||
Daily repetition is how a real warning gets ignored.
|
||||
- **A wall blocks notifications too.** Recipients go through `authz.effective_role` on the
|
||||
matter node. A wall that a notification leaks through is not a wall.
|
||||
matter node. A wall that a notification leaks through is not a wall. That includes the chase for
|
||||
a filed item with no service date, which used to go to every administrator with the subject in
|
||||
the title.
|
||||
- **The KRS API masks the names of natural persons.** A board member comes back as
|
||||
`N**********` with a PESEL of `7**********`; verified against three unrelated companies, so it
|
||||
is policy, not an artefact. `registers.is_masked` detects it and `officers_redacted` reports
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
"""An AML assessment no longer disappears with its matter.
|
||||
|
||||
`aml_assessment.matter_id` was `ON DELETE CASCADE`, so deleting a matter node (or the department
|
||||
above it) took every assessment of that matter with it. The runtime role holding no DELETE on
|
||||
`aml_assessment` did not stop that: PostgreSQL runs a referential action with the privileges of the
|
||||
table's OWNER — here the migrator — not those of whoever deleted the parent row. So the grant that
|
||||
`0002_runtime_grants` writes down as "never deleted" was true of a `DELETE FROM aml_assessment` and
|
||||
false of a `DELETE FROM node`, and art. 49's five years could end the day somebody tidied a folder.
|
||||
|
||||
The key now carries no ON DELETE rule, exactly as `invoice.matter_id` does and for the same reason:
|
||||
the record has to outlive the tidy-up. `services/nodes.delete` says so in words before the database
|
||||
says it as a constraint name; this revision is the half that holds even for code that forgets to ask.
|
||||
|
||||
Located through the catalog rather than by name, and only in `current_schema()`, so a database
|
||||
whose constraint was named under an older convention converges too, and the platform's shared
|
||||
schema is never touched. No percent sign and no colon-name sequence anywhere in the SQL, comments
|
||||
included: op.execute wraps the string in text(), which scans all of it (`0004` says why).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "0007"
|
||||
down_revision = "0006"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_REKEY = """
|
||||
DO $sygna_aml_rekey$
|
||||
DECLARE
|
||||
own text := current_schema();
|
||||
qt text;
|
||||
fk text;
|
||||
BEGIN
|
||||
qt := quote_ident(own) || '.' || quote_ident('aml_assessment');
|
||||
SELECT c.conname INTO fk
|
||||
FROM pg_constraint c
|
||||
WHERE c.conrelid = to_regclass(qt)
|
||||
AND c.contype = 'f'
|
||||
AND c.confrelid = to_regclass(quote_ident(own) || '.' || quote_ident('matter'));
|
||||
IF fk IS NULL THEN
|
||||
RAISE EXCEPTION USING MESSAGE =
|
||||
'aml_assessment in schema ' || own || ' has no foreign key to matter';
|
||||
END IF;
|
||||
EXECUTE 'ALTER TABLE ' || qt || ' DROP CONSTRAINT ' || quote_ident(fk);
|
||||
EXECUTE 'ALTER TABLE ' || qt || ' ADD CONSTRAINT ' || quote_ident(fk)
|
||||
|| ' FOREIGN KEY (matter_id) REFERENCES ' || quote_ident(own) || '.' || quote_ident('matter')
|
||||
|| ' (id){rule}';
|
||||
END
|
||||
$sygna_aml_rekey$;
|
||||
"""
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.execute(_REKEY.format(rule=""))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.execute(_REKEY.format(rule=" ON DELETE CASCADE"))
|
||||
@@ -31,9 +31,11 @@ from dredd_core import pg_enum
|
||||
class AmlAssessment(UUIDPkMixin, TimestampMixin, Base):
|
||||
__tablename__ = "aml_assessment"
|
||||
|
||||
matter_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("matter.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
# No ON DELETE rule, on purpose — like `invoice.matter_id`. With CASCADE, deleting the matter
|
||||
# deleted this record too, and the runtime role's missing DELETE did not stop it: PostgreSQL
|
||||
# runs a referential action as the table's owner. `services/nodes.delete` refuses in words;
|
||||
# this is the rule that holds for code that forgets to ask (revision `0007`).
|
||||
matter_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("matter.id"), nullable=False)
|
||||
client_party_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("party.id"), nullable=False)
|
||||
|
||||
status: Mapped[AmlStatus] = mapped_column(
|
||||
|
||||
@@ -22,10 +22,17 @@ router = APIRouter(prefix="/conflicts", tags=["conflicts"])
|
||||
|
||||
@router.post("/search")
|
||||
def preview(body: ConflictSearchIn, db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(get_current_user)):
|
||||
user: AppUser = Depends(get_current_user)):
|
||||
"""Dry run — nothing is written. Use POST /conflicts to record the result."""
|
||||
hits = conflicts.search(db, subject=body.subject, adverse_names=body.adverse_names)
|
||||
return {"hits": hits, "hit_count": len(hits)}
|
||||
return {"hits": conflicts.visible_hits(db, user, [hits])[0], "hit_count": len(hits)}
|
||||
|
||||
|
||||
def checks_out(db: Session, user: AppUser, checks: list) -> list[dict]:
|
||||
"""Checks as `user` may read them: one batched resolution for every hit of every check.
|
||||
Intake's lead screen uses it too, so there is one way a check leaves this application."""
|
||||
views = conflicts.visible_hits(db, user, [c.hits or [] for c in checks])
|
||||
return [conflict_out(c, hits=hits) for c, hits in zip(checks, views)]
|
||||
|
||||
|
||||
@router.post("")
|
||||
@@ -40,18 +47,18 @@ def run(body: ConflictSearchIn, request: Request, db: Session = Depends(get_db),
|
||||
detail=f"{check.subject} — {check.hit_count} trafień, {check.outcome.value}",
|
||||
ip=client_ip(request))
|
||||
db.commit()
|
||||
return conflict_out(check)
|
||||
return checks_out(db, user, [check])[0]
|
||||
|
||||
|
||||
@router.get("")
|
||||
def recent(db: Session = Depends(get_db), _: AppUser = Depends(get_current_user)):
|
||||
return [conflict_out(c) for c in conflicts.recent(db)]
|
||||
def recent(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
|
||||
return checks_out(db, user, conflicts.recent(db))
|
||||
|
||||
|
||||
@router.get("/{check_id}")
|
||||
def get_check(check_id: uuid.UUID, db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(get_current_user)):
|
||||
return conflict_out(conflicts.get(db, check_id))
|
||||
user: AppUser = Depends(get_current_user)):
|
||||
return checks_out(db, user, [conflicts.get(db, check_id)])[0]
|
||||
|
||||
|
||||
@router.post("/{check_id}/decide")
|
||||
@@ -63,4 +70,4 @@ def decide(check_id: uuid.UUID, body: ConflictDecisionIn, request: Request,
|
||||
entity_id=check.id, detail=f"{check.subject} → {check.outcome.value}",
|
||||
ip=client_ip(request))
|
||||
db.commit()
|
||||
return conflict_out(check)
|
||||
return checks_out(db, user, [check])[0]
|
||||
|
||||
@@ -46,12 +46,13 @@ def inbox(limit: int = Query(200, le=500), db: Session = Depends(get_db),
|
||||
both report their true total separately. A truncated list whose length is presented as the
|
||||
count reads as "this is everything" when it is not."""
|
||||
items = corr.inbox(db, limit=limit)
|
||||
undated = corr.undated(db, limit=limit)
|
||||
# Filtered to the reader: this list also holds items already filed in a matter.
|
||||
undated, undated_total = corr.undated_for(db, user, limit=limit)
|
||||
return {
|
||||
"items": [correspondence_out(i) for i in items],
|
||||
"items_total": corr.count_inbox(db),
|
||||
"undated": [correspondence_out(i) for i in undated],
|
||||
"undated_total": corr.count_undated(db),
|
||||
"undated_total": undated_total,
|
||||
"limit": limit,
|
||||
}
|
||||
|
||||
|
||||
@@ -10,8 +10,9 @@ from ..db import get_db
|
||||
from ..deps import client_ip, get_current_user
|
||||
from ..enums import LeadStage
|
||||
from ..models import AppUser
|
||||
from ..schemas import LeadIn, LeadLostIn, conflict_out, lead_out
|
||||
from ..schemas import LeadIn, LeadLostIn, lead_out
|
||||
from ..services import audit, leads
|
||||
from .conflicts import checks_out
|
||||
|
||||
router = APIRouter(prefix="/leads", tags=["intake"])
|
||||
|
||||
@@ -37,10 +38,10 @@ def create_lead(body: LeadIn, request: Request, db: Session = Depends(get_db),
|
||||
|
||||
@router.get("/{lead_id}")
|
||||
def get_lead(lead_id: uuid.UUID, db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(get_current_user)):
|
||||
user: AppUser = Depends(get_current_user)):
|
||||
row = leads.get_lead(db, lead_id)
|
||||
return {"lead": lead_out(row),
|
||||
"checks": [conflict_out(c) for c in leads.checks_for(db, row)]}
|
||||
"checks": checks_out(db, user, leads.checks_for(db, row))}
|
||||
|
||||
|
||||
@router.patch("/{lead_id}")
|
||||
|
||||
@@ -55,6 +55,7 @@ def open_matter(body: MatterOpenIn, request: Request, db: Session = Depends(get_
|
||||
client_party_id=uuid.UUID(body.client_party_id),
|
||||
parent_node_id=uuid.UUID(body.parent_node_id),
|
||||
conflict_check_id=uuid.UUID(body.conflict_check_id),
|
||||
lead_id=uuid.UUID(body.lead_id) if body.lead_id else None,
|
||||
# The acting user's credential, never Sygna's own and never a service account, so
|
||||
# Galena decides who may create a case file. On the platform that IS the caller's own
|
||||
# token — both modules resolve the same session row — and `credentials.galena_token` is
|
||||
|
||||
@@ -515,9 +515,12 @@ def matter_party_out(mp: MatterParty, party: Party) -> dict:
|
||||
"is_adverse": mp.is_adverse, "note": mp.note}
|
||||
|
||||
|
||||
def conflict_out(c: ConflictCheck) -> dict:
|
||||
def conflict_out(c: ConflictCheck, *, hits: list[dict]) -> dict:
|
||||
"""`hits` is the reader's view of `c.hits` (`conflicts.visible_hits`), and it is required on
|
||||
purpose: a caller that forgets it fails at once, instead of describing to the reader a matter
|
||||
they cannot open."""
|
||||
return {"id": str(c.id), "subject": c.subject, "adverse_names": c.adverse_names,
|
||||
"hits": c.hits or [], "hit_count": c.hit_count, "outcome": c.outcome.value,
|
||||
"hits": hits, "hit_count": c.hit_count, "outcome": c.outcome.value,
|
||||
"decision_note": c.decision_note, "lead_id": _id(c.lead_id),
|
||||
"matter_id": _id(c.matter_id), "run_by": _id(c.run_by),
|
||||
"decided_by": _id(c.decided_by),
|
||||
|
||||
@@ -27,8 +27,8 @@ from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..enums import ConflictOutcome
|
||||
from ..errors import ConflictError, NotFoundError, ValidationError
|
||||
from ..models import AppUser, ConflictCheck, Matter, MatterParty, Party, PartyAlias
|
||||
from . import parties as parties_svc
|
||||
from ..models import AppUser, ConflictCheck, Matter, MatterParty, Node, Party, PartyAlias
|
||||
from . import authz, parties as parties_svc
|
||||
|
||||
# Below this containment score a name pair is not reported. Tuned low on purpose: this
|
||||
# screen is allowed to waste a lawyer's time, but not to miss.
|
||||
@@ -176,6 +176,47 @@ def search(db: DbSession, *, subject: str, adverse_names: str | None) -> list[di
|
||||
return hits
|
||||
|
||||
|
||||
#: What a hit says about the matter it was found in — the part a reader may not be entitled to.
|
||||
MATTER_FIELDS = ("matter_id", "matter_reference", "matter_name", "matter_status")
|
||||
|
||||
|
||||
def visible_hits(db: DbSession, user: AppUser, hit_lists: list[list[dict]]) -> list[list[dict]]:
|
||||
"""Each list of hits as `user` may read it, resolved in one batch for all of them.
|
||||
|
||||
The search itself has to look across every wall — a conflict screen that skipped walled
|
||||
matters would let a walled lawyer take exactly the conflicting instruction the wall exists
|
||||
because of. What it must not do is *describe* those matters: a hit names a reference, a title
|
||||
and a status, and the existence of a matter is itself privileged (CLAUDE.md). So the hit stays
|
||||
— its kind, severity, party and role, everything a decision needs — and the matter's own fields
|
||||
are blanked, with `matter_hidden` saying so, for any matter the reader cannot open. Whoever
|
||||
decides the check asks someone who can.
|
||||
|
||||
Only on the way out: the frozen `conflict_check.hits` is evidence and is never rewritten. A
|
||||
matter that no longer exists has no wall left to keep, so its frozen description is shown as
|
||||
it was recorded.
|
||||
"""
|
||||
ids: set[uuid.UUID] = set()
|
||||
for hits in hit_lists:
|
||||
for hit in hits:
|
||||
if hit.get("matter_id"):
|
||||
ids.add(uuid.UUID(hit["matter_id"]))
|
||||
if not ids:
|
||||
return [list(hits) for hits in hit_lists]
|
||||
found = list(db.scalars(select(Matter).where(Matter.id.in_(ids))).all())
|
||||
nodes = list(db.scalars(select(Node).where(Node.id.in_({m.node_id for m in found}))).all())
|
||||
readable = authz.readable_node_ids(db, user, nodes)
|
||||
hidden = {str(m.id) for m in found if m.node_id not in readable}
|
||||
out: list[list[dict]] = []
|
||||
for hits in hit_lists:
|
||||
shown = []
|
||||
for hit in hits:
|
||||
if hit.get("matter_id") in hidden:
|
||||
hit = {**hit, **{key: None for key in MATTER_FIELDS}, "matter_hidden": True}
|
||||
shown.append(hit)
|
||||
out.append(shown)
|
||||
return out
|
||||
|
||||
|
||||
def run(db: DbSession, user: AppUser, *, subject: str, adverse_names: str | None = None,
|
||||
lead_id: uuid.UUID | None = None) -> ConflictCheck:
|
||||
"""Run a check and persist it. A clean result is auto-decided `clear`; anything with a
|
||||
|
||||
@@ -142,7 +142,23 @@ def set_service_date(
|
||||
|
||||
def assign(db: DbSession, item: Correspondence, matter: Matter, user: AppUser) -> Correspondence:
|
||||
"""Attach an inbox item to a matter. Requires the right to work on that matter — an ethical
|
||||
wall therefore also blocks filing correspondence into a walled matter."""
|
||||
wall therefore also blocks filing correspondence into a walled matter.
|
||||
|
||||
**And on the matter it already sits in, when it is filed somewhere.** Re-assigning takes the
|
||||
item out of that matter, so it is authorized there too, exactly as `unassign` is — otherwise
|
||||
anyone who could work on *some* matter could pull a letter out of one they are walled from and
|
||||
read it in their own. The current matter is checked first, so a caller who cannot see it gets
|
||||
the same 404 as for any other record behind a wall. A filed item that deadlines were derived
|
||||
from does not move at all: those deadlines stay on the old matter and would point at a
|
||||
document that is no longer in it."""
|
||||
if item.matter_id is not None and item.matter_id != matter.id:
|
||||
current = matters_svc.get_matter(db, item.matter_id)
|
||||
matters_svc.assert_role(db, user, current, NodeRole.editor)
|
||||
if derived_deadlines(db, item):
|
||||
raise ConflictError(
|
||||
"Od tej korespondencji policzono terminy. Usuń je przed przeniesieniem "
|
||||
"do innej sprawy."
|
||||
)
|
||||
matters_svc.assert_role(db, user, matter, NodeRole.editor)
|
||||
item.matter_id = matter.id
|
||||
item.status = CorrespondenceStatus.assigned
|
||||
@@ -258,7 +274,34 @@ def undated(db: DbSession, limit: int = 50) -> list[Correspondence]:
|
||||
)
|
||||
|
||||
|
||||
def undated_for(db: DbSession, user: AppUser, *, limit: int = 50) -> tuple[list[Correspondence], int]:
|
||||
"""`undated`, as one person may see it: (the first `limit` items, the visible total).
|
||||
|
||||
The undated list is not the inbox. It takes every incoming item from an authoritative channel
|
||||
without a service date — filed ones included, because a letter already in a matter can still
|
||||
be missing the date its deadlines must count from. So it has to be filtered like every other
|
||||
read of a matter's records: unassigned items stay visible to everyone (see
|
||||
`visible_for_matter_ids`), a filed one only to whoever may read its matter. And the total is
|
||||
counted after the filter, never before — "3 pozycje" next to two rows tells the reader that a
|
||||
third exists, which is the one fact a wall is there to hide.
|
||||
|
||||
The whole undated set is read rather than a page of it: it is the pile somebody has to work
|
||||
off, small by nature, and filtering a capped page would undercount exactly the neglected tail.
|
||||
"""
|
||||
rows = list(
|
||||
db.scalars(
|
||||
select(Correspondence).where(*_undated_where())
|
||||
.order_by(Correspondence.created_at)
|
||||
).all()
|
||||
)
|
||||
visible = visible_for_matter_ids(db, user, rows)
|
||||
shown = [r for r in rows if r.matter_id is None or r.matter_id in visible]
|
||||
return shown[:limit], len(shown)
|
||||
|
||||
|
||||
def count_undated(db: DbSession) -> int:
|
||||
"""Every undated item, regardless of who asks. For the reminder engine's own bookkeeping —
|
||||
a person-facing count is `undated_for(...)[1]`."""
|
||||
return int(db.scalar(select(func.count()).select_from(Correspondence)
|
||||
.where(*_undated_where())) or 0)
|
||||
|
||||
|
||||
@@ -20,7 +20,8 @@ from ..enums import ConflictOutcome, MatterStatus, NodeKind, NodeRole, PartyRole
|
||||
from ..errors import AuthorizationError, ConflictError, NotFoundError, ValidationError
|
||||
from ..integrations import galena
|
||||
from ..models import AppUser, ConflictCheck, EthicalWall, Matter, MatterParty, Node, Party
|
||||
from . import authz, moderation, nodes as nodes_svc
|
||||
from . import authz, conflicts as conflicts_svc, moderation, nodes as nodes_svc
|
||||
from . import parties as parties_svc
|
||||
|
||||
# Roles that put a party on the other side. Stored on the row (see models/matter.py) so a later
|
||||
# re-typing can't silently rewrite what a past conflict check saw.
|
||||
@@ -92,6 +93,37 @@ def assert_wall_admin(db: DbSession, user: AppUser, matter: Matter) -> NodeRole:
|
||||
return authz.assert_role(db, user, parent, NodeRole.manager)
|
||||
|
||||
|
||||
def assert_check_covers(db: DbSession, check: ConflictCheck, client: Party,
|
||||
lead_id: uuid.UUID | None) -> None:
|
||||
"""The check that opens a matter must be a check ON THIS CLIENT (and on this enquiry).
|
||||
|
||||
Without it the gate only asked whether *some* check was clear: run one on any name nobody has
|
||||
heard of — no hits, cleared automatically — and open a matter for the client who would have
|
||||
been a conflict, with the register then recording "Brak trafień" for a subject the matter is
|
||||
not about. The test is the conflict engine's own name match (containment, the threshold the
|
||||
search reports at), against the client's name and every alias, so a check on "Kowalski" covers
|
||||
"Kowalski Nieruchomości sp. z o.o." exactly as the search would have found it. A name too
|
||||
short to stem is compared whole.
|
||||
|
||||
A lead named on the request must be the lead the check was run for: marking an enquiry won is
|
||||
part of opening the matter, and it is won by the check that cleared it, not by another one.
|
||||
"""
|
||||
names = [client.name, *(a.alias for a in parties_svc.aliases_for(db, client))]
|
||||
subject = check.subject or ""
|
||||
covered = any(
|
||||
parties_svc.normalize(name) == parties_svc.normalize(subject)
|
||||
or parties_svc.similarity(subject, name) >= conflicts_svc.MATCH_THRESHOLD
|
||||
for name in names
|
||||
)
|
||||
if not covered:
|
||||
raise ConflictError(
|
||||
f"Sprawdzenie konfliktu dotyczyło „{subject}”, a nie klienta „{client.name}”. "
|
||||
"Sprawdź konflikt dla tego klienta."
|
||||
)
|
||||
if lead_id is not None and check.lead_id != lead_id:
|
||||
raise ConflictError("To sprawdzenie konfliktu nie dotyczyło tego zapytania.")
|
||||
|
||||
|
||||
def open_matter(
|
||||
db: DbSession,
|
||||
user: AppUser,
|
||||
@@ -101,6 +133,7 @@ def open_matter(
|
||||
parent_node_id: uuid.UUID,
|
||||
conflict_check_id: uuid.UUID,
|
||||
token: str | None = None,
|
||||
lead_id: uuid.UUID | None = None,
|
||||
**fields,
|
||||
) -> tuple[Matter, str | None]:
|
||||
"""Open a matter. Returns (matter, case_file_warning)."""
|
||||
@@ -130,6 +163,7 @@ def open_matter(
|
||||
raise ConflictError(
|
||||
"To sprawdzenie zostało już wykorzystane do otwarcia sprawy. Uruchom nowe."
|
||||
)
|
||||
assert_check_covers(db, check, client, lead_id)
|
||||
|
||||
node = nodes_svc.create_node(db, user, parent=parent, kind=NodeKind.matter, name=name)
|
||||
matter = Matter(
|
||||
|
||||
@@ -239,8 +239,28 @@ def delete(db: DbSession, node: Node) -> None:
|
||||
Refuses when anything in the subtree has been invoiced. `invoice.matter_id` carries no
|
||||
ON DELETE rule on purpose — an invoice is a tax document and must not vanish because
|
||||
somebody tidied up a folder — but the raw foreign-key error that produces is unreadable.
|
||||
So the rule is stated here, in words, before the database says it in Latin."""
|
||||
from ..models import Invoice, Matter
|
||||
So the rule is stated here, in words, before the database says it in Latin.
|
||||
|
||||
The same holds for an AML assessment: art. 49 keeps it for five years, it is evidence like a
|
||||
conflict check, and the runtime role holds no DELETE on it. That grant alone did not protect
|
||||
it — the key used to cascade, and PostgreSQL runs a cascade as the table's owner — so a
|
||||
deleted matter took its due-diligence record with it. Refused here first, in words; `0007`
|
||||
took the cascade off so the database refuses as well."""
|
||||
from ..models import AmlAssessment, Invoice, Matter
|
||||
|
||||
subtree = (Node.id == node.id) | (Node.path.like(node.path + "/%"))
|
||||
kept = db.scalar(
|
||||
select(Matter.reference)
|
||||
.join(Node, Node.id == Matter.node_id)
|
||||
.join(AmlAssessment, AmlAssessment.matter_id == Matter.id)
|
||||
.where(subtree)
|
||||
.limit(1)
|
||||
)
|
||||
if kept:
|
||||
raise ConflictError(
|
||||
f"Sprawa {kept} ma dokumentację AML, którą trzeba przechowywać — nie można jej "
|
||||
"usunąć. Zamknij ją zamiast usuwać."
|
||||
)
|
||||
|
||||
blocked = db.scalar(
|
||||
select(Matter.reference)
|
||||
|
||||
@@ -61,6 +61,11 @@ def _readable_by(db: DbSession, node: Node, user_ids: set[uuid.UUID]) -> list[Ap
|
||||
return [u for u in users if authz.effective_role(db, u, node) is not None]
|
||||
|
||||
|
||||
def _matter_node(db: DbSession, matter_id: uuid.UUID) -> Node | None:
|
||||
matter = db.get(Matter, matter_id)
|
||||
return db.get(Node, matter.node_id) if matter is not None else None
|
||||
|
||||
|
||||
def _deadline_link(matter_id) -> str:
|
||||
return f"#/matters/{matter_id}?tab=deadlines"
|
||||
|
||||
@@ -163,7 +168,16 @@ def _run_correspondence(db: DbSession, today: dt.date) -> int:
|
||||
"some items were not chased this cycle.", SCAN_LIMIT)
|
||||
for item in undated:
|
||||
extra = ([db.get(AppUser, item.created_by_id)] if item.created_by_id else [])
|
||||
for user in {u.id: u for u in recipients + [u for u in extra if u]}.values():
|
||||
candidates = {u.id: u for u in recipients + [u for u in extra if u]}
|
||||
if item.matter_id is not None:
|
||||
# A filed item belongs to its matter, and its subject is that matter's business:
|
||||
# nobody the matter's wall or grants exclude is told about it, administrators and
|
||||
# moderators included. Unassigned post is not yet any matter's, so it is unchanged.
|
||||
node = _matter_node(db, item.matter_id)
|
||||
allowed = ({u.id for u in _readable_by(db, node, set(candidates))}
|
||||
if node is not None else set())
|
||||
candidates = {k: v for k, v in candidates.items() if k in allowed}
|
||||
for user in candidates.values():
|
||||
if notify.push(
|
||||
db, user.id, kind=NotificationKind.service_date_missing,
|
||||
title=f"Brak daty doręczenia: {item.subject}",
|
||||
|
||||
@@ -55,7 +55,8 @@ def dashboard(db: DbSession, user: AppUser) -> dict:
|
||||
# Real COUNTs, not len() of a capped list — a card that reads "50" when there are 60 is
|
||||
# worse than no card, because it looks like the whole picture.
|
||||
inbox_count = correspondence.count_inbox(db)
|
||||
undated_count = correspondence.count_undated(db)
|
||||
# Counted as the reader sees it: filed items behind a wall are not theirs to count.
|
||||
undated_count = correspondence.undated_for(db, user, limit=0)[1]
|
||||
|
||||
return {
|
||||
"cards": {
|
||||
|
||||
@@ -226,6 +226,28 @@ def test_undated_authoritative_post_is_chased(db, admin):
|
||||
assert len(_notes(db, admin, f"corr:{item.id}:undated")) == 1
|
||||
|
||||
|
||||
def test_a_walled_administrator_is_not_told_about_a_filed_undated_item(db, admin, matter):
|
||||
"""The undated chase used to go to every administrator, subject in the title, for items
|
||||
already filed in a matter — a wall the reminder walked straight through."""
|
||||
from app.enums import CorrespondenceChannel
|
||||
from app.services import correspondence as corr, matters as matters_svc, reminders
|
||||
|
||||
matters_svc.set_wall(db, matter, admin, user_id=admin.id, reason="test")
|
||||
item = corr.record(db, admin, channel=CorrespondenceChannel.court_portal,
|
||||
subject="Za murem " + uuid.uuid4().hex[:6], matter_id=matter.id)
|
||||
db.flush()
|
||||
try:
|
||||
reminders.run(db)
|
||||
assert _notes(db, admin, f"corr:{item.id}:undated") == []
|
||||
shown, total = corr.undated_for(db, admin, limit=500)
|
||||
assert item.id not in {i.id for i in shown}
|
||||
finally:
|
||||
matters_svc.clear_wall(db, matter, admin.id)
|
||||
db.commit()
|
||||
reminders.run(db)
|
||||
assert len(_notes(db, admin, f"corr:{item.id}:undated")) == 1
|
||||
|
||||
|
||||
def test_counts_are_not_capped_by_the_display_limit(db, admin):
|
||||
"""Regression: the pulpit card was `len(undated(limit=50))`, so a firm with 55 neglected
|
||||
items saw "50" — and the reminder engine, iterating the same truncated list, never chased
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
"""Four holes found by a source review (2026-11-26), one rule each. DB-free.
|
||||
|
||||
1. The undated list in the inbox held items already FILED in a matter, and showed them — and counted
|
||||
them — to everybody; `assign` then let anyone who could work on some matter pull such an item out
|
||||
of one they were walled from.
|
||||
2. A conflict hit described the matter it was found in (reference, title, status) to a reader who
|
||||
may not open that matter.
|
||||
3. Deleting a matter deleted its AML assessments: the key cascaded, and a cascade runs as the table's
|
||||
owner, so the runtime role's missing DELETE did not stop it.
|
||||
4. The check that opens a matter did not have to be a check on that matter's client.
|
||||
|
||||
The reminder half of (1) needs the resolver and a real wall, so it is in `test_reminders.py`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.errors import ConflictError, NotFoundError
|
||||
from app.models import AmlAssessment, Matter, Node
|
||||
from app.schemas import conflict_out
|
||||
from app.services import conflicts, correspondence as corr, matters, nodes
|
||||
|
||||
VERSIONS = Path(__file__).resolve().parents[1] / "alembic" / "versions"
|
||||
|
||||
|
||||
class _Rows:
|
||||
def __init__(self, rows):
|
||||
self._rows = list(rows)
|
||||
|
||||
def all(self):
|
||||
return list(self._rows)
|
||||
|
||||
|
||||
class _Db:
|
||||
"""`scalars` answers from a queue, one list per call, in the order the code asks."""
|
||||
|
||||
def __init__(self, *answers, scalar=None):
|
||||
self._answers = list(answers)
|
||||
self._scalar = list(scalar or [])
|
||||
self.deleted = []
|
||||
|
||||
def scalars(self, _stmt):
|
||||
return _Rows(self._answers.pop(0))
|
||||
|
||||
def scalar(self, _stmt):
|
||||
return self._scalar.pop(0) if self._scalar else None
|
||||
|
||||
def delete(self, row):
|
||||
self.deleted.append(row)
|
||||
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
|
||||
# ── 1. undated correspondence ────────────────────────────────────────────────
|
||||
def _item(matter_id=None):
|
||||
return SimpleNamespace(id=uuid.uuid4(), matter_id=matter_id, status=None,
|
||||
assigned_by_id=None, assigned_at=None)
|
||||
|
||||
|
||||
def test_undated_list_hides_filed_items_the_reader_cannot_see(monkeypatch):
|
||||
mine, walled = uuid.uuid4(), uuid.uuid4()
|
||||
loose, filed_mine, filed_walled = _item(), _item(mine), _item(walled)
|
||||
monkeypatch.setattr(corr, "visible_for_matter_ids", lambda db, user, items: {mine})
|
||||
shown, total = corr.undated_for(_Db([loose, filed_walled, filed_mine]), object(), limit=50)
|
||||
assert shown == [loose, filed_mine]
|
||||
# Counted after the filter: "3" next to two rows says a third exists.
|
||||
assert total == 2
|
||||
|
||||
|
||||
def test_undated_total_is_not_capped_by_the_page(monkeypatch):
|
||||
rows = [_item() for _ in range(5)]
|
||||
monkeypatch.setattr(corr, "visible_for_matter_ids", lambda db, user, items: set())
|
||||
shown, total = corr.undated_for(_Db(rows), object(), limit=2)
|
||||
assert len(shown) == 2 and total == 5
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def assign_world(monkeypatch):
|
||||
"""`assert_role` raises NotFoundError for the walled matter and records every call."""
|
||||
walled = SimpleNamespace(id=uuid.uuid4(), name="za murem")
|
||||
target = SimpleNamespace(id=uuid.uuid4(), name="moja")
|
||||
calls = []
|
||||
|
||||
def assert_role(db, user, matter, minimum):
|
||||
calls.append(matter.id)
|
||||
if matter is walled:
|
||||
raise NotFoundError("Nie znaleziono.")
|
||||
|
||||
monkeypatch.setattr(corr.matters_svc, "assert_role", assert_role)
|
||||
monkeypatch.setattr(corr.matters_svc, "get_matter",
|
||||
lambda db, mid: {walled.id: walled, target.id: target}[mid])
|
||||
monkeypatch.setattr(corr, "derived_deadlines", lambda db, item: [])
|
||||
return SimpleNamespace(walled=walled, target=target, calls=calls)
|
||||
|
||||
|
||||
def test_assign_is_authorized_on_the_matter_the_item_leaves(assign_world):
|
||||
item = _item(assign_world.walled.id)
|
||||
with pytest.raises(NotFoundError):
|
||||
corr.assign(_Db(), item, assign_world.target, SimpleNamespace(id=uuid.uuid4()))
|
||||
assert item.matter_id == assign_world.walled.id
|
||||
# The current matter is asked first, so the refusal is the wall's 404.
|
||||
assert assign_world.calls == [assign_world.walled.id]
|
||||
|
||||
|
||||
def test_assign_from_the_inbox_asks_only_the_destination(assign_world):
|
||||
item = _item()
|
||||
corr.assign(_Db(), item, assign_world.target, SimpleNamespace(id=uuid.uuid4()))
|
||||
assert item.matter_id == assign_world.target.id
|
||||
assert assign_world.calls == [assign_world.target.id]
|
||||
|
||||
|
||||
def test_a_filed_item_with_derived_deadlines_does_not_move(assign_world, monkeypatch):
|
||||
other = SimpleNamespace(id=uuid.uuid4())
|
||||
monkeypatch.setattr(corr.matters_svc, "get_matter", lambda db, mid: other)
|
||||
monkeypatch.setattr(corr, "derived_deadlines", lambda db, item: ["termin"])
|
||||
item = _item(other.id)
|
||||
with pytest.raises(ConflictError):
|
||||
corr.assign(_Db(), item, assign_world.target, SimpleNamespace(id=uuid.uuid4()))
|
||||
assert item.matter_id == other.id
|
||||
|
||||
|
||||
# ── 2. conflict hits ─────────────────────────────────────────────────────────
|
||||
def _hit(matter_id):
|
||||
return {"kind": "client_conflict", "severity": 3, "party_id": str(uuid.uuid4()),
|
||||
"party_name": "Nowak Transport sp. z o.o.", "matched_name": "Nowak", "score": 1.0,
|
||||
"matter_id": str(matter_id) if matter_id else None,
|
||||
"matter_reference": "2026/0002" if matter_id else None,
|
||||
"matter_name": "Spór o roboty budowlane" if matter_id else None,
|
||||
"matter_status": "open" if matter_id else None, "role": "client", "is_adverse": False}
|
||||
|
||||
|
||||
def test_a_hit_in_a_matter_the_reader_cannot_open_keeps_the_hit_not_the_matter(monkeypatch):
|
||||
open_node, walled_node = uuid.uuid4(), uuid.uuid4()
|
||||
readable = Matter(id=uuid.uuid4(), node_id=open_node)
|
||||
walled = Matter(id=uuid.uuid4(), node_id=walled_node)
|
||||
gone = uuid.uuid4() # a matter deleted since the check was frozen
|
||||
hits = [_hit(readable.id), _hit(walled.id), _hit(gone), _hit(None)]
|
||||
frozen = [dict(h) for h in hits]
|
||||
monkeypatch.setattr(conflicts.authz, "readable_node_ids",
|
||||
lambda db, user, found: {open_node})
|
||||
db = _Db([readable, walled], [Node(id=open_node), Node(id=walled_node)])
|
||||
[shown] = conflicts.visible_hits(db, object(), [hits])
|
||||
|
||||
assert shown[0]["matter_reference"] == "2026/0002"
|
||||
hidden = shown[1]
|
||||
assert hidden["matter_hidden"] is True
|
||||
assert all(hidden[key] is None for key in conflicts.MATTER_FIELDS)
|
||||
# Everything a decision needs is still there.
|
||||
assert hidden["kind"] == "client_conflict" and hidden["party_name"] and hidden["severity"] == 3
|
||||
assert shown[2]["matter_reference"] == "2026/0002" # no wall left to keep
|
||||
assert shown[3] == hits[3]
|
||||
assert hits == frozen # the evidence is never rewritten
|
||||
|
||||
|
||||
def test_no_matter_in_any_hit_asks_nothing():
|
||||
class _NoDb:
|
||||
def scalars(self, _stmt):
|
||||
raise AssertionError("queried for hits that name no matter")
|
||||
loose = [_hit(None)]
|
||||
assert conflicts.visible_hits(_NoDb(), object(), [loose, []]) == [loose, []]
|
||||
|
||||
|
||||
def test_a_check_cannot_leave_without_the_readers_view_of_its_hits():
|
||||
check = SimpleNamespace(id=uuid.uuid4(), hits=[_hit(uuid.uuid4())])
|
||||
with pytest.raises(TypeError):
|
||||
conflict_out(check)
|
||||
|
||||
|
||||
# ── 3. AML assessments outlive a deleted matter ──────────────────────────────
|
||||
def test_aml_key_does_not_cascade():
|
||||
fk = next(iter(AmlAssessment.__table__.c.matter_id.foreign_keys))
|
||||
assert fk.column.table.name == "matter" and fk.ondelete is None
|
||||
|
||||
|
||||
def test_deleting_a_matter_with_aml_records_is_refused_in_words():
|
||||
db = _Db(scalar=["2026/0007"])
|
||||
node = Node(id=uuid.uuid4(), path="/firma/sprawa")
|
||||
with pytest.raises(ConflictError, match="AML"):
|
||||
nodes.delete(db, node)
|
||||
assert db.deleted == []
|
||||
|
||||
|
||||
def test_revision_0007_sql_has_no_bind_parameter_lookalikes():
|
||||
source = (VERSIONS / "0007_aml_survives_matter_delete.py").read_text(encoding="utf-8")
|
||||
assert 'down_revision = "0006"' in source
|
||||
sql = re.search(r'_REKEY = """(.*?)"""', source, re.S).group(1)
|
||||
assert "%" not in sql and not re.search(r"(?<!:):[A-Za-z_]", sql)
|
||||
assert "current_schema()" in sql and "CASCADE" not in sql
|
||||
|
||||
|
||||
# ── 4. the check must be a check on this client ──────────────────────────────
|
||||
@pytest.fixture
|
||||
def no_aliases(monkeypatch):
|
||||
monkeypatch.setattr(matters.parties_svc, "aliases_for", lambda db, party: [])
|
||||
|
||||
|
||||
def _check(subject, lead_id=None):
|
||||
return SimpleNamespace(subject=subject, lead_id=lead_id)
|
||||
|
||||
|
||||
def test_a_check_on_another_name_does_not_open_a_matter(no_aliases):
|
||||
client = SimpleNamespace(name="Nowak Transport sp. z o.o.")
|
||||
with pytest.raises(ConflictError, match="nie klienta"):
|
||||
matters.assert_check_covers(_Db(), _check("Zupełnie Inna Firma"), client, None)
|
||||
|
||||
|
||||
def test_the_engines_own_name_match_covers_the_client(no_aliases):
|
||||
client = SimpleNamespace(name="Kowalski Nieruchomości sp. z o.o.")
|
||||
matters.assert_check_covers(_Db(), _check("Kowalski Nieruchomości sp. z o.o."), client, None)
|
||||
matters.assert_check_covers(_Db(), _check("Kowalski"), client, None)
|
||||
|
||||
|
||||
def test_an_alias_covers_the_client(monkeypatch):
|
||||
monkeypatch.setattr(matters.parties_svc, "aliases_for",
|
||||
lambda db, party: [SimpleNamespace(alias="Hala Magazynowa Wola")])
|
||||
client = SimpleNamespace(name="KNW sp. z o.o.")
|
||||
matters.assert_check_covers(_Db(), _check("Hala Magazynowa Wola"), client, None)
|
||||
|
||||
|
||||
def test_a_name_too_short_to_stem_is_compared_whole(no_aliases):
|
||||
matters.assert_check_covers(_Db(), _check("AB"), SimpleNamespace(name="AB"), None)
|
||||
with pytest.raises(ConflictError):
|
||||
matters.assert_check_covers(_Db(), _check("AB"), SimpleNamespace(name="XY"), None)
|
||||
|
||||
|
||||
def test_the_lead_must_be_the_one_the_check_was_run_for(no_aliases):
|
||||
lead = uuid.uuid4()
|
||||
client = SimpleNamespace(name="Nowak Transport sp. z o.o.")
|
||||
matters.assert_check_covers(_Db(), _check(client.name, lead), client, lead)
|
||||
matters.assert_check_covers(_Db(), _check(client.name, lead), client, None)
|
||||
with pytest.raises(ConflictError, match="zapytania"):
|
||||
matters.assert_check_covers(_Db(), _check(client.name, lead), client, uuid.uuid4())
|
||||
with pytest.raises(ConflictError, match="zapytania"):
|
||||
matters.assert_check_covers(_Db(), _check(client.name, None), client, lead)
|
||||
+3
-1
@@ -416,6 +416,7 @@ const I18N = {
|
||||
'podmiot jest stroną przeciwną w innej sprawie': 'party is an opposing party in another matter',
|
||||
'podmiot powiązany': 'related party', 'znany nam podmiot': 'known party',
|
||||
'Rodzaj trafienia': 'Hit type', 'Dopasowanie': 'Match', 'bez wskazanej strony przeciwnej': 'no opposing party given',
|
||||
'sprawa, do której nie masz dostępu': 'a matter you have no access to',
|
||||
'Uzasadnienie decyzji': 'Reason for the decision',
|
||||
'np. zgoda obu klientów na piśmie z 2026-07-14, wdrożono chiński mur': 'e.g. both clients consented in writing on 2026-07-14, ethical wall in place',
|
||||
'Odmawiamy zlecenia': 'Decline the instruction', 'Zgoda — prowadzimy': 'Waive — we act',
|
||||
@@ -3487,7 +3488,8 @@ function hitsHtml(hits) {
|
||||
</tr></thead><tbody>${hits.map((h) => `<tr>
|
||||
<td><span class="stripe s${h.severity}">${esc(h.party_name)}</span><div class="faint tiny" style="padding-left:12px">szukane: ${esc(h.matched_name)}</div></td>
|
||||
<td class="tiny">${esc(label[h.kind] || h.kind)}${h.role ? `<div class="faint">rola: ${esc(PARTY_ROLE[h.role] || h.role)}</div>` : ''}</td>
|
||||
<td class="tiny">${h.matter_reference ? esc(h.matter_reference) + ' ' + esc(h.matter_name || '') : '—'}</td>
|
||||
<td class="tiny">${h.matter_reference ? esc(h.matter_reference) + ' ' + esc(h.matter_name || '')
|
||||
: (h.matter_hidden ? '<span class="faint">sprawa, do której nie masz dostępu</span>' : '—')}</td>
|
||||
<td class="num">${Math.round(h.score * 100)}%</td>
|
||||
</tr>`).join('')}</tbody></table></div>`;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user