21 Commits
Author SHA1 Message Date
adminandClaude Opus 5.5 e1c979c734 Fetch private dredd-core from the Haski Gitea, not GitHub
CI / backend (16) (push) Successful in 3m19s
CI / compose-smoke (push) Successful in 1m36s
CI / managed-db (push) Successful in 2m40s
CI / backend (17) (push) Successful in 3m20s
The Dockerfiles still rewrote credentials for github.com only, so the build
token never reached Gitea and installs worked only while dredd-core was
public. Rewrite http://77.216.148.202:3000/ instead, give every workflow
that pip-installs the same rewrite (org secret DREDD_CORE_TOKEN, the
read-only haski-reader token), and drop the GitHub PAT leftovers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 22:18:42 +01:00
adminandClaude Opus 5.5 3907b33213 CI: allow a manual run (Actions -> CI -> Run workflow)
CI / backend (16) (push) Successful in 4m28s
CI / managed-db (push) Successful in 3m24s
CI / backend (17) (push) Successful in 4m17s
CI / compose-smoke (push) Successful in 1m17s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 20:06:30 +01:00
adminandClaude Opus 5.5 9230e24fbe CI: push runs only on main; branches are tested through their pull request [skip ci]
A push of many branches at once (the migration pushed 100 of Atrium's) started
a run per branch and flooded the runners. Every pull request is still tested.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 16:39:14 +01:00
adminandClaude Opus 5.5 02bb267ebb Build from Gitea instead of GitHub
CI / backend (17) (push) Successful in 5m13s
CI / backend (16) (push) Successful in 7m33s
CI / managed-db (push) Successful in 3m26s
CI / compose-smoke (push) Successful in 2m50s
The Alpaq92 GitHub account is suspended, so nothing can be fetched from it.
dredd-core (and Lexicon's compass packages from Arbiter) now come from the
public Haski repositories on Gitea, so CI no longer authenticates to GitHub:
the "Authenticate to dredd-core" steps and insteadOf rewrites are gone.
The Dockerfile's dredd_core_token build secret stays; any non-empty value
works now (the Haski org secret DREDD_CORE_TOKEN provides one in CI).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 17:05:32 +01:00
admin 4fee196c84 Merge pull request #16 from Alpaq92/fix/walls-evidence-intake
Walls, evidence and the intake gate: four fixes from a source review
2026-11-28 10:39:41 +01:00
Piotr ChojnackiandClaude Opus 5.5 3215c3d569 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>
2026-11-26 20:47:08 +01:00
admin 88a4ae6f15 Merge pull request #14 into main 2026-11-24 20:18:40 +01:00
admin 1a7e957709 Merge pull request #15 into main 2026-11-24 20:18:29 +01:00
Piotr ChojnackiandClaude Opus 5.5 c31214a832 Console a11y: every list opens from the keyboard, and a dialog keeps and returns focus
A pass against the Web Interface Guidelines (and Atrium's console, which already does most
of this):

- The ten clickable tables — deadlines, matters, parties, conflict checks (three places),
  enquiries, invoices (two) and profitability — were mouse-only: the <tr> had the click and
  nothing in the row could take focus, so a keyboard or screen-reader user could not open a
  matter, a party or an invoice from any list. The first cell now holds the way in: a link
  (rowLink) for a row that navigates, a button (rowBtn, .rowbtn) for one that opens a dialog.
  The row keeps its click; both look exactly as before until focused. An invoice without a
  number yet is named "Faktura bez numeru" instead of a bare dash.
- The account avatar was a <span> with a click handler, so the account sheet — sign-out, and
  on a phone every .js-tool — could not be opened from the keyboard. It is a button now, as
  in Atrium and Parafa (aria-label "Konto", aria-haspopup="dialog"); the shared .avatar rule
  already styles a button identically.
- A dialog makes the page behind it inert (aria-modal alone does not stop Tab), focuses its
  first field or else its first RENDERED control (the account sheet's .m-only rows are
  display:none on a desktop and cannot take focus), and closeModal() gives focus back to
  whatever opened it instead of dropping it on <body>. The opener is remembered before the
  page goes inert. The search palette does the same, and its input is labelled.
- The sign-in and dialog error banners are role=alert, so errors are announced.

Checked in the demo console (demo.js) with real key presses: Enter on a list link opens the
matter; the record-time dialog keeps focus through 30 Tabs and Escape returns it to the
button; the account sheet opens from the avatar with focus on "Zamknij" and Escape returns
it; Ctrl+K / Escape returns focus too. node --check frontend/app.js passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 21:55:11 +01:00
tobayahandClaude Opus 5.5 deb5e27ea3 Console EN: the fixed labels the backend sends, and the demo's chrome
The English console still showed Polish wherever the text comes from the API
rather than from app.js: the AML risk factors and their legal bases, the fee
calculator's proceedings, stages, sources and note, the built-in document
templates and their bases, how a rate was resolved ("cennik kancelarii „X”
(stopień: partner)") and the basis of a deadline counted from a service date.

These are closed sets defined in aml.py, fees.py, documents.py, rates.py and
deadlines.py, so they get keys like any other label; the ones framed by numbers
or a card name get anchored patterns that carry the number or the name through.
The new frame patterns (an option's fraction or percentage, a multiplier, a dash
before a basis) answer null unless the label inside is a known key, so user data
in the same shape is left alone. Bare statutory references in the fee basis
lines ("art. 13 ust. 1 pkt 2 u.k.s.c.") stay as cited.

The "preview only for built-in templates" message is written into a <pre>, which
localize() skips as raw content, so it is now passed through _tr by hand.

demo.js's login note and its two refusals get keys too: the demo is the deploy
an English visitor is most likely to see.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 17:40:36 +01:00
tobayahandClaude Opus 5.5 f257342042 Console EN: the strings the language switch still left in Polish
A static scan of app.js plus a crawl of the demo console in English found the
console's own text that never reached I18N: the matter search placeholder, the
"Billable time" tile, the party-link and remove-party messages, the declined
engagement toast, the first AML assessment heading, the notification "In the app"
switch, the unpaid-invoice cap note and the "Basis:" line of a document preview.

The AML "replace the current assessment" confirm had its key but called confirm()
without _tr, so it stayed Polish. The register lookup's pattern only took a
one-word source, so "Biała lista" (the VAT White List) fell through it.

Restoring a backup asked an English reader to type PRZYWRÓĆ. The word is now
translated with the page (RESTORE) and either spelling unlocks the restore.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 17:35:44 +01:00
adminandClaude Opus 5.5 124bc0e666 GET /stats: Sygna answers dredd-core's stats contract (M4, Panorama's tiles)
Two tiles, each counted for the caller by the very function its console list
calls, with the same arguments: open matters (matters.list_matters with
status=open; #/matters?status=open) and deadlines (deadlines.upcoming with the
Terminy screen's 60-day horizon, overdue included; #/deadlines). Behind the
session like every route, so Panorama's call with the person's own token sees
exactly that person's numbers.

dredd-core repinned v0.21.0 -> v0.23.0 (0.22.0 is opt-in, no change here).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 09:36:56 +01:00
admin 2e35f840c8 Merge pull request #13 from Alpaq92/shared-pin
SHARED.md: stop quoting the dredd-core pin, so a repin cannot fail CI again
2026-11-13 12:33:44 +01:00
Piotr ChojnackiandClaude Opus 5.5 e0bce880a6 SHARED.md points to the dredd-core pin instead of quoting it
Every repin from v0.17.0 to v0.21.0 left SHARED.md's quoted version behind and
failed "Deploy pre-flight". The quote existed so the page would not mislead;
checking that it matched only moved the failure to CI. requirements.txt is now
the one place the version is written. deploy_check.py fails if SHARED.md quotes
one again, and if it stops saying where the pin lives.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 12:15:29 +01:00
Piotr ChojnackiandClaude Opus 5.5 47b0ed44a4 SHARED.md: quote dredd-core v0.21.0, the pin requirements.txt installs
The K2 repin moved requirements.txt to v0.21.0 and left SHARED.md on v0.19.0,
so deploy_check.py fails "Deploy pre-flight" again, for the fourth repin in a
row. This commit only catches up; the next one stops it recurring.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 12:14:33 +01:00
adminandClaude Opus 5.5 ea18353e8d 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>
2026-11-11 12:33:07 +01:00
admin dec9dd1b65 Merge pull request #8 from Alpaq92/wyglad-i-jezyk
Console fully in English, palette focus fix
2026-11-10 20:33:27 +01:00
admin 13ed606329 Merge pull request #12 from Alpaq92/ci-fix
CI: quote the installed dredd-core pin, and stop racing curl into grep
2026-11-10 20:33:23 +01:00
tobayahandClaude Opus 5.5 2fa46291f6 Merge main (#11) into the English console, and carry #10's one line
The conflict was the dictionary's head: main had grown a short EN block of
its own. Both are kept as one; where they disagreed this branch's wording
stays (it was already the later key, so the console read it that way).

#11 reworded about thirty sentences after this translation was written, and
localize() matches by exact text, so each of those would have stayed Polish
without a conflict to say so. They have keys now, plus three patterns for
text built around a number or a date (the dashboard's deadline tile, the
reports' period line, the receivables total).

From #10, closed in favour of this: on the platform the module's own menu
leaves out its settings entry, because Atrium's Ustawienia opens it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uwxqGUzevJUNi45tARDzL
2026-11-09 17:48:37 +01:00
tobayahandClaude Opus 5.5 54ab78f31c Console: translate the whole UI to English, on top of applyLang
A dictionary plus patterns for strings with numbers and dates, applied
only in EN, now riding on window.applyLang: the language still changes in
place, from each node's Polish source, and the MutationObserver that
catches screens written after load is installed in both languages
(localize() stays a no-op until the page has shown EN). The tab title
follows the language too.

Data, legal texts from Sygna's backend and the pl-PL number/date format
stay Polish on purpose.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011DXFYDzg1AAJGH56afAFAo
2026-10-23 16:14:01 +02:00
tobayah 58c06a48f0 ui/v1: no focus box inside the command palette's capsule
The bare-input focus ring (zero-specificity :where rule) also matched the palette's query field and drew a rectangle inside the capsule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01SMnEzCfhURcxL2ZZTLa3YY
(cherry picked from commit 4a88e8e10f2047d0343271ea46b50a9b6ce69206)
2026-10-23 16:11:40 +02:00
41 changed files with 1886 additions and 146 deletions
+22 -17
View File
@@ -1,5 +1,20 @@
name: CI
on: [push, pull_request]
on:
push:
# main only: a branch is tested through its pull request (a push of many branches at once
# must not flood the runners)
branches: [main]
pull_request:
workflow_dispatch: # manual run: Actions -> CI -> Run workflow
# dredd-core is private on the Haski Gitea, and so is every repository this workflow may fetch.
# All git traffic to the Gitea host (pip installing dredd-core from requirements, above all) goes
# through the read-only bot haski-reader: its token is the Haski org secret DREDD_CORE_TOKEN,
# which Gitea masks in logs. Docker builds get the same token as a BuildKit secret instead.
env:
GIT_CONFIG_COUNT: "1"
GIT_CONFIG_KEY_0: url.http://x-access-token:${{ secrets.DREDD_CORE_TOKEN }}@77.216.148.202:3000/.insteadOf
GIT_CONFIG_VALUE_0: http://77.216.148.202:3000/
jobs:
backend:
@@ -32,7 +47,7 @@ jobs:
SECRET_KEY: ci-not-a-real-key-0123456789abcdef
# `secrets` is not available in a step-level `if`, so the presence of the token becomes a
# job-level env var the conditional can read.
HAS_GALENA: ${{ secrets.GALENA_REPO_TOKEN != '' }}
HAS_GALENA: "true"
SYGNA_RUN_INTEGRATION: "1"
steps:
- uses: actions/checkout@v5
@@ -51,26 +66,19 @@ jobs:
-- EXISTS then no-ops, so the least-privilege migrator never needs extension rights.
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
SQL
# dredd-core is a private repo, so the checkout token cannot reach it. A fine-grained
# read-only PAT stored as DREDD_CORE_TOKEN lets pip clone it; `url.insteadOf` keeps the
# credential out of requirements.txt, where it would be committed.
- name: Authenticate to dredd-core
run: |
git config --global url."https://x-access-token:${{ secrets.DREDD_CORE_TOKEN }}@github.com/".insteadOf "https://github.com/"
# Two checks are only real with Galena present: `shared_check.py` (the three files still
# genuinely copied) and `test_galena_contract.py` (every path Sygna calls must exist in
# Galena's router table — the check that would have caught `/files/` vs `/projects/`).
# Both skip cleanly without it, so a fork or a contributor without access still gets a
# green build; they simply get a smaller one. Needs GALENA_REPO_TOKEN, a fine-grained
# read-only PAT for Alpaq92/Galena — secrets are per-repository and DREDD_CORE_TOKEN does
# not reach it.
# green build; they simply get a smaller one. Needs GALENA_REPO_TOKEN (Haski org secret,
# haski-reader's read-only token): Galena is private and the job token only reaches Sygna.
- name: Check out Galena (for the cross-application checks)
if: env.HAS_GALENA == 'true'
uses: actions/checkout@v5
with:
repository: Alpaq92/Galena
token: ${{ secrets.GALENA_REPO_TOKEN }}
repository: Haski/Galena
path: .galena
token: ${{ secrets.GALENA_REPO_TOKEN }}
- name: Install deps
working-directory: backend
run: pip install -r requirements-dev.txt
@@ -179,9 +187,6 @@ jobs:
- uses: actions/checkout@v5
- uses: actions/setup-python@v6
with: { python-version: "3.12" }
- name: Authenticate to dredd-core
run: |
git config --global url."https://x-access-token:${{ secrets.DREDD_CORE_TOKEN }}@github.com/".insteadOf "https://github.com/"
- name: Install deps
working-directory: backend
run: pip install -r requirements-dev.txt
@@ -253,7 +258,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: |
+22 -3
View File
@@ -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
@@ -605,6 +622,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
+3 -5
View File
@@ -6,11 +6,9 @@ failed if they drifted. This document was the list, and the rule was "change bot
the same commit".
That is over. The substrate is **[`dredd-core`](https://github.com/Alpaq92/dredd-core)** — a
private package, Apache-2.0, pinned in `backend/requirements.txt`:
```
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.19.0
```
private package, Apache-2.0, pinned to a git tag in `backend/requirements.txt`. That line is the
one place the version is written, so this page does not repeat it: a quoted copy fell behind the
real pin on four repins in a row, and `deploy_check.py` failed CI every time.
Both applications import it. There is nothing left to keep diff-clean, because there is only one
copy, and "which version" is a line in a requirements file rather than a property of two working
+3 -3
View File
@@ -1,7 +1,7 @@
# syntax=docker/dockerfile:1
# ── build stage: resolve dependencies, including the private one ─────────────
# `dredd-core` is a private GitHub repository pinned by tag in requirements.txt, so installing it
# `dredd-core` is a private repository on the Haski Gitea pinned by tag in requirements.txt, so installing it
# needs two things the runtime image should never have: `git`, and a credential.
#
# The credential arrives as a BuildKit SECRET, not a build argument. A build arg is baked into the
@@ -21,8 +21,8 @@ WORKDIR /build
COPY requirements.txt .
RUN --mount=type=secret,id=dredd_core_token,required=true \
GIT_CONFIG_COUNT=1 \
GIT_CONFIG_KEY_0="url.https://x-access-token:$(cat /run/secrets/dredd_core_token)@github.com/.insteadOf" \
GIT_CONFIG_VALUE_0="https://github.com/" \
GIT_CONFIG_KEY_0="url.http://x-access-token:$(cat /run/secrets/dredd_core_token)@77.216.148.202:3000/.insteadOf" \
GIT_CONFIG_VALUE_0="http://77.216.148.202:3000/" \
pip install --no-cache-dir --prefix=/install -r requirements.txt
# ── runtime stage: no git, no credential, no compiler ────────────────────────
+4 -1
View File
@@ -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))
@@ -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"))
+5 -1
View File
@@ -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)
+15
View File
@@ -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",
+5 -3
View File
@@ -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(
+6
View File
@@ -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"),
)
+15 -8
View File
@@ -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]
+3 -2
View File
@@ -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,
}
+7
View File
@@ -62,6 +62,13 @@ def dashboard(db: Session = Depends(get_db), user: AppUser = Depends(get_current
return stats.dashboard(db, user)
@router.get("/stats")
def module_stats(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
"""dredd-core's stats contract, read by Panorama with the person's own session: counts this
person can see, each equal to the list its tile links to."""
return stats.module_stats(db, user)
@router.get("/activity")
def activity(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)):
"""The user's own actions plus activity on matters they can read — never the global log."""
+4 -3
View File
@@ -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}")
+1
View File
@@ -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
+8 -3
View File
@@ -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,
@@ -513,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),
+4 -2
View File
@@ -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-"
+43 -2
View File
@@ -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
+44 -1
View File
@@ -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)
+35 -1
View File
@@ -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(
+22 -2
View File
@@ -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)
+66
View File
@@ -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:
+15 -1
View File
@@ -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}",
+29 -1
View File
@@ -7,15 +7,18 @@ from __future__ import annotations
import datetime as dt
from dredd_core import stats_contract
from sqlalchemy import select
from sqlalchemy.orm import Session as DbSession
from ..config import get_settings
from ..enums import ConflictOutcome, MatterStatus
from ..models import AppUser, ConflictCheck, Lead, Matter, Node
from . import (
authz,
correspondence,
deadlines as deadlines_svc,
matters as matters_svc,
settings as settings_svc,
timelog,
)
@@ -52,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": {
@@ -107,3 +111,27 @@ def dashboard(db: DbSession, user: AppUser) -> dict:
for d, m in unconfirmed[:10]
],
}
#: The horizon of the Terminy screen (`viewDeadlines` asks `/deadlines?days=60`): the tile must count
#: exactly that list, so it uses the same number, not the dashboard's `deadline_horizon_days`.
DEADLINES_SCREEN_DAYS = 60
def module_stats(db: DbSession, user: AppUser) -> dict:
"""`GET /stats`: dredd-core's stats contract (Panorama's tiles). Each count is the length of the
list its link opens, for this person, computed by the very function that list calls with the
very arguments the console passes: `matters.list_matters(status=open)` for
`#/matters?status=open` and `deadlines.upcoming(days=60)` for `#/deadlines`. Nothing here
re-implements access."""
tiles = [
stats_contract.make_tile(
key="open_matters", label="Otwarte sprawy",
count=len(matters_svc.list_matters(db, user, status=MatterStatus.open)),
link="matters?status=open"),
stats_contract.make_tile(
key="deadlines", label="Terminy (60 dni i zaległe)",
count=len(deadlines_svc.upcoming(db, user, days=DEADLINES_SCREEN_DAYS)),
link="deadlines"),
]
return stats_contract.make_response(get_settings().module_slug, tiles)
+5 -1
View File
@@ -76,4 +76,8 @@ 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).
# v0.23.0 brings `dredd_core.stats_contract` (the Compass split's M4): `GET /stats`, Panorama's tiles
# (services/stats.module_stats). 0.22.0 comes along and is opt-in (no table, no change here).
dredd-core @ git+http://77.216.148.202:3000/Haski/dredd-core.git@v0.23.0
+15
View File
@@ -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")
+12 -8
View File
@@ -179,14 +179,18 @@ check("DREDD_CORE_TOKEN" in read(".github/workflows/ci.yml"),
"CI cannot install dredd-core: the private repo needs DREDD_CORE_TOKEN",
"CI authenticates to the private dredd-core repo")
# SHARED.md quotes the pin. A quoted version that has fallen behind the real one is worse than no
# quote — it is documentation that reads as current and is wrong, which is how somebody ends up
# debugging against the wrong core. Found exactly that way: SHARED.md said v0.6.0 for a while
# after requirements.txt moved to v0.7.0.
_pin = requirements.split("dredd-core @ git+")[1].splitlines()[0].strip()
check(_pin in read("SHARED.md"),
f"SHARED.md quotes a different dredd-core pin than requirements.txt ({_pin})",
"SHARED.md quotes the pin that is actually installed")
# SHARED.md names where the pin lives and does not quote it. A quoted version that has fallen
# behind the real one is worse than no quote: it reads as current and is wrong, which is how
# somebody ends up debugging against the wrong core (SHARED.md said v0.6.0 after requirements.txt
# moved to v0.7.0). Checking that the quote matched only moved the failure: every repin from
# v0.17.0 to v0.21.0 broke CI here. One place for the version leaves nothing to keep in step.
_shared = read("SHARED.md")
check(not re.search(r"dredd-core\s*@\s*git\+\S*@v\d", _shared),
"SHARED.md quotes a dredd-core version: it goes stale on the next repin, "
"point to backend/requirements.txt instead",
"SHARED.md points to requirements.txt for the dredd-core pin instead of quoting it")
check("backend/requirements.txt" in _shared,
"SHARED.md no longer says where the dredd-core pin lives (backend/requirements.txt)")
# ── the Netlify front door stays honest ──────────────────────────────────────
# It publishes the console alone. The demo mock is what makes a backend-less deploy worth having,
+51
View File
@@ -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
+22
View File
@@ -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
+4 -4
View File
@@ -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"))
+42
View File
@@ -0,0 +1,42 @@
"""`GET /stats` (dredd-core's stats contract, Panorama's tiles) - DB-free: the route exists behind
the session, and the body is built from the very functions the two lists call."""
from __future__ import annotations
from types import SimpleNamespace
from dredd_core import stats_contract
from app.enums import MatterStatus
from app.services import stats
def test_the_tiles_come_from_the_lists_own_functions(monkeypatch):
seen = {}
def list_matters(db, user, **kw):
seen["matters"] = (user, kw)
return [object()] * 3
def upcoming(db, user, **kw):
seen["deadlines"] = (user, kw)
return [object()] * 5
monkeypatch.setattr(stats.matters_svc, "list_matters", list_matters)
monkeypatch.setattr(stats.deadlines_svc, "upcoming", upcoming)
person = SimpleNamespace(id="p")
body = stats.module_stats(None, person)
stats_contract.validate_response(body)
assert body["module"] == "sygna"
assert [(t["key"], t["count"], t["link"]) for t in body["tiles"]] == [
("open_matters", 3, "matters?status=open"), ("deadlines", 5, "deadlines")]
# The same arguments the console's lists pass: no filter the screen does not apply itself.
assert seen == {"matters": (person, {"status": MatterStatus.open}),
"deadlines": (person, {"days": 60})}
def test_the_route_is_behind_the_session():
from fastapi.testclient import TestClient
from app.main import app
assert TestClient(app).get("/api/v1/stats").status_code == 401
+240
View File
@@ -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)
+2 -1
View File
@@ -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.
+1 -1
View File
@@ -1,7 +1,7 @@
# Sygna on a managed PostgreSQL database (the family's shared one, or any Postgres 16/17 reached
# over a network): an override for docker-compose.yml.
#
# DREDD_CORE_TOKEN=github_pat_... \
# DREDD_CORE_TOKEN=<read-only Gitea token> \
# docker compose -f docker-compose.yml -f docker-compose.managed-db.yml up -d --build
#
# The database lives elsewhere, so the local postgres service is switched off and nothing waits
+2 -2
View File
@@ -18,10 +18,10 @@
# On the platform the modules publish nothing and Atrium's front door keeps :80.
#
# BUILDING NEEDS A CREDENTIAL. dredd-core is a private repository, so the image build clones it
# with DREDD_CORE_TOKEN (a fine-grained, read-only GitHub PAT) supplied as a BuildKit secret —
# with DREDD_CORE_TOKEN (a read-only Gitea access token) supplied as a BuildKit secret —
# never a build arg, which would be readable in `docker history` of any pushed image:
#
# DREDD_CORE_TOKEN=github_pat_... docker compose up -d --build
# DREDD_CORE_TOKEN=<read-only Gitea token> docker compose up -d --build
services:
postgres:
image: postgres:16
+8
View File
@@ -122,6 +122,14 @@ a.tile:hover { background: var(--at-surface-hover); text-decoration: none; }
.stripe.s2 { border-left-color: var(--at-warning); }
.stripe.s1 { border-left-color: var(--border-input); }
/* The keyboard's way into a row that opens a dialog (rowBtn in app.js): a button that reads as the
cell's own text, as a row's link already does. The shell's :focus-visible ring still applies. */
.rowbtn {
margin: 0; padding: 0; border: 0; background: none;
font: inherit; color: inherit; text-align: inherit; cursor: pointer;
}
.rowbtn:hover { text-decoration: underline; }
.modal .field + .field, .modal .grid2 + .field, .modal .field + .grid2 { margin-top: 12px; }
/* ── breakpoints (Sygna's own; the shell's are in shell.css) ────────────── */
+872 -65
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -40,7 +40,7 @@
<button type="button" class="pw-eye" id="pwToggleLogin" title="Pokaż hasło" aria-label="Pokaż hasło"></button>
</span>
</label>
<div id="loginErr" class="banner err hidden"></div>
<div id="loginErr" class="banner err hidden" role="alert"></div>
<button class="btn primary" id="btnLogin" type="submit">Zaloguj się</button>
</form>
<!-- The other state of this screen, and the only one that is NOT about signing in: the session is
@@ -90,7 +90,7 @@
<button class="iconbtn" id="aBell" title="Powiadomienia" aria-label="Powiadomienia"></button>
<button class="iconbtn js-theme js-tool" id="aTheme" title="Motyw" aria-label="Motyw"></button>
<button class="iconbtn txt js-tool" id="aLang" title="Język" aria-label="Język" data-no-i18n>PL</button>
<span class="avatar" id="aUser" title="Konto">?</span>
<button type="button" class="avatar" id="aUser" title="Konto" aria-label="Konto" aria-haspopup="dialog">?</button>
</header>
<main class="content" id="content" tabindex="-1"></main>
</div>
+1
View File
@@ -391,6 +391,7 @@ td.mono { font-family: var(--at-font-mono); font-size: 12.5px; }
.search-modal .sin input {
flex: 1; border: 0; background: none; color: var(--at-text);
font: inherit; font-size: 18px; letter-spacing: var(--at-tracking-title); outline: none; padding: 0;
box-shadow: none; /* the capsule is the field; the bare-input focus ring would draw a box inside it */
}
.search-modal .sin input::placeholder { color: var(--at-text-placeholder); }
.search-results {