13 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
26 changed files with 810 additions and 84 deletions
+21 -16
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
+20 -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
+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 ────────────────────────
@@ -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 -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(
+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
+5 -2
View File
@@ -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),
+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)
+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)
+3 -1
View File
@@ -78,4 +78,6 @@ cryptography==46.0.3 # AES-256-GCM (Apache-2.0/BSD)
# dredd_core.search_contract, new in 0.17.0).
# v0.21.0 adds the platform's counterparty register (K2): Sygna WRITES it; party.counterparty_id links
# an organisation to its counterparty (revision 0006, services/parties.sync_counterparty).
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.21.0
# 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
+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
+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)
+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) ────────────── */
+159 -30
View File
@@ -22,6 +22,13 @@ const esc = (v) => String(v ?? '').replace(/[&<>"']/g, (c) =>
attribute, so left bare they cut the handler short and the click dies on a syntax error. */
const jsArg = (v) => esc(JSON.stringify(v));
/* A clickable row keeps its mouse click on the <tr>; these are the keyboard's and the screen
reader's way in, in the row's first cell — a link for a row that navigates, a button for one
that opens a dialog. stopPropagation, or one click would run both. */
const rowLink = (href, html) => `<a href="${esc(href)}" onclick="event.stopPropagation()">${html}</a>`;
const rowBtn = (fn, arg, html, label) =>
`<button type="button" class="rowbtn"${label ? ` aria-label="${esc(label)}"` : ''} onclick="event.stopPropagation();${fn}(${jsArg(arg)})">${html}</button>`;
/* "1 sprawa", "3 sprawy", "5 spraw". */
function plPlural(n, one, few, many) {
const a = Math.abs(n), d = a % 10, t = a % 100;
@@ -208,6 +215,7 @@ const I18N = {
'E-mail': 'Email', 'e-mail': 'email', 'Hasło': 'Password', 'Motyw': 'Theme', 'Język': 'Language',
'Konto': 'Account', 'Menu': 'Menu', 'Aplikacje': 'Apps', 'Powiadomienia': 'Notifications',
'Szukaj': 'Search', 'Szukaj…': 'Search…', 'Szukaj (Ctrl+K)': 'Search (Ctrl+K)',
'Faktura bez numeru': 'Invoice without a number',
'Zwiń panel': 'Collapse sidebar', 'Zwiń panel (Ctrl+B)': 'Collapse sidebar (Ctrl+B)',
'Kalkulator opłat sądowych': 'Court fee calculator',
// ── the menu groups, the settings tabs and the skip link (from main, #11) ──
@@ -247,7 +255,7 @@ const I18N = {
'Notifications stay in the app only. To have them reach mailboxes, set',
'Liczone w dniach kalendarzowych: soboty, niedziele i święta wliczają się do terminu. Gdy koniec terminu wypada w dzień wolny od pracy lub w sobotę, zapisana data się nie przesuwa, a kalendarz pokazuje, kiedy termin faktycznie upływa (art. 115 k.c.). Jeśli przesyłka jest zarejestrowana, policz termin z zakładki Korespondencja: zostanie z nią powiązany.':
'Counted in calendar days: Saturdays, Sundays and public holidays count towards the deadline. When the last day falls on a non-working day or a Saturday, the recorded date does not move; the calendar shows when the deadline actually expires (art. 115 of the Civil Code). If the item is recorded, count the deadline from the Correspondence tab: it will be linked to it.',
'Nowa ocena (zastąpi obecną)': 'New assessment (replaces the current one)',
'Nowa ocena (zastąpi obecną)': 'New assessment (replaces the current one)', 'Pierwsza ocena': 'First assessment',
'Zapisanie od razu zastąpi obecną ocenę nową, niezatwierdzoną. Poprzednia zostanie zachowana jako zastąpiona. Zapisać?':
'Saving replaces the current assessment with a new, unapproved one straight away. The previous one is kept as superseded. Save?',
'działu': 'department',
@@ -311,7 +319,8 @@ const I18N = {
'Przegląd': 'Overview', 'Strony': 'Parties', 'Czas pracy': 'Time', 'Pisma': 'Documents', 'AML': 'AML',
'Rozliczenia': 'Billing', 'Akta': 'Case file', 'Dostęp i chiński mur': 'Access & ethical wall',
'Akta sprawy': 'Case file', 'Utwórz akta sprawy': 'Create case file', 'Zapisz czas': 'Record time',
'Zarejestrowany czas': 'Recorded time', 'Do rozliczenia': 'Billable',
'Zarejestrowany czas': 'Recorded time', 'Czas rozliczalny': 'Billable time', 'Do rozliczenia': 'Billable',
'Szukaj po nazwie lub sygnaturze…': 'Search by name or case reference…',
'Wartość niezafakturowana': 'Unbilled value',
'Dziedzina': 'Practice area', 'Otwarta': 'Opened', 'Prowadzący': 'Responsible lawyer',
'Pozyskał': 'Originating lawyer', 'Rozliczenie': 'Fee arrangement', 'Moja stawka': 'My rate',
@@ -358,6 +367,7 @@ const I18N = {
'Dawne nazwy i formy odmienione — sprawdzenie konfliktu przeszukuje je tak samo jak nazwę główną.':
'Former names and inflected forms — the conflict check searches them just like the main name.',
'Powiązania': 'Relationships', 'Dodaj powiązanie': 'Add relationship',
'Wybierz podmiot.': 'Select a party.', 'Dodano powiązanie.': 'Relationship added.',
'Spółka matka, beneficjent rzeczywisty czy członek zarządu wpisany tutaj zostanie wykryty przy sprawdzeniu konfliktu,':
'A parent company, beneficial owner or board member recorded here will be found by the conflict check,',
'mimo że nazwy się nie pokrywają': 'even though the names do not match',
@@ -372,7 +382,8 @@ const I18N = {
'Rejestr ukrywa nazwiska osób fizycznych (zwraca np.': 'The register hides the names of natural persons (it returns e.g.',
'nazwiska trzeba wpisać ręcznie': 'the names have to be typed in by hand',
', żeby weszły do sprawdzania konfliktów.': ' so that they are included in the conflict check.',
'Edytuj podmiot': 'Edit party', 'Nowy klient / podmiot': 'New client / party',
'Edytuj podmiot': 'Edit party', 'Nowy klient / podmiot': 'New client / party', 'Zapisano podmiot.': 'Party saved.',
'Usunąć tę stronę ze sprawy?': 'Remove this party from the matter?',
'Pobierz z KRS': 'Fetch from KRS', 'Sprawdź NIP w Białej liście': 'Check NIP on the VAT White List',
'spółka matka': 'parent company', 'spółka zależna': 'subsidiary', 'beneficjent rzeczywisty': 'beneficial owner',
'członek organu': 'board member', 'małżonek': 'spouse', 'inne powiązanie': 'other relationship',
@@ -391,7 +402,7 @@ const I18N = {
'Etap': 'Stage', 'sprawa →': 'matter →', 'Brak zapytań.': 'No enquiries.',
'Ostatnie sprawdzenia konfliktu': 'Recent conflict checks', 'Trafienia': 'Hits', 'Wynik': 'Outcome',
'Brak sprawdzeń.': 'No checks.', 'brak konfliktu': 'no conflict', 'zgoda stron': 'waived by consent',
'odmowa': 'declined', 'do rozstrzygnięcia': 'to decide',
'odmowa': 'declined', 'do rozstrzygnięcia': 'to decide', 'Zapisano odmowę zlecenia.': 'Declined engagement recorded.',
'Przejdź do sprawy': 'Go to matter', 'Otwórz sprawę': 'Open matter', 'Zapytanie': 'Enquiry',
'Osoba kontaktowa': 'Contact person', 'Szacowana wartość': 'Estimated value', 'Strona przeciwna': 'Opposing party',
'Sprawdzenia konfliktu': 'Conflict checks', 'Nie wykonano jeszcze sprawdzenia.': 'No check has been run yet.',
@@ -405,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',
@@ -650,8 +662,8 @@ const I18N = {
'Operacja jest atomowa: przy błędzie baza wraca do stanu sprzed próby. Zamiar zostaje zapisany w dzienniku':
'The operation is atomic: on an error the database returns to its state before the attempt. The intention is recorded in the log',
'przywróceniem, bo przywracanie nadpisuje także dziennik.': 'the restore, because restoring also overwrites the log.',
'Wpisz': 'Type', 'PRZYWRÓĆ': 'PRZYWRÓĆ', ', aby potwierdzić': ' to confirm',
'Wpisz PRZYWRÓĆ, aby potwierdzić.': 'Type PRZYWRÓĆ to confirm.', 'Usunąć tę kopię zapasową?': 'Delete this backup?',
'Wpisz': 'Type', 'PRZYWRÓĆ': 'RESTORE', ', aby potwierdzić': ' to confirm',
'Wpisz PRZYWRÓĆ, aby potwierdzić.': 'Type RESTORE to confirm.', 'Usunąć tę kopię zapasową?': 'Delete this backup?',
'Zapisano ustawienia.': 'Settings saved.',
// ── AML ──
@@ -737,7 +749,7 @@ const I18N = {
// ── notifications, account, tokens ──
'wszystko przeczytane': 'all read', 'Brak powiadomień.': 'No notifications.',
'Oznacz wszystkie jako przeczytane': 'Mark all as read', 'Ustawienia powiadomień': 'Notification settings',
'Dotyczą wyłącznie Twojego konta': 'They apply to your account only', 'W konsoli': 'In the console', 'Na e-mail': 'By email',
'Dotyczą wyłącznie Twojego konta': 'They apply to your account only', 'W konsoli': 'In the console', 'W aplikacji': 'In the app', 'Na e-mail': 'By email',
'Instancja nie ma skonfigurowanej poczty — administrator musi ustawić': 'This instance has no mail configured — an administrator has to set',
'. Do tego czasu przełącznik nic nie zmienia.': '. Until then this switch changes nothing.',
'Wiadomość domyślnie nie wymienia klienta, sprawy ani terminu — poczta opuszcza kancelarię. Zakres ustala administrator.':
@@ -773,6 +785,75 @@ const I18N = {
'Utwórz token': 'Create token', 'Dla klientów desktopowych i skryptów — bez podawania hasła': 'For desktop clients and scripts — without giving a password',
'Tokeny są wyłączone na tym serwerze.': 'Tokens are disabled on this server.', 'Ostatnio użyty': 'Last used',
'unieważniony': 'revoked', 'Brak tokenów.': 'No tokens.', 'Token unieważniony.': 'Token revoked.',
// ── fixed vocabulary the BACKEND sends (labels, legal bases, notes) — not user data. Keyed on the
// exact strings in services/aml.py, fees.py, documents.py and rates.py: a label reworded there
// shows in Polish again until its key here is updated. ──
// aml.py: the risk factors, their bases and the catalogue's note
'Osoba zajmująca eksponowane stanowisko polityczne (PEP)': 'Politically exposed person (PEP)',
'Powiązanie z państwem trzecim wysokiego ryzyka': 'Link to a high-risk third country',
'Rozliczenia gotówkowe lub aktywami na okaziciela': 'Settlement in cash or in bearer assets',
'Złożona struktura właścicielska lub powiernictwo': 'Complex ownership structure or trust arrangement',
'Nawiązanie relacji bez osobistego kontaktu': 'Relationship established without face-to-face contact',
'Beneficjent rzeczywisty nieustalony lub wątpliwy': 'Beneficial owner not identified or doubtful',
'Obrót nieruchomościami lub przedsiębiorstwem': 'Sale or purchase of real estate or a business',
'Tworzenie lub prowadzenie spółki': 'Forming or running a company',
'Obsługa środków pieniężnych klienta': 'Handling client money',
'Klient nowy, bez historii współpracy': 'New client, no history with the firm',
'Klient znany kancelarii od lat, bez zastrzeżeń': 'Client known to the firm for years, no concerns',
'Podmiot publiczny lub spółka notowana na rynku regulowanym': 'Public body or company listed on a regulated market',
'art. 46 — wymaga środków wzmożonych i akceptacji kadry kierowniczej wyższego szczebla':
'art. 46 — requires enhanced due diligence and senior management approval',
'art. 43 ust. 2 pkt 3 i art. 44': 'art. 43(2)(3) and art. 44', 'art. 43 ust. 2 pkt 6': 'art. 43(2)(6)',
'art. 43 ust. 2 pkt 2': 'art. 43(2)(2)', 'art. 43 ust. 2 pkt 5': 'art. 43(2)(5)',
'art. 36 — obowiązek ustalenia beneficjenta rzeczywistego': 'art. 36 — duty to identify the beneficial owner',
'art. 2 ust. 1 pkt 14 lit. a': 'art. 2(1)(14)(a)', 'art. 2 ust. 1 pkt 14 lit. b–c': 'art. 2(1)(14)(b)–(c)',
'art. 2 ust. 1 pkt 14 lit. d': 'art. 2(1)(14)(d)', 'art. 33 ust. 3': 'art. 33(3)',
'art. 33 ust. 3 — okoliczności obniżające ryzyko': 'art. 33(3) — risk-reducing circumstances',
'art. 42 ust. 2 — przesłanki środków uproszczonych': 'art. 42(2) — grounds for simplified due diligence',
'Ocena ryzyka jest podpowiedzią, nie decyzją. Ustawa wymaga oceny indywidualnej — wynik należy zweryfikować i uzasadnić. Czynniki poniżej wskazują przepis, z którego wynikają.':
'The risk rating is a suggestion, not a decision. The Act requires an individual assessment — verify the result and give your reasons. Each factor below cites the provision it comes from.',
'2018-03-01 (t.j. Dz.U. 2023 poz. 1124, ze zm.)': '2018-03-01 (consolidated text Dz.U. 2023 item 1124, as amended)',
// fees.py: proceedings, representation stages, sources and the note. The statutory references in
// the basis lines ("art. 13 ust. 1 pkt 2 u.k.s.c.", "§ 2 pkt 5") are left as cited.
'Pozew (postępowanie zwykłe)': 'Statement of claim (ordinary proceedings)',
'Pozew w postępowaniu nakazowym': 'Statement of claim in order-for-payment proceedings',
'Pozew w EPU (e-sąd)': 'Statement of claim in the electronic payment-order procedure (EPU, e-court)',
'Apelacja': 'Appeal', 'Zażalenie': 'Interlocutory appeal', 'Skarga kasacyjna': 'Cassation appeal',
'I instancja': 'First instance', 'Apelacja — sąd okręgowy': 'Appeal — regional court',
'Apelacja — sąd apelacyjny': 'Appeal — court of appeal', 'Postępowanie kasacyjne': 'Cassation proceedings',
'Zażalenie — sąd okręgowy': 'Interlocutory appeal — regional court',
'Zażalenie — sąd apelacyjny / SN': 'Interlocutory appeal — court of appeal / Supreme Court',
'Stawki wymagają sprawdzenia z aktualnym brzmieniem u.k.s.c. i rozporządzenia MS. Wynik jest szacunkiem, nie opinią prawną.':
'Check the rates against the current text of the Court Costs Act (u.k.s.c.) and the Minister of Justice regulation. The result is an estimate, not a legal opinion.',
'Ustawa z 28.07.2005 r. o kosztach sądowych w sprawach cywilnych (u.k.s.c.)':
'Act of 28 July 2005 on court costs in civil cases (u.k.s.c.)',
'Rozporządzenie MS z 22.10.2015 r. w sprawie opłat za czynności adwokackie':
'Minister of Justice Regulation of 22 October 2015 on fees for advocates’ services',
'Rozporządzenie MS z 22.10.2015 r. w sprawie opłat za czynności radców prawnych':
'Minister of Justice Regulation of 22 October 2015 on fees for attorneys-at-law’s services',
'Ustawa z 16.11.2006 r. o opłacie skarbowej': 'Stamp Duty Act of 16 November 2006',
'ustawa o opłacie skarbowej, zał. cz. IV': 'Stamp Duty Act, annex, part IV',
// documents.py: the built-in templates and their bases (the documents themselves stay Polish)
'Pełnomocnictwo procesowe': 'Power of attorney for litigation',
'Wezwanie do zapłaty': 'Demand for payment', 'Pozew o zapłatę': 'Statement of claim for payment',
'art. 87 § 1 k.p.c. — pełnomocnikiem może być adwokat lub radca prawny':
'art. 87 § 1 of the Code of Civil Procedure — the attorney may be an advocate or an attorney-at-law',
'art. 455 k.c. — świadczenie bezterminowe staje się wymagalne po wezwaniu; wezwanie jest też warunkiem art. 187 § 1 pkt 3 k.p.c. (próba ugodowa)':
'art. 455 of the Civil Code — an obligation with no fixed date becomes due on demand; the demand also satisfies art. 187 § 1(3) of the Code of Civil Procedure (attempt at settlement)',
'art. 187 k.p.c. — wymogi formalne pozwu; wartość przedmiotu sporu: art. 19 i nast. k.p.c.':
'art. 187 of the Code of Civil Procedure — formal requirements of a statement of claim; value in dispute: art. 19 et seq. of the Code of Civil Procedure',
// rates.py: how a rate was resolved (a rate card's own name is carried through by a pattern below)
'stawka ustalona na sprawie': 'rate set on the matter', 'stawka domyślna kancelarii': 'firm default rate',
'brak stawki — ustal cennik lub stawkę na sprawie': 'no rate — set a rate card or a rate on the matter',
'stawka podstawowa cennika': 'rate card base rate',
// demo.js (the backend-less showcase deploy only): its login note and its refusals
'System zarządzania kancelarią — wersja demonstracyjna': 'Practice management for law firms — demo',
'Dane są wymyślone i zostają w tej przeglądarce. Dowolne hasło otwiera demo.':
'The data is made up and stays in this browser. Any password opens the demo.',
'To jest wersja demonstracyjna — dane są tylko w tej przeglądarce, więc tej operacji nie zapisuję. Pełna instalacja Sygny robi to naprawdę.':
'This is the demo — the data lives only in this browser, so this operation is not saved. A full Sygna installation does it for real.',
'Ten ekran nie ma danych w wersji demonstracyjnej.': 'This screen has no data in the demo.',
},
};
@@ -782,6 +863,8 @@ const I18N = {
which is what keeps user data out of translation. The result is still assigned as nodeValue or
an attribute, never as markup. */
const _D = '\\d{2}\\.\\d{2}\\.\\d{4}'; // fmtDate's dd.mm.yyyy
/* registers.py names its sources "KRS" and "Biała lista"; only the second needs English. */
const _regSource = (s) => (s === 'Biała lista' ? 'VAT White List' : s);
const _plural = (n, one, many) => `${n} ${Math.abs(Number(String(n).replace(',', '.'))) === 1 ? one : many}`;
const I18N_PATTERNS = [
[/^Terminy w ciągu (\d+) dni$/, (m) => `Deadlines in the next ${m[1]} days`],
@@ -808,9 +891,13 @@ const I18N_PATTERNS = [
[/^Sprawdzenie: (.+)$/, (m) => `Check: ${m[1]}`],
[/^Pokazano najstarsze (\d+) z (\d+) — najdłużej leżące są najpilniejsze\.$/,
(m) => `Showing the oldest ${m[1]} of ${m[2]} — the ones waiting longest are the most urgent.`],
[/^(\S+?)(?: — stan z (.+?))?: (?:uzupełniono (.+)|(wszystkie pola były już wypełnione))$/,
(m) => `${m[1]}${m[2] ? ` — as of ${m[2]}` : ''}: ${m[3] ? `filled in ${m[3]}` : 'all fields were already filled in'}`],
[/^(Biała lista|\S+?)(?: — stan z (.+?))?: (?:uzupełniono (.+)|(wszystkie pola były już wypełnione))$/,
(m) => `${_regSource(m[1])}${m[2] ? ` — as of ${m[2]}` : ''}: ${m[3] ? `filled in ${m[3]}` : 'all fields were already filled in'}`],
[/^stan z (.+)$/, (m) => `as of ${m[1]}`],
// the register lookup's header line: "<source>: <name> · <legal form>"; name and form are register data
[/^Biała lista: (.+)$/, (m) => `VAT White List: ${m[1]}`],
[/^Pokazano pierwsze (\d+) z (\d+\+?) faktur\.$/, (m) => `Showing the first ${m[1]} of ${m[2]} invoices.`],
[/^Podstawa: (.+)$/, (m) => `Basis: ${_trKey(m[1]) || m[1]}`],
[/^adres e-Doręczeń: (.+)$/, (m) => `e-Delivery address: ${m[1]}`],
[/^\)\. Znaleziono (\d+) osób w organach —$/, (m) => `). Found ${_plural(m[1], 'person', 'people')} on its boards —`],
[/^Rachunki w Białej liście \((\d+)\) — sprawdź przed przelewem$/,
@@ -823,8 +910,8 @@ const I18N_PATTERNS = [
[/^Zapłacono (.+), pozostało (.+)$/, (m) => `Paid ${m[1]}, outstanding ${m[2]}`],
[/^KSeF: (.+) — konektor powstanie w etapie 2\.$/, (m) => `KSeF: ${m[1]} — the connector comes in phase 2.`],
[/^Opłata skarbowa od pełnomocnictwa × (\d+)$/, (m) => `Stamp duty on power of attorney × ${m[1]}`],
[/^(.+) — (\d+\/\d+) opłaty$/, (m) => `${m[1]} — ${m[2]} of the fee`],
[/^Wersja stawek: (.+)$/, (m) => `Schedule version: ${m[1]}`],
[/^(.+) — (\d+\/\d+) opłaty$/, (m) => `${_trKey(m[1]) || m[1]} — ${m[2]} of the fee`],
[/^Wersja stawek: (.+)$/, (m) => `Schedule version: ${m[1].split(' · ').map((x) => _trKey(x) || x).join(' · ')}`],
[/^klient: (.+)$/, (m) => `client: ${m[1]}`],
[new RegExp(`^(${_D}) – bezterminowo$`), (m) => `${m[1]} – open-ended`],
[/^Język: (PL|EN)$/, (m) => `Language: ${m[1]}`],
@@ -859,6 +946,21 @@ const I18N_PATTERNS = [
[new RegExp(`^(?:(.+) — )?Termin przypada w dniu wolnym — zgodnie z art\\. 115 k\\.c\\. upływa (${_D})\\.$`),
(m) => `${m[1] ? m[1] + ' — ' : ''}The deadline falls on a non-working day — under art. 115 of the Civil Code it expires on ${m[2]}.`],
[/^(\d+) terminów · (\d+) rozpraw$/, (m) => `${_plural(m[1], 'deadline', 'deadlines')} · ${_plural(m[2], 'hearing', 'hearings')}`],
// deadlines.py writes the basis of a deadline counted from a service date
[/^doręczenie (\d{4}-\d{2}-\d{2}) \+ (\d+) dni$/, (m) => `service ${m[1]} + ${_plural(m[2], 'day', 'days')}`],
// rates.py: "cennik kancelarii „<card name>” (osoba | stopień: <grade> | stawka podstawowa cennika)"
[/^(— )?cennik (sprawy|klienta|kancelarii) „(.+)” \((.+)\)$/, (m) => {
const how = /^stopień: (.+)$/.exec(m[4]);
const basis = how ? `grade: ${_trKey(how[1]) || how[1]}` : _trKey(m[4]) || m[4];
return `${m[1] || ''}${{ sprawy: 'matter', klienta: 'client', kancelarii: 'firm' }[m[2]]} rate card “${m[3]}” (${basis})`;
}],
[/^(.+) · § 2 \(stawka minimalna\)$/, (m) => `${m[1]} · § 2 (minimum rate)`],
// The rest wrap a backend label in a fixed frame (an option's fraction or percentage, a multiplier,
// a dash before a basis). Each answers null — leave the node — unless the label itself is known.
[/^(.+) \((\d+\/\d+)\)$/, (m) => { const v = _trKey(m[1]); return v == null ? null : `${v} (${m[2]})`; }],
[/^(.+) — (\d+)%$/, (m) => { const v = _trKey(m[1]); return v == null ? null : `${v} — ${m[2]}%`; }],
[/^(.+) × (\d+)$/, (m) => { const v = _trKey(m[1]); return v == null ? null : `${v} × ${m[2]}`; }],
[/^— (.+)$/, (m) => { const v = _trKey(m[1]); return v == null ? null : `— ${v}`; }],
];
let LANG = (function () {
try { const s = localStorage.getItem('sygna_lang'); if (s === 'en' || s === 'pl') return s; } catch {}
@@ -1263,7 +1365,7 @@ function deadlineTable(rows, withMatter) {
</tr></thead><tbody>${rows.map((d) => {
const sev = d.overdue ? 3 : (d.days_left <= 3 ? 2 : 1);
return `<tr class="click" onclick="location.hash='#/matters/${d.matter_id}?tab=deadlines'">
<td><span class="stripe s${sev}">${esc(d.title)}</span></td>
<td><span class="stripe s${sev}">${rowLink(`#/matters/${d.matter_id}?tab=deadlines`, esc(d.title))}</span></td>
${withMatter ? `<td class="faint tiny">${esc(d.matter_reference || '')} ${esc(d.matter_name || '')}</td>` : ''}
<td>${fmtDate(d.due_date)}</td>
<td class="num">${d.overdue ? `<span class="chip err">${fmtDays(d.days_left)} po terminie</span>` : fmtDays(d.days_left)}</td>
@@ -1299,7 +1401,7 @@ async function viewMatters(C, q) {
+ (rows.length ? `<div class="card"><div class="tablewrap"><table><thead><tr>
<th>Sygnatura wewn.</th><th>Sprawa</th><th>${clientWord()}</th><th>Sygn. akt</th><th>Status</th>
</tr></thead><tbody>${rows.map((m) => `<tr class="click" onclick="location.hash='#/matters/${m.id}'">
<td class="mono">${esc(m.reference)}</td>
<td class="mono">${rowLink(`#/matters/${m.id}`, esc(m.reference))}</td>
<td>${esc(m.name)}<div class="faint tiny">${esc(m.practice_area || '')}</div></td>
<td>${esc(m.client_name || '—')}</td>
<td class="mono">${esc(m.case_signature || '—')}</td>
@@ -1547,7 +1649,7 @@ async function viewParties(C, q) {
+ (rows.length ? `<div class="card"><div class="tablewrap"><table><thead><tr>
<th>Nazwa</th><th>Rodzaj</th><th>NIP</th><th>KRS</th><th>Ryzyko</th>
</tr></thead><tbody>${rows.map((p) => `<tr class="click" onclick="location.hash='#/parties/${p.id}'">
<td>${esc(p.name)}${p.is_pep ? ' <span class="chip warn">PEP</span>' : ''}</td>
<td>${rowLink(`#/parties/${p.id}`, esc(p.name))}${p.is_pep ? ' <span class="chip warn">PEP</span>' : ''}</td>
<td class="tiny faint">${p.kind === 'person' ? 'osoba fizyczna' : 'podmiot'}</td>
<td class="mono">${esc(p.nip || '—')}</td>
<td class="mono">${esc(p.krs || '—')}</td>
@@ -1622,13 +1724,13 @@ async function viewIntake(C) {
+ (pending.length ? `<div class="card"><h3>Konflikty do rozstrzygnięcia<span class="n">${pending.length}</span></h3>
<div class="banner warn">Dopóki sprawdzenie nie zostanie rozstrzygnięte, sprawy nie da się otworzyć.</div>
<div class="tablewrap" style="margin-top:12px"><table><tbody>${pending.map((c) => `<tr class="click" onclick="openConflictResult('${c.id}')">
<td>${esc(c.subject)}<div class="faint tiny">przeciwko: ${esc(c.adverse_names || '—')}</div></td>
<td>${rowBtn('openConflictResult', c.id, esc(c.subject))}<div class="faint tiny">przeciwko: ${esc(c.adverse_names || '—')}</div></td>
<td class="num"><span class="chip err">${c.hit_count} trafień</span></td>
<td class="tiny faint">${fmtDateTime(c.created_at)}</td></tr>`).join('')}</tbody></table></div></div>` : '')
+ (leads.length ? `<div class="card"><h3>Zapytania</h3><div class="tablewrap"><table><thead><tr>
<th>Klient</th><th>Dziedzina</th><th>Źródło</th><th>Etap</th><th></th>
</tr></thead><tbody>${leads.map((l) => `<tr class="click" onclick="location.hash='#/intake/${l.id}'">
<td>${esc(l.name)}<div class="faint tiny">${esc(l.contact_name || '')}</div></td>
<td>${rowLink(`#/intake/${l.id}`, esc(l.name))}<div class="faint tiny">${esc(l.contact_name || '')}</div></td>
<td>${esc(l.practice_area || '—')}</td>
<td class="tiny faint">${esc(l.source || '—')}</td>
<td><span class="chip ${l.stage === 'won' ? 'ok' : (l.stage === 'lost' ? '' : 'warn')}">${esc(LEAD_STAGE[l.stage] || l.stage)}</span></td>
@@ -1637,7 +1739,7 @@ async function viewIntake(C) {
+ `<div class="card"><h3>Ostatnie sprawdzenia konfliktu<span class="n">${Math.min(checks.length, 25)}</span></h3>
${checks.length ? `<div class="tablewrap"><table><thead><tr><th>Podmiot</th><th>Trafienia</th><th>Wynik</th><th>Kiedy</th></tr></thead><tbody>
${checks.slice(0, 25).map((c) => `<tr class="click" onclick="openConflictResult('${c.id}')">
<td>${esc(c.subject)}</td><td class="num">${c.hit_count}</td>
<td>${rowBtn('openConflictResult', c.id, esc(c.subject))}</td><td class="num">${c.hit_count}</td>
<td>${conflictChip(c.outcome)}</td><td class="tiny faint">${fmtDateTime(c.created_at)}</td></tr>`).join('')}
</tbody></table></div>` : '<div class="empty">Brak sprawdzeń.</div>'}</div>`;
}
@@ -1668,7 +1770,7 @@ async function viewLead(C, id) {
</div>
<div class="card"><h3>Sprawdzenia konfliktu<span class="n">${d.checks.length}</span></h3>
${d.checks.length ? `<div class="tablewrap"><table><tbody>${d.checks.map((c) => `<tr class="click" onclick="openConflictResult('${c.id}')">
<td>${esc(c.subject)}</td><td class="num">${c.hit_count} trafień</td><td>${conflictChip(c.outcome)}</td>
<td>${rowBtn('openConflictResult', c.id, esc(c.subject))}</td><td class="num">${c.hit_count} trafień</td><td>${conflictChip(c.outcome)}</td>
<td class="tiny faint">${fmtDateTime(c.created_at)}</td></tr>`).join('')}</tbody></table></div>`
: '<div class="empty">Nie wykonano jeszcze sprawdzenia.</div>'}</div>`;
}
@@ -1939,7 +2041,7 @@ async function renderMatterBilling(el, matterId) {
${d.invoices.length ? `<div class="tablewrap"><table><thead><tr>
<th>Numer</th><th>Rodzaj</th><th>Wystawiona</th><th class="num">Brutto</th><th class="num">Pozostało</th><th>Status</th><th></th>
</tr></thead><tbody>${d.invoices.map((i) => `<tr class="click" onclick="openInvoice('${i.id}')">
<td class="mono">${esc(i.number || '—')}</td>
<td class="mono">${rowBtn('openInvoice', i.id, esc(i.number || '—'), i.number ? '' : 'Faktura bez numeru')}</td>
<td class="tiny">${esc(INVOICE_KIND[i.kind] || i.kind)}</td>
<td>${i.issued_on ? fmtDate(i.issued_on) : '—'}</td>
<td class="num">${fmtMoney(i.gross_minor, i.currency)}</td>
@@ -2473,7 +2575,7 @@ async function viewReports(C, q) {
${a.invoices.length ? `<div class="tablewrap" style="margin-top:12px"><table><thead><tr>
<th>Faktura</th><th>Sprawa</th><th>Termin</th><th class="num">Po terminie</th><th class="num">Pozostało</th>
</tr></thead><tbody>${a.invoices.slice(0, 15).map((i) => `<tr class="click" onclick="openInvoice('${i.invoice_id}')">
<td class="mono">${esc(i.number || '—')}</td>
<td class="mono">${rowBtn('openInvoice', i.invoice_id, esc(i.number || '—'), i.number ? '' : 'Faktura bez numeru')}</td>
<td class="tiny">${esc(i.matter_reference)} ${esc(i.matter_name)}</td>
<td>${i.due_on ? fmtDate(i.due_on) : '—'}</td>
<td class="num">${i.days_overdue ? `<span class="chip ${i.days_overdue > 90 ? 'err' : 'warn'}">${i.days_overdue} dni</span>` : '—'}</td>
@@ -2486,7 +2588,7 @@ async function viewReports(C, q) {
${d.profitability.length ? `<div class="tablewrap"><table><thead><tr>
<th>Sprawa</th><th class="num">Zafakturowane</th><th class="num">Koszt czasu</th><th class="num">Wydatki własne</th><th class="num">Marża</th><th class="num">%</th>
</tr></thead><tbody>${d.profitability.map((p) => `<tr class="click" onclick="location.hash='#/matters/${p.matter_id}?tab=billing'">
<td>${esc(p.reference)} ${esc(p.name)}${p.incomplete ? ' <span class="chip warn">brak stawki kosztowej</span>' : ''}</td>
<td>${rowLink(`#/matters/${p.matter_id}?tab=billing`, `${esc(p.reference)} ${esc(p.name)}`)}${p.incomplete ? ' <span class="chip warn">brak stawki kosztowej</span>' : ''}</td>
<td class="num">${fmtMoney(p.billed_minor)}</td>
<td class="num">${fmtMoney(p.cost_of_time_minor)}</td>
<td class="num">${fmtMoney(p.unrecharged_expenses_minor)}</td>
@@ -2850,7 +2952,7 @@ async function addUbo(matterId) {
}
async function saveAml(matterId, replacesCurrent) {
if (replacesCurrent && !confirm('Zapisanie od razu zastąpi obecną ocenę nową, niezatwierdzoną. Poprzednia zostanie zachowana jako zastąpiona. Zapisać?')) return;
if (replacesCurrent && !confirm(_tr('Zapisanie od razu zastąpi obecną ocenę nową, niezatwierdzoną. Poprzednia zostanie zachowana jako zastąpiona. Zapisać?'))) return;
const factors = [...document.querySelectorAll('.am-f')].filter((x) => x.checked).map((x) => x.value);
try {
await api('POST', `/matters/${matterId}/aml`, {
@@ -2976,8 +3078,9 @@ async function previewDocument(matterId) {
if (_isCustom()) {
/* A firm's own .docx is filled in place, keeping its letterhead and styles — there is no
plain-text version of it to show, and faking one would misrepresent what comes out. */
$('dgPreview').textContent = 'Podgląd jest dostępny tylko dla wzorów wbudowanych. '
+ 'Szablon kancelarii zachowuje własny papier firmowy i formatowanie — pobierz go, żeby zobaczyć wynik.';
// _tr by hand: the preview is a <pre>, which localize() leaves alone as raw content
$('dgPreview').textContent = _tr('Podgląd jest dostępny tylko dla wzorów wbudowanych. '
+ 'Szablon kancelarii zachowuje własny papier firmowy i formatowanie — pobierz go, żeby zobaczyć wynik.');
$('dgBasis').textContent = '';
$('dgWarn').innerHTML = '';
return;
@@ -3115,7 +3218,8 @@ function confirmRestore(name) {
function doRestore(name) {
guard(async () => {
if (($('rsConfirm').value || '').trim().toUpperCase() !== 'PRZYWRÓĆ') {
// The word shown is translated with the page, so both spellings of it unlock the restore.
if (!['PRZYWRÓĆ', 'RESTORE'].includes(($('rsConfirm').value || '').trim().toUpperCase())) {
throw new Error('Wpisz PRZYWRÓĆ, aby potwierdzić.');
}
const r = await api('POST', '/admin/backup/restore', { name });
@@ -3194,11 +3298,12 @@ function searchBadge(item) {
}
function openSearch(prefill) {
rememberOpener();
state._search = { flat: [], sel: 0, seq: 0, timer: null };
$('modalRoot').innerHTML = `<div class="scrim search-scrim" onclick="if(event.target===this)closeModal()">
<div class="modal search-modal" role="dialog" aria-modal="true" aria-label="Szukaj">
<div class="sin">${svg(ICN.search, 18)}
<input id="searchQ" type="search" autocomplete="off" spellcheck="false"
<input id="searchQ" type="search" autocomplete="off" spellcheck="false" aria-label="Szukaj"
placeholder="Sprawa, klient, sygnatura, NIP, numer faktury…"
value="${esc(prefill || '')}">
</div>
@@ -3208,6 +3313,7 @@ function openSearch(prefill) {
const input = $('searchQ');
input.addEventListener('input', () => searchDebounced(input.value));
input.addEventListener('keydown', searchKey);
$('app').inert = true;
input.focus();
input.select();
if (input.value.trim().length >= 2) searchRun(input.value);
@@ -3312,8 +3418,24 @@ function searchGo(idx) {
else location.hash = hit.href;
}
function closeModal() { $('modalRoot').innerHTML = ''; }
/* A dialog keeps keyboard focus inside itself and hands it back when it closes. aria-modal alone
does not stop Tab, so the page behind is inert while a dialog is open. The opener is taken
BEFORE the page goes inert — an inert ancestor takes focus away from it — and a dialog opened
from inside another keeps the first one's opener. */
let _modalOpener = null;
function rememberOpener() {
const a = document.activeElement;
if (!_modalOpener && a && a !== document.body && !$('modalRoot').contains(a)) _modalOpener = a;
}
function closeModal() {
const wasOpen = !!$('modalRoot').innerHTML;
$('modalRoot').innerHTML = '';
$('app').inert = false;
if (wasOpen && _modalOpener && document.contains(_modalOpener)) _modalOpener.focus();
_modalOpener = null;
}
function modal(title, sub, bodyHtml, actionsHtml, opts) {
rememberOpener();
$('modalRoot').innerHTML = `<div class="scrim" onclick="if(event.target===this)closeModal()">
<div class="modal ${opts && opts.wide ? 'wide' : ''}" role="dialog" aria-modal="true" aria-labelledby="modalTitle">
<h3 id="modalTitle">${esc(title)}</h3>${sub ? `<div class="msub">${esc(sub)}</div>` : ''}
@@ -3321,13 +3443,19 @@ function modal(title, sub, bodyHtml, actionsHtml, opts) {
<div class="acts">${actionsHtml}</div>
</div></div>`;
localize($('modalRoot'));
const first = $('modalRoot').querySelector('input,select,textarea');
$('app').inert = true;
// A field if there is one; otherwise the dialog's first control, so a keyboard user starts inside.
// Only one that is rendered: a display:none row (the account sheet's .m-only ones on a desktop)
// takes no focus, and focus would stay behind on the now-inert page.
const shown = (el) => el.getClientRects().length > 0;
const first = [...$('modalRoot').querySelectorAll('input:not([type=hidden]),select,textarea')].find(shown)
|| [...$('modalRoot').querySelectorAll('.modal button, .modal a[href]')].find(shown);
if (first) first.focus();
}
function modalError(msg) {
const b = $('modalBody');
let el = b.querySelector('.banner.err');
if (!el) { el = document.createElement('div'); el.className = 'banner err'; el.style.marginBottom = '12px'; b.prepend(el); }
if (!el) { el = document.createElement('div'); el.className = 'banner err'; el.setAttribute('role', 'alert'); el.style.marginBottom = '12px'; b.prepend(el); }
el.textContent = msg;
}
async function guard(fn) {
@@ -3360,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>`;
}
+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>